Sending Notifications using ASP.NET SignalR

Introduction

Web applications needing real-time communication can use HTML5 features such as Web Sockets and Server Sent Events. While these techniques can be used in modern web applications they can’t be used with browsers not supporting HTML5. Additionally, they can pose some difficulty in complex scenarios. ASP.NET SignalR is a library that allows you to perform real-time communication in web applications easily. In this article you will learn the basics of using SignalR in an ASP.NET web forms application. 

What is SignalR?

ASP.NET SignalR is a library for developing applications needing real-time communication. In such applications as soon as data is generated on the server or some interesting event happens on the server the client needs to be updated with the latest data. The traditional approach to achieve this functionality is to make Ajax calls to the server periodically. However, this approach has its own pitfalls. Another way is to use HTML5 Web Sockets or Server Sent Events (SSE) to perform real-time communication. However, both of these techniques work only on the browsers supporting HTML5. SignalR uses HTML5 Web Sockets if the target browser supports them, otherwise it falls back to other techniques. The best part is that – as a developer you need not know these internal implementation details. Additionally, SignalR makes connection management, grouping and authorization easy. You can work with the high level API exposed by SignalR in your web applications without worrying too much about the internals of the communication technique used.

You can use SignalR in variety of situations, some of them are listed below:

  • Chat applications where two or more end users chat with each other in real-time.
  • Broadcasting notifications or messages to all or selected clients.
  • Real-time gaming applications.
  • Social networking websites.
  • Discussion boards where admins or members can communicate to other admins or members.

Sample Application

To illustrate how SignalR can be used in an ASP.NET application you will develop a web form application as shown below:

Develop a web form application
Develop a web form application

The web application consists of two simple web forms, viz. AdminForm.aspx and ClientForm.aspx. The former web form is supposed to be used by an administrator to send notifications to all the clients connected at a given point of time. The later web form displays the notifications sent from the administrator to the end user. The notifications are displayed in a balloon that disappears after 5 seconds.

Getting SignalR

In order to develop the above application you should first install the SignalR library. You can get SignalR in couple of ways. Firstly you can install it as a NuGet package. To do so, open Tools > Library Package Manager > Package Manager Console and then issue the following command:

install-package Microsoft.AspNet.SignalR 

Not only easier, but the recommended way is to install Microsoft ASP.NET and Web Tools 2012.2. Doing so will add certain project item templates in the Add New Item dialog as shown below:

Add New Item
Add New Item

You can use these templates (more on that later) instead of manually creating the respective project items.

Developing the Admin Web Form

Now let’s develop the admin web form first. Begin by creating a new blank ASP.NET web forms application. Then right click on the project in the Solution Explorer and select Add New Item. Then add a new SignalR Hub Class to the project. This creates a new class that inherits from Hub base class.

namespace SignalRDemo
{
    public class MyHub1 : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}

The Hub class resides in the Microsoft.AspNet.SignalR namespace. A hub class can have any number of developer defined methods. These methods can then be called from a client side script. SignalR hubs provide a higher level RPC framework for your application. Additionally, you will find certain script files under the Scripts folder.

Additional scripts
Additional scripts

In this example you need a method – SendNotifications() – inside the hub class as shown below:

public void SendNotifications(string message)
{
    Clients.All.receiveNotification(message);
}

As you can see, the SendNotifications() method accepts a string parameter. Inside, it uses the Clients.All property to access all of the clients currently connected with the server. The receiveNotification() is a client side callback function that you will write in your jQuery code later. This way a notification is broadcast to all the connected clients. How the clients make use of the message is governed by the receiveNotification() client side function.

Next, add a Global.asax file to your web application and write the following code in the Application_Start event handler.

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHubs();
}

The MapHubs() method registers default routes for SignalR hubs.

Now, add a web form to the project and name it as AdminForm.aspx. Add the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Admin Form Sending Notifications</title>

    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>

    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            $("#button1").click(function () {
                proxy.server.sendNotifications($("#text1").val());
            });

            $.connection.hub.start();
        });
    </script>

</head>
<body>
    <input id="text1" type="text" />
    <input id="button1" type="button" value="Send" />
</body>
</html>

The AdminForm.aspx refers SignalR script files in the head section. Notice the code marked in the bold letters. First a variable named proxy is declared to hold a reference to a proxy of the remote hub class (NotificationHub). Make sure that the client side code uses camel casing in naming conventions. For example, NotificationHub is referred as notificationHub in the client code.

Next, the click event handler of the button is wired to a function. The client event handler calls the sendNotifications() method on the proxy object and passes the notification message entered in the textbox (see earlier figure to know what the admin form looks like).

Finally, the start() method of the hub is called to start the connection.

Developing the Client Web Form

Now that you have completed AdminForm.aspx let’s develop the client web form. Add another web form to the project and name it ClientForm.aspx. Key-in the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Client Form Receiving Notifications</title>
    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            proxy.client.receiveNotification = function (message) {
                $("#container").html(message);
                $("#container").slideDown(2000);
                setTimeout('$("#container").slideUp(2000);', 5000);
            };

            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <div class="notificationBalloon" id="container">
    </div>
</body>
</html>

The client code also declares a variable to hold a reference to the proxy hub object. It then wires a callback function receiveNotification (recollect that you used this name in the server side NotificationHub class). The receiveNotification() function receives the notification message sent by the server and displays it to the user after animating it using slideDown() and slideUp() jQuery functions. The notification message is automatically discarded after 5 seconds using the setTimeout() JavaScript function.

Finally, a connection is started by calling the start() method on the hub.

That’s it! Run the AdminForm.aspx and load ClientForm.aspx in two or three browser windows or tabs. Now enter some message in the textbox from AdminForm.aspx and click on the Send button. All the browser windows showing ClientForm.aspx should show the notification message.

Summary

SignalR is a library that allows ASP.NET applications to perform real-time communication. If the target browser supports HTML5 SignalR uses Web Sockets otherwise fallback techniques are used. Additionally, SignalR provides an easy way for connection management, connection grouping and security for the communication. This article demonstrated a basic use of SignalR to send notifications to all the connected clients in real-time.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read