Skip to main content

Real time data to web application using Microsoft Signal R and Razor Pages

Today we are going to learn how to create razor pages and how to send run time value to the razor page using Signal R

Create a new .NET core web application

Add Signal R library by,  Add Client-Side Library dialog in the project, for Provider select "unpkg" and select the latest version from the drop down
For Library, enter @aspnet/signalr@1,
Add a new folder to the project named as Hubs
The chat hub class inherits from HUb class that manages connections and messaging
The send message is called to send the message to all the clients. MyHub.cs file contains the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
//using System.Threading.Tasks;
namespace SignalRSample.Hubs
{
    public class MyHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Nest step is to configure signalR

Add using SignalRSample.Hubs to startup.cs file
 //Add the following line
            services.AddSignalR();

app.UseSignalR(routes =>
            {
                routes.MapHub<MyHub>("/MyHub");
            });

I will add this in the video description section for use

In Index.chtml page

Modify the Pages\Index.cshtml to follwing code
@page
@model SignalRSample.Pages.IndexModel
@{
}

In Index.chtml.cs

namespace SignalRSample.Pages
{
    public class IndexModel : PageModel
    {
        public IActionResult OnGet()
        {
            return new RedirectToPageResult("/MyViewPage");
        }
    }
}

Before that we will add a new page named MyViewPage

We will modify the page and add the code

<div class="container">
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-6">&nbsp;</div>
            <div class="col-6">
                Runtime Data1..........<input type="text" id="TimeSpan" />
                <br />
                Runtime Data2...<input type="text" id="CurrentTime" />
            </div>
        </div>
    </div>

We will add the folllowing code to MyViewPage.cshtml.cs
public void OnGet()
        {
        }
        private readonly IHubContext<MyHub> _myhubContext;
        public MyViewPageModel(IHubContext<MyHub> hubcontext)
        {
            _myhubContext = hubcontext;
            Class1.UpdateAction = ReceiveMessage;
            Class1.StartTimer();
        }
        public async void ReceiveMessage(string message1, string messag2)
        {
         
            await _myhubContext.Clients.All.SendAsync("ReceiveMessage", message1, messag2);
        }
We will add a layout page for the new page added and will give the name as MyViewPageLayout.cshtml
We will add the follwong code to it

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
    <script src="~/lib/signalr/signalr.js"></script>
    <script src="~/js/MyHub.js"></script>
</body>
</html>

  Now we add a java script file named MyHub.js in wwwroot/js folder
Add the shown code in the js file
"use strict";

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/MyHub")
    .configureLogging(signalR.LogLevel.Information)
    .build();
connection.on("ReceiveMessage", function (msg1, msg2) {
    document.getElementById("TimeSpan").value = msg1;
    document.getElementById("CurrentTime").value = msg2;
});

connection.start().catch(function err()
{
    return console.error(err.ToString());
});

What we basically did is we updated the two text boxes in MyViewPage with the messages received from Signal R callback

Now we will add a project that basically sends time and count message from a timer event, this will be our run time value that will be
sent to the razor page. The element gets updated without refreshing the whole page.

The data class is a C# dll project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace DataSource
{
    public class Class1
    {
        //The action takes two parameters
        public static Action<string, string> UpdateAction { get; set; }
        //Update action is an event that is raised from class,
        public static void Update(string noOftime, string time)
        {
            UpdateAction.Invoke(noOftime, time);
        }
        private static System.Timers.Timer myTimer;

        public static void StartTimer()
        {
            SetMyTimer();                 
        }
        private static void SetMyTimer()
        {
            // Create a timer with a two second interval.
            myTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer.
            myTimer.Elapsed += OnTimedEvent;
            myTimer.AutoReset = true;
            myTimer.Enabled = true;
        }
        static long count = 1;
        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            count++;
            Update(count.ToString(), DateTime.Now.ToString());
        }
    }
}

So, lets complie the project and see it in demo.The demo video is at
 https://youtu.be/EZ6dNa0-XHQ

Comments

Popular posts from this blog

CRUD operation with WCF service and WPF client

 The database restored on local server WCF Service is talking to the database. Used Visual Studio 2019, entity framework 6 for data base operations from the service. The service exposes the following API’s.  The WCF contracts has both synchronous and asynchronous API's The client is in WPF. It has three windows, main window, customer window and order window as follows. The client uses the WCF service for database operations. When customer button is clicked, the customer window is displayed as below. We can perform CRUD operation from it. The customer can be searched based on ID. New customer window The order button launched order window. It has combo box to choose the customer ID. On selecting the ID, the order details are displayed in the data grid as follows. The source code is available in the GIT hub, URL below: https://github.com/SwagatikaGoswami/WPF_WCF_CRUD.git

Online Exam App with .NET Core Web API and Blazor Client

 We will develop an app that can host online exam. It will have the feature to register user, allow the user to log in. Dashboard for creating sample tests.  The code is shared in GIT hub repository https://github.com/ SwagatikaGoswami/ OnlineExamApp.git The database is MySQL database. The server is a WEB API .NET Core service that uses entity framework for DB operations. The client is a web assembly blazor application. The password stored in the database is encrypted. Register window is as follows. It checks for the mandatory fields. The log in page is as follows: The admin dashboard after logging in  The admin dashboard when new test button is clicked. It uses a Blazor component for adding new test samples.