SignalR – Full Duplex communication


Today we are going to talk about Full Duplex communication, but, what’s that? In a common web scenario, the user makes a call to a web server and that returns the specific page. Each time that you make an action, like push a button, the information is sent to server and that returns again the information. In this scenario, the user is always who trigger the communication and te communication is always from the user to the server.

But, what happend if is the server who wants to send us a notification? An example or that maybe facebook message notifications, twitter notifications, etc. This is a full duplex communication. We can trigger the action or the server can trigger an action. To implement this real time communications we have a library, called SignalR, that help us to do that.

Sometimes, this library is wrongly called, “chat library” because is the first thing that you think when you try to do something with this library or you think in full duplex communication but SignalR is more powerful than that. We will try to do an example with SignalR, avoiding the typical example of chat, where the server will send us the information of the most used words in a file (like the hashtags of twitter).

 

The first step is install JQuery and SignalR through Nuget and aggregate the scripts to our page. In addition we need to do two more things, add a “hubs” reference in the scripts (/signalr/hubs) the content will be created dynamically by SignalR and add the OwinStartup in the AssemblyInfo.

SignalR1

The next step is create our “Hub” classes. We need to add to the project a “SignalR Hub Class” file where we are going to implement our method. We will create a Init method to initialize the class when we will create a timer to repeat the proces each X time. Our function will read the information from a file or ddbb to get the more hashtags and will send the information to the connected clients to refresh the pages.

Untitled

The next step is create the method “listHashTags” in our client side and initialize our hub. We need to create object of our hub (be careful because the names starts with lowercase, even if our class is in uppercase). We have the function start that will  be launched at load the page. We will call init method from this function to initialize our hub and draw the hashtags the first time.

For each function that we call from .net (Clients.All.listHashTags) we need to create the method in client side with the actions to do.

SignalR3

 When we launch the application, the hub will be created and draw the first time. Each 15 seconds the server will be launch a update for our connected clients.

SignalR3

We can update all clients or specific clients. We will update the project to update all clientes and each client separately. We will manage our connected clientes with a Dictionary and when the server tries to update clientes we will update each client with his own data. To do that, we need to override the methods OnConnected,  OnDisconnected and OnReconnected in our Hub and update each client in our method.

SignalR4

SignalR6

With this way, each client will be update with his own data for the time and for the same data for the hashtags.

SignalR7

 You can download the code here.

Web Routes in asp.net


Route config allow us to manage the name of the URL. By default the url are based on the location path and sometimes can be a little ugly and in addition that names penalize in the search positioning. We can do the url similar to MVC but with more control (friendly url). We can define only the name and the path, the name with restrictions, etc.

Continuing with our case, we have a simple page Books/List and two additional pages, one for see details of Authors and Publishers of the book and another one for the details of the books.

We can define some restriction in the variable parameters of the url applying regular expressions as in our case with Id (of 4 numbers) or types (needs to be Author or Publisher).

1

We need to call this method from Global.asax.

At the end, our url should be something like that:

http://localhost/Books/ 0007/Author

http://localhost/Books/0007

http://localhost/Books/List

Call server methods with JavaScript events


Sometimes, will be usefull call some server methods after detect an event. For example, click on a button, select a value in dropdownlist.
With the framework controls we can do this kind of actions (default events implemented), but what happen if we  want control other events like “type a value”, “make double click”, etc.
To manage this events we need to manage trough javascript and if we want to invoke a server method, one solution should be call WebMethod through ajax (http://api.jquery.com/jquery.ajax/).
Exists an easy way to do that without jquery ajax. We can associate a javascript event with a server method.
To do that we need to register the event in the Page_Init method and assign them to the control. We register the control and his events.
var onBlurScript = Page.ClientScript.GetPostBackEventReference(TxtJsEvntBox, "OnDblClick");
TxtJsEvntBox.Attributes.Add("ondblclick", onBlurScript);

var onKEyPress = Page.ClientScript.GetPostBackEventReference(TxtJsEvntBox, "OnKeyUp");
TxtJsEvntBox.Attributes.Add("onkeyup", onKEyPress);
The next step is manage the control and the event that has been triggered in Page_Load.
var ctrlName = Request.Params[Page.postEventSourceID];
var args = Request.Params[Page.postEventArgumentID];
HandleCustomPostbackEvent(ctrlName, args);
After that we need to design the logic of the server method for each event previously defined, for example like this:
if (ctrlName == TxtJsEvntBox.UniqueID) {
  switch (args) {
    case "OnDblClick":
      LblTest.Text = "On Double Click Event at " + DateTime.Now; break;
    case "OnKeyUp":
      LblTest.Text = "On Key Up Event at " + DateTime.Now;
      ScriptManager.RegisterStartupScript(this, GetType(), "focus", GetFocus(ctrlName.Replace('$', '_')), true);
      break;
  }
}
Maybe this is more easy to understand and implement if you not are familiarized with javascript or jquery language. You can download the full example here.