Introduction to SignalR in ASP.NET MVC 4 by building Trading Trends Application

Author: Veeresh Rudrappa. Date: March 19, 2013

In the coming days there is going to be lot of stress on building more interactive web applications. SignalR is one such framework in .NET technology which helps to build interactive, real-time, multi user applications. Let us learn what is SignalR by building a simple Application in ASP.NET MVC 4.

When I wanted to experiment with SignalR I was trying to think of a Scenario where I could use it and build a simple application, just to get myself started with SignalR. So here it is, assume you have a trading agency with 10 to 15 employees who receive calls from your clients and execute their order of buying or selling stocks. Suppose one of the clients calls in and asks what is your general trading strategy for "Google" today, are your clients/investors dumping "Google" stocks or piling it up? This application here, will let the employees or possibly even the clients if you have provided them with a web portal to know about the trading trends of any stock.
All right, might sound a bit weird :), but it was just enough to get me started with SignalR. Bare in mind this application no way complete.

Trading Trends

SignalR makes it simple to add real-time web capabilities to your ASP.NET application, using WebSockets if available and automatically falling back to other techniques when the browsers are not compatible. Using WebSockets alone could be quite cumbersome and you will never know if the client browsers would be supporting or not. But with the use of SignalR you can be rest assured that it would make the right choice of which technology to use underneath to keep the persistent connection going. It will free the developers from worrying about the compatibility issues and let SignalR manage the connections between client and server. SignalR includes components at both server and client side which will facilitate message delivery and reception in real time.

There are two kinds of communication possible between server and client with SignalR.

a. Persistent Connection
PersistentConnection facilitate lower level socket connections between client an server to exchange messages/data. Each client connection to the server is identified by a connectionID. The server has the capability to either communicate with individual clients, or broadcast to all the clients or even to selectively communicate with a group of clients.
You would have to implement the PersistentConnection class on the server side and add the URL mapping in the Application_Start method to link the incoming clients with the PersistentConnection class. From the client side you would be connecting to the same URL which gets mapped in the Application_Start. I know, it is getting little confusing here but you will understand when we get to the examples.
b. Hubs
Hubs provide a higher level RPC framework over a PersistentConnection. If you have different types of messages that you want to send between server and client then hubs is recommended so you don't have to do your own dispatching. This can also be done using Persistent Connections but using Hubs makes it a lot easier. Hubs are higher level API to persistent connection.

Ok lets get started with he application:
I'm developing on visual studio 2012, you can get your free copy from here

Step 1: Install the SignalR libraries. Download and Install ASP.NET and Web Frameworks 2012.2.

ASP.NET and Web Frameworks 2012

Step 2: Create new ASP.NET MVC 4 web application, select empty project and add a Home Controller
ASP.NET MVC 4 web application

empty project

Home Controller


Step 3: Right Click on Models and add a SignalR Hub class. TradingHub.
SignalR Hub Class

Step 4: Add a public method which can be called from the client once the connection is established. Every time a client sends a message to the server an object of type TradingHub would be created and corresponding methods would processed based on which method in the hub was invoked by the client.

                                    using System;
                                    using System.Collections.Generic;
                                    using System.Linq;
                                    using System.Web;
                                    using Microsoft.AspNet.SignalR;

                                    namespace StockTrading.Models
                                    {
                                        public class TradingHub : Hub
                                        {
                                            public void UpdateTrade(string action, string numberOfShares)
                                            {
                                                Clients.All.NotifyTradeAction(action, numberOfShares);
                                            }
                                        }
                                    }
                                    

Step 5: Add the line RouteTable.Routes.MapHubs(); in the Application_Start method of your GLobal.asax file. It would initialize the default hub route to be as /signalr and you would be specifying the same from your client code. Make sure you add that line just above RouteConfig.RegisterRoutes(RouteTable.Routes); , otherwise you will get an error saying /signalr not found. I got this hack from the stackoverflow.com.

Step 6: Add a view page to your HomeController. You can copy the code below. I have included my master page, so you might have to get your styling right if you want the application to look the same as in screenshots.


@{
ViewBag.Title = "Home";
Layout = "~/Views/Shared/_Layout.cshtml";
}

@{ String appRoot = ( Request.ApplicationPath == "/" ) ? String.Empty : Request.ApplicationPath; }

Trading Trends

Loading graph...

Sell / Buy Stocks

Stock Name: Google

Number of Shares:
    

Step 7: Client Side JavaScript. Since its a MVC application make sure u give the default url as ~/signalr/hubs instead of /signalr/hubs. I had a tough time figuring this one out.








                                         

Step 7: Download your free copy of JS charts from here.Add it to your scripts folder.


                                         

Step 8: Add GraphGenerator.js to your Scripts folder. Its has the logic for generating graphs.

function GraphGenerator() {
    return this;
};

GraphGenerator.currentTotal = 0;
GraphGenerator.graphArray = null;
GraphGenerator.currentIndex = 2;

GraphGenerator.generateGraph = function (action, numberOfShares) {
    if (action == "Buy") {
        var num = parseInt(numberOfShares);
        GraphGenerator.currentTotal += num;
    }
    if (action == "Sell") {
        var num = parseInt(numberOfShares);
        GraphGenerator.currentTotal -= num;
    }

    GraphGenerator.graphArray.push([GraphGenerator.currentIndex, GraphGenerator.currentTotal]);
    GraphGenerator.currentIndex++;

};
                                        

Step 8: Build and run your project. Copy the URL and open it in two more new instances of your browser. Now start buying and selling stocks. You will notice graphs getting updated in real time as soon as stock are bought or sold. Note: With the way the graph logic is designed now, the graph of the clients coming in late wont sync with previous transactions. So make sure you have opened all of your browsers, how many ever you wish to and only then start trading stocks.

Trading Trends

Hope this Helps :)
comments powered by Disqus