Telerik blogs

Prior to 2012, ASP.Net had only one way to get data on a client browser without forcing an entire screen refresh: a JavaScript AJAX call to the webserver.  In 2012, Microsoft began publishing ASP.Net SignalR, a new technology that gives us an interesting new way to publish “real-time” data for our customer’s browsers to consume.  In this article, I am going to introduce ASP.Net SignalR and walk through a sample project demonstrating how it can be used with the Telerik ASP.Net RadNotification control to provide real-time notifications in the web browser. 

To follow the sample code in this article, you will need Visual Studio 2012 and a copy of the Telerik ASP.net AJAX controls.  The trial version of the controls will work with this sample, and is available for download.

What is SignalR?

SignalR is a new framework in ASP.Net that allows developers to create real-time communications and functionality in their web applications.  This means that your webserver can push content to connected clients as events happen, in real-time.  The framework has been constructed to be completely backwards compatible to all versions of browsers that support JavaScript, stepping down communication channels from the most modern to the oldest and most commonly available solution.  This means that all browsers that use a SignalR enabled service will be able to see the benefits of this real-time communication, and THAT is a very cool thing.

SignalR can be used anywhere within the ASP.Net ecosystem: as a component within WebForms, MVC, or WebPage projects.  In any application where a browser refresh is needed to see more data, we can potentially inject SignalR to provide a better experience.  Additionally, there are client libraries available if you would like to connect an application, not just a browser, to be able to receive real-time content from your ASP.Net web service.

I Already Have RadNotifications, How Does SignalR Help Me?

The RadNotification control as delivered provides the ability to check for notifications on a periodic basis.  There is an UpdateInterval property that defines the number of milliseconds between server-side checks for data. These requests are even smaller than regular AJAX postbacks as they rely on the ICallbackEventHandler interface MS gave us, so they skip the Render phase of the page lifecycle.  When the notification control connects to your webserver, it triggers the OnCallbackUpdate server-side event.  It is inside of this event that you would construct content to be displayed in the Notification control. 

Building the Sample Project

In this sample, I am going to start a new Telerik C# RadControls Web Application and select the Black theme as the default skin.  I will add the references to the SignalR libraries with the following commands in the NuGet package manager window:

Install-Package Microsoft.AspNet.SignalR.SystemWeb –pre
Install-Package Microsoft.AspNet.SignalR.Js –pre
Listing 1 - NuGet commands to add SignalR to a web project

These two commands will introduce the collection of SignalR libraries and dependencies necessary to configure for the IIS webserver and use a JavaScript client in the browser to connect to our server in real-time.

Next, I will start working through the default.aspx page.  First, add the script references to jQuery and the SignalR javascript libraries necessary to connect to a browser:

<script src="Scripts/jquery-1.9.0.min.js" />
<script src="Scripts/jquery.signalR-1.0.0-rc2.min.js" />
<script src="/SignalR/hubs" />
Listing 2 - Script Includes required to connect a browser to a SignalR service

Notice the third script that is included.  This references the SignalR server-side code that will communicate with our web browser.  More on that later.  Next, I am going to add a textbox for transmitting a notification message to all connected clients.  I will also add my RadNotification with a Slide animation and a ContentTemplate that contains a span tag where I will place incoming message content:

Message to send to all connected clients:
<input type="text" id="txtMessageToTransmit" />
<br />
<button id="submit">Transmit</button>
 
<telerik:RadNotification runat="server" ID="radNotify"
  EnableShadow="True" ShowCloseButton="False"
  Title="Incoming Notification:" Animation="Slide"
  Width="300" Height="100"
  OffsetX="-20" OffsetY="-20" Skin="Black">
</telerik:RadNotification>
Listing 3 - Code to present a 'Send Notification' form and the Notification Control

At this point, we have not really done anything that different from a normal implementation of a RadNotification.  Here is where things start to change:  I am next going to add a class file to the project and call it NotificationHub.  This server-side code will replace the OnCallbackUpdate or WCF service in the standard Notification control, and provide content to the browser.

This class will descend from a SignalR Hub and contain one method to relay messages to all clients:

public class NotificationHub : Microsoft.AspNet.SignalR.Hub
{
  public void SendNotification(string message)
  {
    this.Clients.All.Notify(message);
  }
}
Listing 4 - A small communication hub that will relay messages to other connected clients

This is a very simple implementation, and it just reaches out to all connected clients and calls the Notify method exposed on their client implementation.  I can hear you now: “But Jeff, how do we tell the server that there is a Notify method available to call?”  Inside of the Hub object, the Clients.All property returns a dynamic object that is interpreted at run time.  We need to expose the Notify method from our web page client with some JavaScript.

The JavaScript to connect from the browser back to the server is defined with a handful of jQuery-like syntax.

$(function () {
  var notificationHub = $.connection.notificationHub;
 
  notificationHub.client.Notify = function(msg) {
    var $radNotify = $find("<%= radNotify.ClientID%>");
    $radNotify.set_text(msg);
    $radNotify.show();
  };
 
  $.connection.hub.start();
 
  $("#submit").click(function (e) {
    e.preventDefault();
    var server = $.connection.notificationHub.server;
    server.sendNotification($("#txtMessageToTransmit").val());
    return false;
  });
});

Listing 5 – JavaScript client code that will enable a webpage to communicate to the SignalR hub

SignalR exposes a connection object on the $.connection property of the jQuery global object.  Inside of the signalr/hubs referenced script referenced earlier, you will find the NotificationHub class is configured as a JavaScript object that can be accessed through the notificationHub property of the connection.  By convention, SignalR will change the casing of any hub and method to a camelCase standard.

To expose the Notify method that our NotificationHub will call on the client, we attach a function with a matching signature to the notificationHub.client object.  Inside this method, we set the text of our notification with the set_text() method of the $radNotify object.  The final task is a standard RadNotification client-side show command.

The next line is very important.  In order for communications to flow back and forth between server and client, you must call start() on the $.connection.hub object.  If you do not call start, the SignalR client will never initiate communications with the server.  There is no need to call an end method, as the connection will simply time-out if the client goes away.

The final block of code in this JavaScript is a standard button click handler.  The important part to notice here is that instead of calling a standard jQuery $.ajax() method, we reach out through the $.connection.notificationHub.server method to call the public sendNotification method in our C# NotificationHub class.

With these snippets of code in place, I can start up several different browsers and transmit a notification to all of them at the same time.  Our RadNotification control will immediately display all of the messages.

Figure 1 – A notification sent from Chrome to Firefox and Internet Explorer connected browsers

Conclusion

We went through a very simple example to show how you can breathe new life into the RadNotification control with the new SignalR framework in ASP.Net.  The source code of this sample is available for download.  There are many ways that you can use SignalR to add real-time functionality to all of the ASP.Net AJAX controls.  What can you do with SignalR and our AJAX controls?  Download a copy of the AJAX Controls, grab a copy of the SignalR toolkit from NuGet and let me know what amazing techniques you come up with in the comments below.


About the Author

Jeffrey T. Fritz

Jeffrey T. Fritz is a Microsoft MVP in ASP.Net and an ASPInsider with more than a decade of experience writing and delivering large scale multi-tenant web applications. After building applications with ASP, ASP.NET and now ASP.NET MVC, he is crazy about building web sites for all sizes on any device. You can read more from Jeffrey on his personal blog or on Twitter at @csharpfritz. Google Profile


Comments

Comments are disabled in preview mode.