Real-Time Applications with Azure SignalR, Angular and .Net Core

Posted on July 10, 2023
.NET CoreazureangularAzure SignalR

In today's digital world, real-time communication and collaboration have become integral parts of modern applications. Users expect instantaneous updates and interactive experiences, making real-time functionality crucial for many applications. Azure SignalR, combined with Angular, offers a powerful solution to build scalable and real-time applications. In this blog post, we will explore an example of integrating Azure SignalR with Angular and demonstrate how to create a real-time application.

What is Azure SignalR?

Azure SignalR is a fully managed real-time messaging service provided by Microsoft Azure. It simplifies the development of real-time features by abstracting away the underlying infrastructure complexity. Azure SignalR supports various platforms and frameworks, making it easy to build real-time applications for web, mobile, and IoT devices.

How Azure SignalR Works

When a client (web browser or mobile app) connects to your application, it establishes a connection with the Azure SignalR Service. The client uses the SignalR client library to establish and maintain the connection. On the backend, you define a SignalR Hub, which acts as the central communication point for clients. The hub manages connections, receives messages from clients, and sends messages to connected clients.

When a client sends a message to the hub, Azure SignalR routes the message to the appropriate hub instance, ensuring scalability and load balancing. The message is then forwarded to the connected clients. The hub broadcasts messages to all connected clients or sends messages to specific clients based on your application's logic. Clients receive the messages in real-time through their established connections.

Azure SignalR scales automatically to handle a large number of concurrent connections and messages. It dynamically adjusts resources to accommodate the application's needs, ensuring high performance and responsiveness.

SignalR Working

RealTime Chat App - Demo

Demo

The full source code for this article can be found on GitHub.

Integration Steps in .Net Core + Angular + Azure SignalR

Step 1: Set up Azure SignalR Service

  • Create an Azure SignalR service instance in the Azure portal.
  • Make a note of the connection string provided by Azure SignalR.

Create SignalR Azure

Step 2: Create a .NET Core Web API Project

  • Open your terminal and execute the following command OR through visual studio to create a new .NET Core Web API project:
dotnet new webapi -n RealTimeChatApp

Step 3: Install NuGet Packages

dotnet add package Microsoft.AspNetCore.SignalR
dotnet add package Microsoft.Azure.SignalR

Step 4: Configure Azure SignalR Service

  • Open the Startup.cs file and add the following code within the ConfigureServices method:
using Microsoft.Azure.SignalR;

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR()
        .AddAzureSignalR(options =>
        {
            options.ConnectionString = "YOUR_AZURE_SIGNALR_CONNECTION_STRING";
        });
    // Other service configurations
}

Step 5: Create a SignalR Hub

  • Add a new class called ChatHub.cs in the project and add the following code:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace codehack_realtime_chat_signalR.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(ChatMessage chatMessage)
        {
            await Clients.All.SendAsync("ReceiveMessage", chatMessage);
        }
    }

    public class ChatMessage
    {
        public string Sender { get; set; }

        public string Content { get; set; }
    }
}

Step 6: Update Controller and Routing

  • Open the Program.cs file and add the following code within the Configure method:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Other middleware configurations

    app.UseRouting();
    app.MapControllers();
    app.MapHub<ChatHub>("/chat");
}

Step 7: Create Angular Project

  • Open your terminal and execute the following command to create a new Angular project:
ng new real-time-chat-app

Step 8: Install SignalR Client Package

  • Install the @microsoft/signalr package by running the following command:
npm install @microsoft/signalr

Step 9: Update Angular Component

  • Open the app.component.hml file in the Angular project and replace the code with the following:
<div class="chat-app">
  <div class="header">
    <h1>Real-time Chat App</h1>
  </div>
  <div class="chat-container">
    <div class="user-section" *ngIf="!userName">
      <input type="text" [(ngModel)]="tempUserName" placeholder="Enter your name" class="name-input" />
      <button (click)="startChat()" class="start-button">Start Chat</button>
    </div>
    <div class="chat-box" *ngIf="userName">
      <p class="user-name">Welcome, {{ userName }}!</p>
      <ul class="message-list">
        <li *ngFor="let msg of messages" class="message-item" [ngClass]="{'current-user': msg.sender === userName}">
          <span class="message-sender">{{ msg.sender }}:</span> {{ msg.content }}
        </li>
      </ul>
    </div>
    <div class="input-section" *ngIf="userName">
      <input type="text" [(ngModel)]="message" placeholder="Type a message" class="message-input"
        (keydown.enter)="sendMessage()" />
      <button (click)="sendMessage()" class="send-button">Send</button>
    </div>
  </div>
</div>
  • Open the app.component.ts file in the Angular project and replace the code with the following:
import { Component } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public message: string | undefined;
  public messages: any[] = [];
  public tempUserName: string | undefined;
  public userName: string | undefined;

  private hubConnection: signalR.HubConnection | undefined;

  constructor() {
    this.startSignalRConnection();
  }

  private startSignalRConnection(): void {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:7098/chat') //REPLACE YOUR HUB URL
      .build();

    this.hubConnection.start()
      .then(() => console.log('SignalR connection started.'))
      .catch(err => console.log('Error while starting SignalR connection: ', err));

    this.hubConnection.on('ReceiveMessage', (message: any) => {
      console.log('Received message: ', message);
      this.messages.push(message);
    });
  }

  public startChat(): void {
    if (this.tempUserName) {
      this.userName = this.tempUserName;
      this.tempUserName = '';
    }
  }

  public sendMessage(): void {
    if (this.message) {
      const chatMessage = {
        sender: this.userName,
        content: this.message
      };
      this.hubConnection?.invoke('SendMessage', chatMessage)
        .catch(err => console.error('Error while sending message: ', err));

      this.message = '';
    }
  }
}

Note to User: When your application's backend and frontend run on different ports, it becomes crucial to enable CORS (Cross-Origin Resource Sharing) for SignalR. This step is essential for facilitating communication between the frontend and backend components.

  • In the ConfigureServices method, configure CORS policies:
// Add services to the container.
var allowedSpecificOriginsPolicy = "_AllowedSpecificOriginsPolicy";
builder.Services.AddCors(options =>
{
    options.AddPolicy(allowedSpecificOriginsPolicy, builder =>
    {
        builder.WithOrigins("http://localhost:4200")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
    });
});


// Configure the HTTP request pipeline.
app.UseCors(allowedSpecificOriginsPolicy);

Summary

We are creating a real-time chat application with a professional and user-friendly interface. The application allows users to enter their names, start a chat session, and exchange messages in real-time. The chat messages are displayed in a scrollable chat box, colorizing each user's messages for easy identification. Users can send messages by clicking the "Send" button or pressing Enter. The design includes a header, margins, and a messenger-style look, enhancing the overall appearance. The application utilizes Angular for dynamic rendering and handles communication with the backend using SignalR. The result is a modern and engaging chat experience.

We are using Angular, SignalR, HTML, CSS, .NET Core, and C# to develop a real-time chat application. Angular is used for the front end, providing dynamic rendering and user interface components. SignalR enables real-time communication between servers and clients. HTML structures the content, while CSS styles the application. On the backend, we use .NET Core and C# to handle server-side logic and integrate with SignalR. These technologies combine to create a responsive and interactive chat application with real-time messaging capabilities.

References

Thanks for reading!


Posted on July 10, 2023
Profile Picture

Arun Yadav

Software Architect | Full Stack Web Developer | Cloud/Containers

Subscribe
to our Newsletter

Signup for our weekly newsletter to get the latest news, articles and update in your inbox.

More Related Articles