Real Time With SignalR
What went wrong? The state of the rental model changed and when I was notified I did not have enough clarity to tell the agent "I'll take it, I'll take it!" and instead decided to negotiate an extra day on the rental. What would be the solution to this rental problem? I could face the same problem the next day if I was not fast enough! A real time system, pushing notifications to registered clients would help me make a better decision.SignalR is a new Microsoft library; where its RC1 was released in December 2012. This library makes it extremely simple to ASP.NET developers to add real-time web functionality to applications. In a nutshell, this framework is a persistent connection abstraction over HTTP for .Net. Using SignalR server side code is able to push content to connected clients instantly as it becomes available instead of having connected clients periodically poll information from the system.
What is SignalR
SignalR is a server-side framework to write push services. It is composed of a set of server and client libraries to make push service communication easy and simple to use on any platform, and it has been optimized for asynchronous processing.
SignalR provides a light weight infrastructure to build HTTP light wight services.
SignalR Programming Models
Two programming models are available:
- Persistent Connections
- Hubs
Persistent Connections offer a low level API similar to Socket Programming, however, the API provides semantics to Connect, Reconnect, broadcast to all clients, groups or individuals. Persistent Connections offers great flexibility, however, programmers are responsible for sending and receiving the data.
Hubs is a high level API which is built on top of Persistent Connections. The way it works is very similar to RPC from client-server and server-client. It is very simple to use and the framework generates automatically a client proxy (JavaScript) representing the server side methods that the client can call. Hubs work like a controller in ASP.NET MVC but it is not a controller and it does not inherits from any controller abstraction.
SignalR has an excellent reach in terms of pushing data to different clients because the SignalR team has implemented a rigorous failover mechanism to be able to support different clients and technologies. Here is how SignalR attempts to establish its communications depending on the environment and supported technology:
- First it will try to connect using WebSockets which is a fairly new technology. However, this technology needs to be supported by the environment (OS and clients).
- If WebSockets fails, then it will try to use Server Sent Events.
- If Server Sent Events fails, then it will try to use Forever Frame which uses a hidden IFrame. For this example, launch IE debugging tools and under Networking we can see the Forever Frame at work.
- If all of the above fails then Long Polling is used. Long Polling opens a connection to the server and waits until data is available. Once the data is available then it is polled and the client connects again waiting for data to be available again.
Getting Started with SignalR
To get started you need to install at least five packages. I have tried creating SignalR projects on Visual Studio 2010 Ultimate and on Visual Studio 2012 Express for Web. In either case you can add the required packages using NuGet.
| The sample project gives a quick flavor of how well this real time technology works. The SignalR team at Microsoft is really doing a great job! |
The packages that you need are:
- Microsoft ASP.NET SignalR
- Microsoft ASP.NET SignalR Web Components
- Microsoft ASP.NET SignalR JavaScript Client
- Microsoft ASP.NET SignalR Core Components
- Microsoft ASP.NET SignalR OWIN
The SignalR team at Microsoft has worked very hard to make the experience of implementing real time push services for web solutions seem painless so in this way we can concentrate on building our business solutions.
The Rental Vehicle Problem with SignalR
This solution uses a Hub API implementation. The structure of my project is depicted in this figure:
| Note the SignalR JS library added. |
The Rent a Truck problem is a simplified rise problem where users are rising each other to get the resource they want. Available rental vehicles are limited, therefore, the basic idea is first comes-first served. What the Rent a Truck does for registered users is notify them about the current state of the available collection of rental vehicles when changes occur.
SignalR can be used to solve much more complex problems such as The Assignment Problem, which is the core of the algorithm use in auctions, so bidders do not need to be polling periodically "am I winning?... am I winning?... oh, I lost!" and instead are notified when other bidders place a bid real time so they can react to that if they have more money in their pockets.
SignalR can be used to solve much more complex problems such as The Assignment Problem, which is the core of the algorithm use in auctions, so bidders do not need to be polling periodically "am I winning?... am I winning?... oh, I lost!" and instead are notified when other bidders place a bid real time so they can react to that if they have more money in their pockets.
The Hub
The RentalShopHub class is defined in the above figure. Note that this class derives from Hub and that the class is decorated with the attribue HubName. This attribute is the name, rentalShop, that clients are going to know the service by, and it will be used when making a connection.
![]() |
| HubName is used by clients to connect to the hub. The client uses a dynamically generated JavaScript proxy, hubs, which is sent to the client. |
Also note in the hub class the void methods RentVehicle and ReturnAllRentals. In the body of these methods there is a call to a function which is not implemented anywhere, rentalStatus, which takes a RentalViewModel objact as a parameter. This is a dynamic expression which is compiled on the fly and this is provided by the framework. All I care at this point is that I want to return to the client a ViewModel object.
![]() |
| This is the client receiving a pushed notification from the server |
Another method of interest, and the way it is handled from the client, is RentalsState, which takes no parameters and returns a ViewModel containing the state of the model of the system.
SignalR has been optimized for asynchronous communication therefore the client needs to wait until this method is done before it does anything to the data sent to the client. The above figure also gives a hint at the fact that we need to wait until the connection has been started before we handle the rest of the UI.
The Client
I am not going to dedicate time to the actual markup. You can take a look at the HTML and CSS from the project download. The client JavaScript is the interesting part.
Line 4 stands out. This mysterious script src="/signalR/hubs" is a JavaScript proxy which is produced by SignalR so we can reference methods in the server through JavaScript. This is the heart of the simplicity of SignalR. If this solution was using SignalR Persistent Connections API then this proxy would not be provided and we would be responsible for creating and managing this duplex type of communication. Just think that this is the JavaScript proxy which is promised by the framework and that it is send down the wire in the response to the first GET from the client.
Initially ignore from line 22 to line 41, the story does not start there. The initial magic is between line 44 and line 80. On Line 11 the connection object is created using the SignalR library and on Line 44 the connection is started. Note that we need to wait until the connection has started before anything else is done.
| Dynamically generated Hubs. This JavaScript proxy is provided by SignalR only when using the Hub high level API |
Initially ignore from line 22 to line 41, the story does not start there. The initial magic is between line 44 and line 80. On Line 11 the connection object is created using the SignalR library and on Line 44 the connection is started. Note that we need to wait until the connection has started before anything else is done.
Once the conneciton has been created successfully the client invokes the server method on Line 47 to get the initial state of the system.
| This is what we see in the browser debugger. Not that every time you hit F5 to refresh the page a new connection is created with a different connection Id. |
Note the Forever Frame being used as the type of transport for the connection. My computer is running Win7 Pro which does not support the use of WebSockets. This is part of the SignalR failback mechanism in action. Thank you SignalR Team! You are a bunch of Batmans!
Now redirect your attention to line 72. In this block the rent button click event has been handled. Note how the client is calling the server method rentVehicle passing the value of the checked radio button. On teh server, inside of RentVehicle the server notifies all connected clients the current rental status (see line 40 of the Hub above).
Register the Default Hubs Route
SignalR will not work if the route is not set. The following piece of code will get it up and running. Even if you implemented other hubs in your solution, this code is the default medicine and your solutions will work. Note that I have two SignalR hubs in my project; a Chat using Hubs (when I was learning socket programming it was uncool not to develop one's own chat), and the Rent a Truck hub.If something frails, if you get strange errors during negotiation the transport, or anything then write a comment bellow and we will try to troubleshoot it together.
Conclusion
SingalR is a new framework created by Microsoft which allows ASP.NET developers add real time functionality to their applications. Using this framework and using its Hub high level API and in a few lines of code, a simple real time push notification solution was created to resolve the Rent a Truck (select a resource) problem.
What is Next
My interest now resides in researching how external events can trigger a notification push to registered clients using SignalR. The particular scenario could be described as follows: the push service would be observing changes in a database and when the change takes place then registered clients (connected clients) are notified of the change using SignalRThe project
The project which is available for download was created using Visual Studio 2012 Express for Web. I created this article while listening to "The Dark Knight Rises" OST by Hanz Zimmer. Wicket!
To run the solutions unzip and build the project (Visual Studio Express 2012 for Web) and expand any of the hub folders (RentaTruck or ChatHub), then right click on the index file and select to View in Browser. then launch other browsers (Chrome, Firefox, Opera) and paste the url of the running SignalR and go at it.
Its is easy... build your own real time SignalR solution and brag about it.
The Drawings
I drew all images by hand and scanned them, which I thought was pretty cool! I used to be pretty good at drawing when I was a child... long time ago... yes, I was a child once. I remember that after I watched the film "Spartacus" 1960, with Kirk Douglas, and "Helen of Troy" 1956, I used to spend countless hours drawing epic battles between Roman and Greek soldiers... those were the good days! Today I see the cycle starting again in my children. I love them!
References
- SignalR http://www.asp.net/signalr
- SignalR GitHub Samples: https://github.com/SignalR/Samples
- Quick Starts: https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs
- Quick Starts: https://github.com/SignalR/SignalR/wiki/QuickStart-Persistent-Connections
- SignalR Security: http://www.asp.net/signalr/overview/security/introduction-to-security
- http://www.asp.net/signalr/overview/security/hub-authorization
- http://www.asp.net/signalr/overview/security/persistent-connection-authorization







