Tuesday, October 9, 2012

SignalR To Rescue

SignalR To Rescue

Asynchronous library for .NET to help build real-time, multi-user interactive web applications.

Many asp.net based real time applications uses some traditional techniques to trigger some business on client. Some old techniques include an recursive timely call like Ajax call to server to fetch data at intervals, a trigger from server using duplex channel when using WCF etc… These all traditional techniques has some or more disadvantages like a constant callbacks increasing server load, firewalls restricting duplex protocols hiding clients and resulting in broken links in duplex channels etc.


But now SignalR has emerged to rescue us from these types of architectural bottlenecks. One can easily build notification systems, chat applications, triggers across multiple applications and other myriads of real-time application using this simple yet powerful technology.


In this article I will jot down a very basic sample of broadcasting message to a group or to a specific client using SignalR and asp.net. For further technical documentation please refer https://github.com/SignalR/SignalR/wiki


Prerequisites


In order to take advantage of SignalR a small integration of its infrastructure is required. To keep it simple I will use use Package Manager Console and Nuget package of SignalR later in the project.


Application


Two important parts needs to be coded for creating basic SignalR based applications.


- Server Hub: A simple class containing methods that can be called from client hub. Also it is the main container of logic on server side. It can trigger methods on client hub with specific connection or with a group of connections.


- Client Hub: A piece of code that is used for registering to server hub. It can contain methods that call server hub methods. It can also contain methods that are called from server hub. Client hubs can be coded in native ASP.Net or JavaScript.


Step 1) Create a new Asp.Net Web Application (“SignalRNotification”) in Visual Studio. Remove all the default folders and web forms created by template if any.



Step 2) Install SignalR infrastructure
Go to Tools > Library Package Manager > Package Manager Console



Run below command
Install-Package SignalR



The above steps will install SignalR infrastructure required to make use of this technology

For detail description and latest news for SignalR release please refer http://nuget.org/packages/signalr

Step 3) Create a new class named NotificationHub that inherits from Hub.

[sourcecode language="csharp"]
using System;
using SignalR.Hubs;

namespace SignalRNotification
{
[HubName("notificationHub")]
public class NotificationHub:Hub
{
public void NotifyUsers(string message)
{
//Invokes onReceiveNotification function for all the Clients
Clients.onReceiveNotification(string.Format("{0} {1}", message, DateTime.Now.ToString()));
}
}
}
[/sourcecode]

In the above code one can chose to send message to all clients, a group of clients or to a specific client. To keep things simple the above code simply broadcast the message to all clients.

Step 4) Create a web form Admin.aspx. Add a textbox and a button to it as shown below. It includes reference to magical scripts that is actually responsible for connecting to SignalR hub and creating the proxy class. Internally this script registers the client using a unique GUID by making an ajax call. We will use this form for sending messages.

[sourcecode language="html"]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="SignalRNotification.Admin" %>

Admin
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script><script type="text/javascript" src="Scripts/jquery.signalR-0.5.3.min.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
$(function () {
// the generated client-side hub proxy
var server = $.connection.notificationHub;
// Start the connection
$.connection.hub.start();
$('#xbtnNotify').click(function () {
var message = document.getElementById('txtMessage').value;
//call the method on server using the proxy
server.notifyUsers(message);
});
});

// ]]></script>

<form id="form1">
<h1>Administrator</h1>
<div>Message :
<textarea id="txtMessage" style="width: 400px;" rows="3" cols="1"></textarea>
<input id="xbtnNotify" type="button" value="Send this to All Users" /></div>
</form>

[/sourcecode]

Step 5) Create a web form User.aspx as shown below. We will use this form for receiving messages.

[sourcecode language="html"]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="User.aspx.cs" Inherits="SignalRNotification.User" %>

User

<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script><script type="text/javascript" src="Scripts/jquery.signalR-0.5.3.min.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
// the generated client-side hub proxy
$(function () {
var server = $.connection.notificationHub;
//This is the method that will be invoked from the server!!
server.onReceiveNotification = function (message) {
$("#messages").append('
<li>' + message + '</li>

');
};
// Start the connection
$.connection.hub.start();
});
// ]]></script><pre>
<form id="form1">
<div>
<h1>User</h1>
</div>
<ul id="messages"></ul>
</form>
</pre>

[/sourcecode]

That’s it.

A simple way to do complex things.
In my next article I will explain how to create CHAT server using SignalR.