Real-Time Dashboard using Azure SignalR Hub

From the article by Mr. Darshana Mihiran Edirisinghe

In this article, we are going to discuss creating a real-time application using Azure SignalR, .NET API, and a React application. This is a great choice for building interactive, collaborative applications like chat, live dashboards, or online gaming.

This Article covers the below topics,

  1. Option for managing Real-time.
  2. Create Azure SignalR Service.
  3. Authentication and Authorization.
  4. Scale and Optimize.
  5. Monitoring and Diagnostic.
  6. Implement in .NET API.
  7. Implement in React Application.
  8. Best Practices.

Introduction

When implementing real-time applications in a .NET API, SignalR is the primary and most well-established option. SignalR is a library provided by Microsoft specifically for building real-time features in .NET applications. However, there are other alternative options and technologies you can consider for real-time applications in .NET.

1. SignalR:

SignalR is a robust choice for adding real-time capabilities to your .NET Core API. It supports a range of communication protocols, including WebSockets, Server-Sent Events, and more. You can create hubs for managing real-time communication between the server and clients. SignalR also provides a client library for various platforms, including JavaScript and .NET.

2. WebSockets (System.Net.WebSockets):

You can directly use the System.Net.WebSockets library in .NET Core to implement WebSocket communication in your API. This is a lower-level approach compared to SignalR and provides fine-grained control over WebSocket connections.

3. gRPC with Real-Time Support:

gRPC, which is a high-performance remote procedure call framework, can be extended to support real-time features using bidirectional streaming. You can implement real-time features in your .NET Core API by utilizing gRPC’s bidirectional communication capabilities.

4. Custom Protocols with ASP.NET Core:

You can create custom real-time protocols in your ASP.NET Core application, handling WebSocket or other communication methods directly. This approach provides maximum flexibility but requires significant development effort.

5. Third-Party Libraries:

There are third-party libraries available for real-time communication in .NET Core, although they may not be as feature-rich or widely adopted as SignalR. Some examples include Fleck (a WebSocket library) and WampSharp (an implementation of the Web Application Messaging Protocol).

6. RabbitMQ or Other Message Brokers:

If your real-time application involves messaging or event-driven scenarios, you can use a message broker like RabbitMQ in combination with your .NET Core API to implement real-time messaging.

Create Azure SignalR Service

Creating an Azure SignalR Service involves several steps.

  1. Select SignalR Service: Log in to Azure Portal. Create a New SignalR Service. Click on “Create a resource” in the Azure Portal. Search for SignalR Service. Select SignalR Service.
  2. Configurations: Let's create the service. On the “Create SignalR Service” page, click “Create.” Fill in the necessary information below. - Subscription: Choose your Azure subscription. - Resource Group: You can either select an existing resource group or create a new one. - SignalR Service Name: Choose a unique name for your SignalR service. - Region: Select the Azure region where you want to create your SignalR service. - Pricing Tier: Choose the pricing tier that fits your needs. Click “Review + Create.”
  3. Deployment: Once you review the information you provided, click “Create” to start the deployment process. Azure will now deploy your SignalR service. This may take a few minutes. Once the deployment is complete, you’ll receive a notification that your deployment was successful.
  4. Connection: To access your SignalR service, you’ll need connection strings or access keys. In the Azure Portal, navigate to your newly created SignalR Service. Under the “Settings” section, click on “Keys.” Depending on the type of application you’re building, you will need to configure your client application to connect to the SignalR service using the connection string or access keys you obtained in the previous step.

Security and Authentication

Implement any required security and authentication mechanisms for your application. Azure SignalR Service can work with Azure Active Directory (Azure AD) for authentication if needed.

  1. Select Your SignalR Service. In the Azure SignalR Service settings, go to the “Authentication” section. Choose an Authentication Provider. Azure SignalR Service supports different authentication providers, including Azure Active Directory (Azure AD) and custom authentication. Select the authentication provider that suits your needs.
  2. For Azure AD Authentication, Click on “Azure Active Directory.” Configure Azure AD authentication settings, including the Azure AD tenant ID, client ID, and client secret. These values can be obtained when you register your application in Azure AD.
  3. Save Configuration. Update your client application. For Azure AD Authentication, Update your client application to obtain Azure AD tokens and pass them to the SignalR service when connecting. For Authorization, Define the access control rules for your SignalR service. This controls who can connect to your service and access specific hubs. You can do this using the [Authorize] attribute in your SignalR hub methods or by implementing custom authorization logic based on the authentication information.

Scale and Optimize

Configure scaling options if your application is expected to have varying workloads. Log in to the Azure Portal (https://portal.azure.com) with your Azure account. Navigate to the Azure SignalR Service that you’ve created by clicking on it in the Azure Portal.

Scale Up or Out

Azure SignalR Service can be scaled either vertically (scaling up) or horizontally (scaling out). Choose the scaling method based on your requirements.

Vertical Scaling (Scale Up): To scale up, increase the capacity of your service by changing the pricing tier. This increases the available resources for your SignalR service. In the Azure Portal, go to your SignalR service and click on “Scale-up.”

Horizontal Scaling (Scale Out): To scale out, add more instances of your SignalR service. This helps distribute the load across multiple instances. In the Azure Portal, go to your SignalR service and click on “Scale-out.” Specify the number of units you want to run in parallel.

Set Auto-Scale Rules (Optional): You can configure auto-scaling rules to automatically adjust the number of units based on usage metrics. This ensures your service is always right-sized and can handle fluctuations in traffic. In the Azure Portal, navigate to your SignalR service and click on “Auto-scale.” Create rules based on metrics like the number of connections or messages per second. Define the minimum and maximum number of units for auto-scaling.

Optimize Hub and Connection Management

Depending on your application’s needs, you can fine-tune how hubs and connections are managed. Configure hub methods for load distribution and optimization. Implement connection management and disconnect idle connections when necessary.

Monitoring and Diagnostics

Set up monitoring and diagnostics for your Azure SignalR Service to track its performance and troubleshoot issues. Navigate to the Azure SignalR Service that you’ve created by clicking on it in the Azure Portal. Azure SignalR Service provides diagnostic logs that capture information about service activities and usage. In the Azure Portal, go to your SignalR service. Under “Settings,” select “Diagnostic settings.” Click on “Add diagnostic setting.” Provide a name for the diagnostic setting. Under “Category details,” select the diagnostic categories you want to monitor, such as “Service and performance counters” or “Connectivity.” Choose a destination for the diagnostic logs, typically Azure Monitor, and configure the settings accordingly. Save the diagnostic setting.

Configure Metrics Collection

Metrics are essential for understanding the performance and usage of your SignalR service. Azure SignalR Service provides metrics like connections, messages sent, and messages received. In the Azure Portal, go to your SignalR service. Under “Monitoring,” select “Metrics.” Choose the metrics you want to collect and visualize. Set up alerts if necessary to be notified of critical issues.

Set Up Alerts

Alerts help you proactively respond to issues or unusual events in your SignalR service. You can create alerts based on metric thresholds, diagnostic logs, or other conditions. In the Azure Portal, go to your SignalR service. Under “Monitoring,” select “Alerts.” Click on “New alert rule” to create a new alert rule. Configure the alert criteria, such as metric thresholds, conditions, and alert actions (e.g., sending an email or triggering an Azure Function). Save the alert rule.

Integrate with Application Insights

Application Insights is a powerful tool for monitoring the performance of your application, including interactions with the SignalR service. In the Azure Portal, go to your SignalR service. Under “Settings,” select “Application Insights.” You can choose to link an existing Application Insights resource or create a new one. Follow the steps to link the Application Insights resource to your SignalR service.

Implement Azure SingalR in .NET API

  1. Create .NET API project.
  2. Install the SignalR Package.

dotnet add package Microsoft.Azure.SignalR        

3. Create a SignalR Hub. Create a SignalR hub class by adding a new class to your project. The hub class should derive from Hub .

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRApp.Hubs
{
    public class RealTimeHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            // Broadcast the message to all connected clients
            await Clients.All.SendAsync("Hi", user, message);
        }
    }
}        

4. In your Program.cs, you should configure the Azure SignalR Service connection string using the IConfiguration interface, which retrieves the connection string from your appsettings.json or other configuration sources.

services.AddSignalR().AddAzureSignalR(Configuration.GetConnectionString("AzureSignalR"));

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/RealTimeHub"); // Map the ChatHub to a specific endpoint
            });        

5. Create API Endpoint.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using MyAzureSignalRApp.Hubs;

namespace AzureSignalRApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DashboardController : ControllerBase
    {
        private readonly IHubContext<ChatHub> _hubContext;

        public DashboardController(IHubContext<ChatHub> hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpGet]
        public async Task<IActionResult> SendMessage(string message)
        {
            await _hubContext.Clients.All.SendAsync("ReceiveMessage", message);
            return Ok();
        }
    }
}        
Hub methods are typically called from client applications (e.g., web browsers, mobile apps) to send real-time messages to the server and, in turn, to other connected clients. However, in some cases, you may need to invoke hub methods from your server-side code, such as from a controller in a .NET Core API.

Implement Azure SingalR in React Application

Create a React application. install the SignalR client library. You can do this using npm or yarn:

npm install @microsoft/signalr
# or
yarn add @microsoft/signalr        

Create a SignalR Service Module.

// signalRService.js
import { HubConnectionBuilder } from '@microsoft/signalr';

const signalRService = {
  connection: null,

  startConnection: (hubUrl) => {
    signalRService.connection = new HubConnectionBuilder()
      .withUrl(hubUrl)
      .build();

    signalRService.connection.start().then(() => {
      console.log('SignalR connection established.');
    }).catch((err) => {
      console.error('Error starting SignalR connection:', err);
    });
  },

  onReceiveMessage: (callback) => {
    signalRService.connection.on('ReceiveMessage', (user, message) => {
      callback(user, message);
    });
  },

  sendMessage: (user, message) => {
    signalRService.connection.invoke('SendMessage', user, message)
      .catch((err) => {
        console.error('Error sending message:', err);
      });
  },
};

export default signalRService;        

Use SignalR in React Components.

import React, { useEffect, useState } from 'react';
import signalRService from './signalRService';

function App() {
  const [messages, setMessages] = useState([]);
  const [user, setUser] = useState('');
  const [message, setMessage] = useState('');

  useEffect(() => {
    signalRService.startConnection('/RealTimeHub');

    signalRService.onReceiveMessage((receivedUser, receivedMessage) => {
      setMessages([...messages, { user: receivedUser, message: receivedMessage }]);
    });

    return () => {
      signalRService.connection.stop();
    };
  }, [messages]);

  const sendMessage = () => {
    signalRService.sendMessage(user, message);
    setMessage('');
  };

  return (
    <div className="App">
      <h1>React SignalR Chat</h1>
      <div>
        <input
          type="text"
          placeholder="Your Name"
          value={user}
          onChange={(e) => setUser(e.target.value)}
        />
        <input
          type="text"
          placeholder="Message"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
        <button onClick={sendMessage}>Send</button>
      </div>
      <div>
        {messages.map((msg, index) => (
          <div key={index}>
            <strong>{msg.user}:</strong> {msg.message}
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;        

Best Practices

  1. Use Azure SignalR Service for Scalability.

2. Organize your SignalR hub classes in a structured manner, keeping related hub methods and functionality together. This makes your code easier to understand and maintain.

3. Use Authorization and Authentication:

4. Validate input data in your hub methods to ensure it’s safe and that your server is protected from malicious input.

5. Error Handling.

6. Load Testing.

7. Logging and Diagnostics.

8. Real-Time Monitoring.

9. Message Size Considerations.


要查看或添加评论,请登录

Mohammed Shamseer Vettan的更多文章

  • Be familiar with NoSQL solutions like MongoDB, CouchDB.

    Be familiar with NoSQL solutions like MongoDB, CouchDB.

    These beasts can be a real life-saver when traditional relational DBs reach their limits at scaling and performance…

  • “What database actually Facebook uses?”

    “What database actually Facebook uses?”

    A billion of people are using FACEBOOK.Users are expressing themselves and interacting with their peer and friends…

    1 条评论
  • Learn to Love

    Learn to Love

    HEART TOUCHING STORY Ex Indian President Dr. Abdul Kalam Says: "When I was a kid, my Mom cooked food for us.

    1 条评论

社区洞察

其他会员也浏览了