Wednesday, August 15, 2018

SignalR – Create a simple application

SignalR is addition to the ASP.NET. It is started as an opensource project by some members of ASP.NET team. Due to its features and usability it is incorporated in the ASP.NET and officially become the part of the Microsoft ASP.NET.
SignalR enables you to do real-time communications between your browsers and server so that you push real-time updates to the browsers. Signal usage the technology that each browser support to enable real-time communication for example. If you are using the Internet Explorer 6 then used web pooling but in case of the current updated browser it used WebSocket.
Web pooling
clip_image002
In case of latest and updated clients, WebSocket make the real-time communication easy
clip_image004
clip_image006
Image create from - https://www.pubnub.com/learn/glossary/what-is-websocket/
SignalR does a quite bit more for the real-time communication. It is capable of communicating with multiple mobile and desktop clients.
It supports both ASP.NET and OWIN for open web interface for .NET. It can work with different Backplanes and using these Backplanes you can have multiple webserver which can in sync with each other. All of these keep real-time communication with different type of clients.
SignalR Components
clip_image008
For example, a client pushes a update to one of your webserver and that webserver communicates over the Backplanes to another web server which sends information down to a client using jQuery and html it is all setup for you through SignalR.
Let’s create a small SignalR example: This example is just for showing the functionality. In this example we just create static variable to know the active connections.
Open Visual studio and create an empty ASP.NET application
clip_image010
Then add a SignalR Hub Class, but there is another option is available “SignalR Persistent Connection Class” which something low level connection. SignalR Hub Class is high level implementation use. Now right click on the project in Solution Explorer and select New -> New Item to add a Hub Class named “ActiveConnectionCounter”.
clip_image012
clip_image014
Once you add this class file to the project then required references automatically added to the project e.g. jQuery and react JavaScript libraries.
clip_image015
Now the add static variable to keep the active connections and rename default create method name to “NotifyNewUser”. After that notify the all clients about the active connections change by specifying a dynamic method as shown in the below code snippet.
namespace WebDev.AspNetReact
{
    public class ActiveConnectionCounter : Hub
    {
        static int activeConnections = 0;
        public void NotifyNewUser()
        {
            activeConnections += 1;
            //Notify all users about the active users by passing value to a dynamic method
            Clients.All.onAtiveConnectionChanged(activeConnections);
        }
    }
}
Now time to trap the disconnected event so that we can notify about the disconnection of the any user. To do so override the OnDisconnected method and notify the all clients after decreasing the active connections.
public override Task OnDisconnected(bool stopCalled)
{
    activeConnections -= 1;
    //Notify all users about the active users by passing value to a dynamic method
    Clients.All.onAtiveConnectionChanged(activeConnections);
    return base.OnDisconnected(stopCalled);
} 

Now in implementation client call the method NotifyNewUser to notify the new user active on the website and client notified using the “onAtiveConnectionChanged” callback.
To complete the example, add a html page to the project using Project->Add New Item menu or by right click on project.
Add a <div> to show the active users count and required JavaScript libraries e.g. jQuery, jquery.singalR.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
    <div id="activeUserCount"></div>   </body>
</html>

After that add script to initiate the communication.

<script type="text/javascript">
    $(function () {
        var cn = $.hubConnection();
        
        var hub = cn.createHubProxy('activeConnectionCounter');
        hub.on('onAtiveConnectionChanged', function (i) {
            $('#activeUserCount').text(i);
        });
        cn.start(function () {
            //Invoke Server method name
            hub.invoke('NotifyNewUser');
        });
    });
</script>

Though we have created an empty ASP.NET project so we need to configure OWIN or map SignalR a startup. To do this create one Class with name Startup.cs under “App_Start” folder in the solution explorer.
using Owin;
namespace WebDev.AspNetReact
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

There are three way to configure the OWIN and they are described here - OWIN Startup Class Detection.
Now example is ready. Run the application and open the html page URL in different browsers.
clip_image017
Here we have created an example to start learning about the SignalR application and to know about the Visual Studio tool go through the tutorial.


No comments :

Post a Comment