Yet Another Tech Blog

SignalR - notifying clients about server events


SignalR is really good and famous library for asynchronous signalling. In simple terms, you can use signalR in scenarios where you are polling server after fix interval to check if server has something which client needs to update. With SignalR it becomes very easy to implement solutions which require real time asynch connection with server.

If you are completely new to the term SignalR, then please read this Scott Hanselman's this post and visit SignalR's page on GitHub.


Scenario 1: 

Recently I encounter this scenario in one of my web form application.

The application is used by limited number of users (approximately 100) who needs to run certain report every morning. They can run the report only after the last days reconciliation process has been completed (External process). The reconciliation process takes random amount of time everyday.

So to inform everyone that the process has been completed and they can start using reports, an admin drops a mail to all.

Scenario 2:

There's also another scenario in same application where the system receives multiple source data files from different departments. The data/files comes either in Sql Server or in server file location via secured FTP. The application users are also needs to be updated about which all files have been received till this time.

There could be multiple ways to handle this from inside application. But, we decided to use SignalR in this scenario. In the following article, I would elaborate about following points

  • Create notification page for site administrator to issue general notification.
  • Make web site generate notification based on database (data) condition.

Article Body

Lets start with, installing SignalR and get it working.

Since, SignalR is available on NuGet, it is a two click task to install SignalR in your web application.

To start with, create a new web application project. Go to Package manager console (If you cannot see it, Go to View -> Other Windows -> Package Manager Console).

In the console, type

PM>  Install-Package SignalR

After minutes of download and install, you have a SignalR library available in your project.

There are two model which can be followed in SignalR. Hub and  PersistantConnection. For this demo, I am going to follow PersistantConnection way.

Send notification message from Admin to all user's

Lets first create a separate class which inherits from SignalR.PersistantConenction class. Create a new class in your project (say SendMessage.cs) and add following code in the file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR;
using System.Threading.Tasks;

/// <summary>
/// Summary description for chat
/// </summary>
public class SendMessage : PersistentConnection

    protected override Task OnReceivedAsync(string clientId, string data)
        // Broadcast data to all clients
        return Connection.Broadcast(data);        


Main points in the code is that the class inherits from PersistantConnection class of SignalR namespace, The code has reference to SingalR and System.Threading.Tasks namespace.

For PersistantConnection model we need to add following event in Global.asax of the project.

using SignalR.Hosting.AspNet.Routing;
using System.Web.Routing;

public void Application_Start()
      RouteTable.Routes.MapConnection<SendMessage>("echo", "echo/{*operation}");

Here, we are passing just created class "SendMessage" as type for MapConnection.

Note: The MapConnection approach is only requires in case of using PersistantConnection mode. In case of Hub mode, this is not required.

Now, Lets consider two separate pages each for user and admin. The admin page will have ability to broadcast the message while user page can read the broadcasted messages.

First lets write a code for Admin page. Create a new aspx page in project and create a TextBox (to allow user type in the message) and a Button (to send notification messages).

<asp:TextBox ID="txtMsg" runat="server" Width="289px" Rows="5" 

 <asp:Button ID="broadcast" runat="server" BackColor="#CCFFFF" 
            OnClientClick="return false" 
            Text="Broadcast to all connected user" />

Then add below JavaScript code in the head of page.

<script type="text/javascript">
        $(document).ready(function () {

            // Proxy created on the fly
            var connection = $.connection('echo');

            // Start the connection

            $("#<%=broadcast.ClientID%>").click(function () {
                // Call the send method on the server
                connection.send($('#<%= txtMsg.ClientID%>').val());


Here, we are calling echo from the Javascript code, which is hooked in Global.asax Application_start event (as we seen already). So, 'echo' is just an identifier used in routing, you can change the name as you wish.

Now, add another aspx page in the project and name it as User.aspx. The User page has a div control used to display broadcasted messages from server and JavaScript code as displayed below,

<style type="text/css">
      #divAlert {
     position: absolute;
     top: 0;
     border:1 solid black;

<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>  
<script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script type="text/javascript">
     $(document).ready(function () {

            // Proxy created on the fly
            var connection = $.connection('echo');

            // Declare a function on the chat hub so the server can invoke it
            connection.received(function (data) {

            // Start the connection

<div id="divAlert" style="display:none;">

That's it. Run the project and start Admin.aspx and User.aspx in separate windows. Keep both the windows side by side. In Admin.aspx page, type some message and hit the button. The message will be displayed to all the users of web application.

This resembles to a chat application but in different context. This is all fine. Lets now look at more complex scenario.

Sending auto alerts about server events from application to all users

In first scenario we are calling server event when admin broadcasts a message. From the server event, SignalR then hooks up all the clients who are having open connection with server.

But, how could we create a server to generate the event on its own (without some application user listening/sending a signal). The SignalR library have provided a method to do that too.

The logic is somehow to get hold of SignalR connection object and by using the connection object, we can broadcast the message to all clients who have open connection with server.

To implement Auto alert feature, I have used System.Timers.Timer. The timer has been set to call an event after every 10 seconds. In the elapsed event, write a logic to check if new file has been received either in predefined file path location or in database. If yes, then hook up a connection object and broadcast a message.

Note that in this approach, the the broadcast is being done from outside of PersistantConnection class (unlike in first scenario) and so, we have to explicitly hook up the connection.

Since, I don't want to keep timer event running all the time hence, I have created a check box on admin page which indicates whether to start the timer on or off.

On check changed of Auto alert checkbox, A server side event is called which then sets the timer elapsed period, timer elapsed evnet hanlder and starts the timer.

protected void chkEvent_CheckedChanged(object sender, EventArgs e)
            System.Timers.Timer timerMsg = new System.Timers.Timer(10000);
            timerMsg.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

After timer period is elapsed, the elapsed event handler method is called. In the elapsed event as shown below, we have used DependencyResolver and GetConnection methods to get hold of IConnection which then allows us to broadcast the messages to all the connected clients.

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            //Get name of data file received from sql server and file location path
            string strDataReceived = objClass.GetReceivedFileName();
            //Using Dependency resolver of current host to resolve IConnectionManager
            IConnectionManager connectonManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
            //Get connection of specific PersistantConnection by using class name as type and get connection method
            IConnection connection = connectonManager.GetConnection<sendMessage>();
            //using IConnection broadcast message to all users who are conencted (and used echo).

That's it. Run the application, open both user and admin pages in separate windows and tick (mark check) auto alert check box. Wait for some time so that the timer elapsed event is called on server. The file is available on required location. Hence, server generates a message which is broadcasted in all user's page.


SignalR makes it possible to create true real time collaboration apps. There could be countless number of scenarios where we can utilize SignalR to improve how our web applications work and to improve overall user experience.

Thanks for visiting my site. If you have any thoughts or comments please drop a line or share your experience about how you are taking advantage of SignalR.