Tag Archives: SignalR

SignalR in ASP .NET Core 3.1

By Shahed C on May 11, 2020

This is the nineteenth of a new series of posts on ASP .NET Core 3.1 for 2020. In this series, we’ll cover 26 topics over a span of 26 weeks from January through June 2020, titled ASP .NET Core A-Z! To differentiate from the 2019 series, the 2020 series will mostly focus on a growing single codebase (NetLearner!) instead of new unrelated code snippets week.

Previous post:

NetLearner on GitHub:

In this Article:

S is for SignalR

SignalR has been around for 7+ years now, allowing ASP .NET developers to easily include real-time features in their web applications. SignalR Core has been available in ASP .NET Core since v2.1, as a cross-platform solution to add real-time features to web apps and more!

In this article, we’ll go over SignalR concepts, using a new sample I developed to allow web users to vote in a real-time online poll. Before you begin, take a look at the sample code project on GitHub:

Back in 2018, I ran a couple of polls on Facebook and Twitter to see what the dev community wanted to see. On Twitter, the #1 choice was “Polling/Voting app” followed by “Planning Poker App” and “Real-time game”. On Facebook, the #1 choice was “Real-time game” followed by “Polling/voting app”. As a result, I decided to complement this article with a polling sample app.

More importantly, Brady Gaster suggested that the sample app should definitely be “Not. Chat.” 🙂

In the sample project, take a look at the SignalRPoll project to see how the polling feature has been implemented. In order to create a project from scratch, you’ll be using both server-side and client-side dependencies.

SignalR poll in action
SignalR poll in action

If you need a starter tutorial, check out the official docs:

Dependencies

Visual Studio showing csproj + dependencies
Visual Studio showing csproj + dependencies

The Server-Side dependencies for SignalR Core are available via the Microsoft.AspNetCore.App package so this is a freebie when you create a new 3.1 web app project. In your server-side code, you can use the following namespace:

using Microsoft.AspNetCore.SignalR;

This will give you access to SignalR classes such as Hub and Hub<T> for your SignalR hub to derive from. In the sample project, the PollHub class inherits from the Hub class. Hub<T> can be used for strongly-typed SignalR hubs.

The Client Side dependencies for SignalR Core have to be added manually. Simply right-click on your web app project and select Add | Client-Side Library. In the popup that appears, select a provider (such as “unpkg”) and enter a partial search term for Library, so that you can ideally pick the latest stable version.

Steps to add client library via LibMan (aka Library Manager):

  • Right-click project in Solution Explorer
  • Select Add | Client-Side Library

In the popup that appears, select/enter the following:

  • Provider: choose from cdnjs, filesystem, unpkg
  • Library search term: @aspnet/signalr@1… pick latest stable if desired
  • Files: At a minimum, choose specific files signalr.js and/or its minified equivalent
Visual Studio, showing libman.json with client-side references
Visual Studio, showing libman.json with client-side references

If you need help with adding client-side references, check out this earlier blog post in this A-Z series:

Server-Side Hub

In the sample app, the PollHub class has a simple SendMessage() method with a few parameters. Derived from the sample Chat application, it starts with the user’s desired “user” value and a custom “message” that can be passed to the SignalR Hub. For the the Captain Marvel/America poll, the method also passes an Id and Value for the selected radio button.

public class PollHub : Hub
{
   public async Task SendMessage(string user, string message, string myProjectId, string myProjectVal)
   {
      await Clients.All.SendAsync("ReceiveMessage", user, message, myProjectId, myProjectVal);
   }
}

To ensure that the SendMessage method from the server has a trigger on the client-side, the client-side code must invoke the method via the SignalR connection created with HubConnectionBuilder() on the client side. Once called, the above code will send a call to ReceiveMessage on all the clients connected to the Hub.

Client-Side

On the client-side, the JavaScript file poll.js handles the call from the browser to the server, and receives a response back from the server as well. The following code snippets highlight some important areas:

var connection = new signalR.HubConnectionBuilder().withUrl("/pollHub").build(); 
... 
connection.on("ReceiveMessage", function (user, message, myProjectId, myProjectVal) { 
   ... 
   document.getElementById(myProjectId + 'Block').innerHTML += chartBlock;
}); 
...

document.getElementById("sendButton").addEventListener("click", function (event) {
   ...
   connection.invoke("SendMessage", user, message, myProjectId, myProjectVal)
   ... 
});

The above snippets takes care of the following:

  1. Creates a new connection objection using HubConnectionBuilder with a designated route
  2. Uses connection.on to ensure that calls to ReceiveMessage come back from the server
  3. Sets the innerHTML of a <span> block to simulate a growing bar chart built with small blocks
  4. Listens for a click event from the sendButton element on the browser
  5. When the sendButton is clicked, uses connection.invoke() to call SendMessage on the server

Configuration

The configuration for the SignalR application is set up in the Startup.cs methods ConfigureServices() and Configure(), as you may expect.

public void ConfigureServices(IServiceCollection services) 
{
   ...
   services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   ...
   app.UseEndpoints(endpoints =>
   {
      ... 
      endpoints.MapHub<PollHub>("/pollHub");
   });
   ...
}

The above code takes care of the following:

  1. the ConfigureServices() method adds SignalR to the ASP.NET Core dependency injection system with a call to AddSignalR()
  2. the Configure() method adds SignalR to the middleware pipeline, while setting up the necessary route(s), using a call to UseSignalR().

At the time of this writing, I have more than one route set up for multiple hubs. For the polling app, we only need the call to MapHub<PollHub>() that sets up the route “/pollHub“. You may recall this route from the client-side JavaScript code where the initial connection is set up.

For streaming fragments of data over time, you should also take a look at Streaming in SignalR Core:

Running the App

To run the app, simply run the SignalRPoll app Visual Studio or from the command line. Then, click the Poll item in the top menu to go to the Poll page. This page is a simple Razor page that contains all the HTML elements necessary to display the poll. It also includes <script> references to jQuery, SignalR and poll.js client-side references.

NOTE: Even though I am using jQuery for this sample, please note that jQuery is not required to use SignalR Core. On a related note, you can also configure Webpack and TypeScript for a TypeScript client if you want.

This GIF animation below illustrates the poll in action. To record this GIF of 1 browser window, I also launched additional browser windows (not shown) pointing to the same URL, so that I could vote several times.

SignalR poll in action
SignalR poll in action

In a real world scenario, there are various ways to prevent a user from voting multiple times. Some suggestions include:

  • Disable the voting button as soon as the user has submitted a vote.
  • Use a cookie to prevent the user from voting after reloading the page.
  • Use authentication to prevent a user from voting after clearing cookies or using a different browser.

For more information on authenticating and authorizing users, check out the official docs:

Azure SignalR Service

Azure SignalR Service is a fully-managed service available in Microsoft’s cloud-hosted Azure services, that allows you to add real-time functionality and easily scale your apps as needed. Using Azure SignalR Service is as easy as 1-2-3:

  1. Add a reference to the Azure SignalR Service SDK
  2. Configure a connection string
  3. Call services.AddSignalR().AddAzureSignalR() and app.UseAzureSignalR in Startup.cs

For more information on Azure SignalR Service, check out the official docs and tutorials:

Packaging Changes in 3.x

You may have heard that ASP .NET Core 3.0 changed the way packages are made available to developers. So how does this affect SignalR for 3.x projects? Here is a recap from the official announcement:

  • Microsoft “will stop producing many of the NuGet packages that we have been shipping since ASP.NET Core 1.0. The API those packages provide are still available to apps by using a <FrameworkReference> to Microsoft.AspNetCore.App. This includes commonly referenced API, such as Kestrel, Mvc, Razor, and others.”
  • “This will not apply to all binaries that are pulled in via Microsoft.AspNetCore.App in 2.x.”
  • Notable exceptions include: The SignalR .NET client will continue to support .NET Standard and ship as NuGet package because it is intended for use on many .NET runtimes, like Xamarin and UWP.”

Sourcehttps://github.com/aspnet/Announcements/issues/325

References:

Blazor Full-Stack Web Dev in ASP .NET Core

By Shahed C on January 14, 2019

This is the second of a new series of posts on ASP .NET Core for 2019. In this series, we’ll cover 26 topics over a span of 26 weeks from January through June 2019, titled A-Z of ASP .NET Core!

ASPNETCoreLogo-300x267 A – Z of ASP .NET Core!

In this Article:

B is for Blazor

In a previous post, I covered various types of Pages that you will see when developing ASP .NET Core web applications. In this article, we will take a look at a Blazor sample and see how it works. Blazor (Browser + Razor) is an experimental .NET web framework which allows you to write full-stack C# .NET web applications that run in a web browser, using WebAssembly.

NOTE: Server-slide Blazor (aka Razor Components) allows you to run your Blazor app on the server, while using SignalR for the connection to the client, but we will focus on client-only Blazor in this article.

To get started by yourself, follow the official instructions to set up your development environment and then build your first app. In the meantime, you may download the sample code from my GitHub repo.

Web Blazor projects on GitHub: https://github.com/shahedc/BlazorDemos

Specifically, take a look at the Blazor Dice project, which you can use to generate random numbers using dice graphics. The GIF below illustrates the web app in action!

blazor-dice

Entry Point and Configuration

Let’s start with Program.cs, the entry point of your application. Just like any ASP .NET Core web application, there is a Main method that sets up the entry point. A quick call to CreateHostBuilder() in the same file ensures that two things will happen: The Blazor Web Assembly Host will call its own CreateDefaultBuilder() method (similar to how it works in a typical ASP .NET Core web application) and it will also call UseBlazorStartup() to identify the Startup class where the application is configured.

public class Program
{
   public static void Main(string[] args)
   {
      CreateHostBuilder(args).Build().Run();
   }

   public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
      BlazorWebAssemblyHost.CreateDefaultBuilder()
      .UseBlazorStartup<Startup>();
}

Note that the Startup class doesn’t have to be called Startup, but you do have to tell your application what it’s called. In the Startup.cs file, you will see the familiar ConfigureServices() and Configure() methods, but you won’t need any of the regular MVC-related lines of code that set up the HTTP pipeline for an MVC (or Razor Pages) application. Instead, you just need a minimum of 1 line of  code that adds the client side “App”. (This is different for server-hosted apps.)

public class Startup
{
   public void ConfigureServices(IServiceCollection services)
   {
   } 

   public void Configure(IBlazorApplicationBuilder app)
   {
      app.AddComponent<App>("app");
   }
}

Note that the Configure() method takes in an app object of type IBlazorApplicationBuilder, unlike the usual IApplicationBuilder we see in regular ASP .NET Core web apps.  When it adds the App component, it specifies the client-side app with the name “app” in double quotes.

UPDATE: In the above statement, I’m referring to “app” as “the client-side app”. In the comments section, I explained to a reader (Jeff) how this refers to the HTML element in index.html, one of the 3 locations where you would have to change the name if you want to rename it. Another reader (Issac) pointed out that “app” should be described as “a DOM Element Selector Identifier for the element” in that HTML file, which Angular developers should also recognize. Issac is correct, as it refers to the <app> element in the index.html file.

NAME CHANGES: Issac also pointed out that “IBlazorApplicationBuilder has already become IComponentsApplicationBuilder”. This refers to recent name changes on Jan 18, 2019. I will periodically make changes to the articles and code samples in this series. In the meantime, please refer to the following GitHub commit:

NOTE: There is an App.cshtml file in the project root that specifies the AppAssembly as a temporary measure, but the app config in this file is expected to move to Program.cs at a future date. 

Continue reading

Happy New Year 2019!

By Shahed C on December 27, 2018

If you’ve been following my ASP .NET Core blog series from October to December 2018, you may have noticed a little surprise. The first letter of each article spells out the words HAPPY NEW YEAR!

happy-new-year-2019

Congratulations! You’ve made it this far! 😀

Not just a gimmick, this blog series kicks off with a “Hello World” intro to ASP .NET Core, reveals a new open-source learning app (NetLearner) halfway through, breaks all my previous blog viewership records with December’s .NET Core 3.0 recap after Connect(); 2018 and finally wraps with up a SignalR writeup (and a new sample app that’s not chat!)

Blog viewership numbers in 2018:

  • Jan – Sep: ~2k/month with little or no updates
  • Oct: ~6k
  • Nov: ~8k
  • Dec: 36k+ (as of Dec 27, when this blog post was published)
    • 40k+ as of Dec 31 midnight

blog-stats-2018

Special thanks to the following people at Microsoft for all your guidance, motivation, inspiration, feedback and suggestions:

 

Also, I really appreciate the support from the Visual Studio team with their tweets:

@VisualStudio on Dec 18: https://twitter.com/VisualStudio/status/1075086548712988673

@VisualStudio on Dec 20: https://twitter.com/VisualStudio/status/1075804272279867397

During this blog series, I also participated in Matthew Groves’ 2nd annual C# Advent 2018, which ran daily from Dec 1 – Dec 25. Check out his website to see dozens of new blog posts from many talented C# developers and bloggers:

Hope you enjoyed the 2018 series and will stay tuned for what’s to come in 2019:

  • A-Z with ASP .NET Core 2019 Series
    • Jan – June 2019: 26 weeks of ASP .NET Core posts
    • Will be combined to form a living breathing ebook
    • Will be updated to align with .NET Core 3.0 release

 

Real-time ASP .NET Core Web Apps with SignalR

By Shahed C on December 23, 2018

This is the twelfth of a new series of posts on ASP .NET Core. In this post, we’ll learn about the use of SignalR to build real-time functionality in your ASP NET Core web apps. SignalR can also be used to add real-time functionality to desktop applications, mobile apps and Azure Functions.

ASPNETCoreLogo-300x267

In this Article:

What is SignalR?

SignalR has been around for 5+ years now, allowing ASP .NET developers to easily include real-time features in their web applications. Fast forward to 2018, SignalR Core is now available with ASP .NET Core (as of 2.1) as a cross-platform solution to add real-time features to web apps and more!

In this article, we’ll go over SignalR concepts, using a new sample I developed to allow web users to vote in a real-time online poll. Before you begin, take a look at the sample code project on GitHub:

Web SignalR Core Samples on GitHub: https://github.com/shahedc/SignalRCoreSamples

I ran a couple of polls on Facebook and Twitter to see what the dev community wanted to see. On Twitter, the #1 choice was “Polling/Voting app” followed by “Planning Poker App” and “Real-time game”. On Facebook, the #1 choice was “Real-time game” followed by “Polling/voting app”. As a result, I’ve decide to complement this article with a polling sample app, and I plan to work on other ideas in 2019.

More importantly, Brady Gaster suggested that the sample app should definitely be “Not. Chat.” 🙂

In the sample project, take a look at the SignalRPoll project to see how the polling feature has been implemented. In order to create a project from scratch, you’ll be using both server-side and client-side dependencies.

Continue reading

Build 2018 Videos for .NET Developers

By Shahed C on May 10, 2018

Hope you got a chance to watch some of the Build 2018 keynotes and sessions, either in person or online:

Build2018-logo

If you’re looking for videos on .NET Core, ASP.NET Core and the future of C# and .NET, here’s a handy list, followed by embedded videos from the MS Dev channel on YouTube.

.NET Overview & Roadmap

Entity Framework Core 2.1: Simple, Powerful Data Access for .NET

Modernizing Desktop Apps on Windows 10 with .NET Core 3.0

ASP.NET Core SignalR

What’s new in Web Development with ASP.NET Core 2.1

The future of C#

The Future of .NET on the Desktop

The videos themselves are hosted on YouTube, so here are the same videos, embedded below:

.NET Overview & Roadmap

YouTube link: https://www.youtube.com/watch?v=KAIJ3ezQb3c

Entity Framework Core 2.1: Simple, Powerful Data Access for .NET

YouTube Link: https://www.youtube.com/watch?v=k55kDH_ixrQ

Modernizing Desktop Apps on Windows 10 with .NET Core 3.0

YouTube Link: https://www.youtube.com/watch?v=spgI12ZEBcs

ASP.NET Core SignalR

YouTube Link: https://www.youtube.com/watch?v=u0_vkWYYXRc

What’s new in Web Development with ASP.NET Core 2.1

YouTube Link: https://www.youtube.com/watch?v=SEgyZRau0rU

The future of C#

YouTube Link: https://www.youtube.com/watch?v=QZ0rWLaMZeI

The Future of .NET on the Desktop

YouTube Link: Coming Soon!