Getting Started With SignalR Using ASP.NET Core And Azure SignalR Service

Introduction

In this article, we'll learn how to get started with Azure SignalR service to scale out the service in the cloud without any limitation and infrastructure problems. To scale up SingalR, we have a couple of options, like Radis and Azure Service. At the time of writing this article, Azure Service is in Preview. Soon, it will be released as version 1.0. It is a fully managed service to add real-time functionality to your application.

Azure SignalR Service

It is a fully managed service to add a real-time update to any of your apps, not only web applications. It could be any client, like TypeScript /JavaScript client (Angular, React, VueJS) and .NET client. This service is capable of handling unlimited concurrent connections. So, you can scale out any level of the SignalR fast and best performing real-time framework. SignalR supports the native development on ASP.NET Core cross-platform development. It has ease of use API, you are good to go after changing a couple of lines only.

This article is part of the series of posts on SignalR using ASPNET Core.

  • Overview of New Stack SIgnalR on ASPNET Core here.
  • Getting started with SignalR using ASP.NET Core and Angular 5 here.
  • Working with dynamic hubs here.
  • Working with Xamarin.
  • Streaming data here.

This article demonstrates the following.

  • Creating Azure SignalR Service instance.
  • Accessing Azure Service keys and Connection string.
  • Creating Project Template using .NET CLI.
  • Consuming the Azure Service by Angular Client.
  • Demo.

The source code is available at GitHub.

Before reading this article, I would highly recommend you to go through the other articles of the series which are mentioned above.

Creating Azure SignalR Service

Now, we are going to create an Azure SignalR service instance. Go to the Azure portal by accessing http://portal.azure.com. If you don't have an Azure subscription, then get started with a free Azure account (https://azure.microsoft.com/en-us/free/) and try out.

To create an instance of service, click on "Create a resource" (top-left,) then search for SignalR service and click to that service. It will open a window detailing about the service and you will find the "Create" button at the bottom side. 

Azure

Now, you have to fill the required details like Resource Name, Subscription, Resource Group, Location, Pricing tier. Azure pricing tier offers you free instance for a tryout.

Azure 

Accessing Azure Service keys and Connection string

After creating Azure SignalR service instance, now we need a service key and a connection string to use that service. The key info is available "Keys" link under Settings option.

Azure 

We are done with the Azure SignalR service. Now, we have to consume that service in the client.

Creating Project Template using DOTNET CLI

Now, we are going to create a project template to use Azure SignalR Service. This time, we'll use .NET command line interface to create the project template. It uses "DOTNET" keyword to start any command on CLI.

Command - to create a new project.

dotnet new angular --name ASPNETCore_SignalR_AzureService

Command uses,

  • dotnet - prefix keyword to use any command in .NET CLI.
  • new - create/initialize .net projects.
  • Angular - ASPNET Core with the Angular template.
  • Name - Name of the project to be created. If you not mention the name of the project template than project created by the folder name.

Read more about .NET commands here 

The project has been created successfully using dotnet cli command. See the image below for reference.

Azure 

We have created an Angular template project. Now, we need to initialize the npm and install npm package for SignalR. So, I'd highly recommend you to go through Angular versions here.

Consuming the Azure Service by Angular Client

We are going to use Azure SignalR client in order to use Azure Service. We need to install Azure SignalR client SDK "Microsoft.Azure.SignalR".

CLI Command

dotnet add package Microsoft.Azure.SignalR --version 1.0.0-preview1-10015

Nuget Package

Install-package Microsoft.Azure.SignalR --version 1.0.0-preview1-10015

Azure 

Azure SignalR SDK allows the ease of use API just to change a couple of APIs and ready to use Azure SignalR service. In order to use this service, we have to AddAzureSignalR in configure service method and pass the Azure connection string which is copied from the Azure portal. I'm passing the same using configuration file (appsettings.json).

  1. // This method gets called by the runtime. Use this method to add services to the container.  
  2.         public void ConfigureServices(IServiceCollection services)  
  3.         {  
  4.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  5.   
  6.             // In production, the Angular files will be served from this directory  
  7.             services.AddSpaStaticFiles(configuration =>  
  8.             {  
  9.                 configuration.RootPath = "ClientApp/dist";  
  10.             });  
  11.   
  12.             services.AddSignalR().AddAzureSignalR(Configuration["Azure:SignalR:ConnectionString"]);  
  13.         }  

After adding Azure SignalR service, we need to use the Azure SignalR route pipeline to map the hub which is done in the configure method. Map the hub with URL to work correctly.

  1.          // Azure SignalR service
  2.          app.UseAzureSignalR(routes =>  
  3.             {  
  4.                 routes.MapHub<ChatHub>("/chat");  
  5.             });  

We have done with Azure SignalR SDK.

Chat SignalR Service

  1. import { EventEmitter, Injectable } from '@angular/core'  
  2. import { HubConnection,HubConnectionBuilder } from '@aspnet/signalr'  
  3.   
  4. @Injectable()  
  5. export class chatSignalRService {  
  6.   
  7.   hubConnection: HubConnection;  
  8.   onMessageReceived= new EventEmitter<any>();  
  9.   
  10.   constructor() {  
  11.     this.createConnection();  
  12.     this.registerEvents();  
  13.     this.startConnection();  
  14.   }  
  15.   
  16.   sendMessage(message) {  
  17.     this.hubConnection.invoke('sendMessage', message);  
  18.   }  
  19.   
  20.   private createConnection() {  
  21.     this.hubConnection =  new HubConnectionBuilder()  
  22.                               .withUrl("/chat")  
  23.                               .build();  
  24.   }  
  25.   
  26.   private startConnection() {  
  27.     this.hubConnection.start().then( () => {  
  28.       console.log('Connection started');  
  29.     }).catch(err => {  
  30.       console.error(err);  
  31.       setTimeout(this.startConnection(), 5000);  
  32.     });  
  33.   }  
  34.   
  35.   private registerEvents() {  
  36.     this.hubConnection.on('receivemessage', (message: any) => {  
  37.       console.log('message received:' + message);  
  38.       this.onMessageReceived.emit(message);  
  39.     })   
  40.   }  
  41. }  

HomeComponent

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. import { chatSignalRService } from '../service/chat.signalr.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-home',  
  7.   templateUrl: './home.component.html',  
  8. })  
  9. export class HomeComponent implements OnInit {  
  10.   message: any;  
  11.   messageHistory: any[];  
  12.   constructor(private chatService: chatSignalRService) {  
  13.     this.messageHistory = [];      
  14.   }  
  15.   
  16.   ngOnInit() {  
  17.     this.chatService.onMessageReceived.subscribe((message) => {  
  18.       this.messageHistory.push(message);  
  19.     });  
  20.   }  
  21.   
  22.   send() {  
  23.     this.chatService.sendMessage(this.message);  
  24.     this.message = '';  
  25.   }  
  26.   
  27. }  
  1. <form (ngSubmit)="send()">  
  2.   
  3.   Enter Text to send <input type="text" [(ngModel)]="message" name="message" />  
  4.   <input type="submit" name="" value="Send" />  
  5. </form>  
  6.   
  7. <div>  
  8.       messages received  
  9.      <div *ngFor="let msg of messageHistory">  
  10.        <p>{{msg}}</p>  
  11.      </div>  
  12. </div>  

Demo screen

Azure 

Summery

In this article, we have seen scaling out SignalR on Azure using ASPNET Core and Angular 5. We have learned the following.

  • Creating Azure SignalR service instance and accessing keys.
  • Project template creation using dotnet cli.
  • Consuming azure signalr service by Angular client.

References