Posted by & filed under Content - Highlights and Reviews, Programming & Development.

codeA guest post by Samuel Jack, the founder of TruthVine, a start-up that takes the hassle out of sharing audio sermons on church websites. He is also a freelance .Net consultant, working on projects as diverse as Flow, music making software for DJs, to RavenDb, the NoSQL database. He blogs at blog.functionalfun.net, and you can follow him at @samuel_d_jack.

You might have heard of SignalR, a real-time communications library for the web from Microsoft. It’s open source, it’s hip (it supports WebSockets!) – and just about all the Getting Started tutorials are about Chat applications. How many times have you had to write a Chat application in your career? I’d bet a two-toed sloth could keep count for you on one foot and still have digits to spare.

I want to show you how SignalR can solve elegantly a problem you will almost certainly have faced at some point: reporting progress of long-running operations on web pages. I say you’ve probably faced the problem – and if you’re anything like me, you’ve probably ducked out of solving it too, leaving your web site visitors in the tender care of a wait cursor while your web application does its thing in its own sweet time. Getting a server to report back to a web page has always been a fiddle, and many of the techniques in common use feel like hacks. SignalR changes all of that.

Let’s warm up in this article by finding out just how easy it is to get started with SignalR, and in the next installment you’ll see how to use SignalR to solve the progress-reporting problem.

SignalR began as an open-source hobby project by two members of the ASP.NET team, David Fowler and Damian Edwards, back in late 2011. Seeing its fan club growing rapidly, Microsoft officially adopted it as part of ASP.NET at the end of 2013. You must be targeting .NET 4.5 on your server to use SignalR (though IIS is not required – self-hosting is fine). On the client side, there’s a jQuery plugin that is compatible with all modern browsers (IE 8 and up). There are also SignalR client libraries for .NET and Xamarin’s mobile frameworks.

Let’s get started with a very simple example: showing a count of the number of people currently viewing a page.

Installing SignalR

First, you need to add SignalR to your ASP.NET MVC project: following recent trends, Microsoft ships SignalR as packages on NuGet, rather than as part of the core framework. So to install SignalR, open the Package Manager Console and type:

Then you’ll need to make sure your SignalR components get wired up. You do this in the Startup.cs class, by adding a call to app.MapSignalR():

Communicating with Hubs

The primary building blocks SignalR gives you are called Hubs. Hubs enable two-way communication between the client and server using a Remote Procedure Call (RPC) model. When a client connects to a Hub, it is given a proxy object. The client invokes methods on that proxy, SignalR sends the message over the wire, and the method will be invoked on the server. Likewise, the server can invoke methods on the Hub, and all the connected clients will have their corresponding method called.

Let’s create a very simple Hub. Add this class to an empty ASP.Net MVC project (it doesn’t matter where it goes – SignalR will find it using Reflection):

As you can see, Hubs are derived from the Hub base class. Hub functions very much like Controller in ASP.Net MVC. One Hub instance will be instantiated for each incoming request, the appropriate methods will be called on the class depending on what action the client has taken, and then the instance will be disposed of.

In this case, each time a client connects or disconnects, we increment a counter (which we store in a static field, since individual Hub instances never stick around). Having updated the counter we then notify all connected clients by calling Clients.All.viewerCountChanged(viewerCount). Clients.All returns a dynamic object on which we can call any method we like. Whenever we do so a callback of the same name will be invoked on all of the connected clients. One important note, though, is that you should always have a public method on your Hub class for every method you intend to invoke on the client, so that SignalR knows what methods to generate on the proxies.

Connecting to SignalR with JavaScript

Here’s how SignalR plays out on the client side:

The first of the two script libraries referenced is added to your project when you install the SignalR package (check this though – the version number might have changed since this article was written). The second script is dynamically generated at runtime by SignalR using Reflection on all of the Hub-derived classes in your assembly. It provides the JavaScript proxies to your server-side hubs.

To set things up then, the first thing we have to do is get hold of the proxy for our PageViewersHub, which we do using $.connection.pageViewersHub (note that SignalR has helpfully translated the name from the Pascal-cased world of .Net to the Camel-cased world of JavaScript).

Once we have the proxy, we can register a callback on it, so that every time the sever says viewerCountChanged, we can do something about it, and update the appropriate span in this case.

Finally, we call $.connection.hub.start() to initiate the connection with the server.

Conclusion

Try running the sample application and opening the page in multiple tabs (you’ll find all of the source code here). Each time you open it in a new tab, you’ll see the count go up on all of the pages. Each time you close a tab, it will go down.

With your appetite whetted by SignalR’s simplicity, stay tuned for the next episode where we put it to work on a real-life problem.

Look below for some great SignalR resources from Safari Books Online.

Not a subscriber? Sign up for a free trial.

Safari Books Online has the content you need

SignalR: Real-time Application Development is a hands-on, step-by-step guide that will take you from the basics of SignalR to more advanced techniques, such as making your application cloud ready and making it scalable. If you want your applications to be enterprise grade then SignalR, together with this book, is the answer.
ASP.NET MVC 4 Mobile App Development helps you to develop next generation applications, while guiding you to deal with the constraints the mobile web places on application development. By the end of the book, you will be well versed with all the aspects of mobile app development. This book also contains a good section on SignalR.
Real World Windows 8 Development is for .NET developers wanting to utilize their existing skills in XAML and C# towards building a Windows 8 application. On the fence about how your C# and .NET skills apply in the new WinRT world? Have a dream application idea that you slowly want to build up? This book is for you. Be sure to also look at the Signal R sections.

Tags: ASP.NET, ASP.NET MVC, Javascript, jQuery, Microsoft, open source, SignalR, WebSockets, Xamarin,

Comments are closed.