Thursday, March 5, 2015

First SignalR Codes

Lets start SignalR with hands on ,

Not like usual chat demos in SignalR , We are going to make counter application which displays number of connected nodes to the web

1. Create New empty ASP.Net web project with visual studio
2. The install following Nuget on the Application
   Microsoft.AspNet.SignalR
 After Installing SignalR Your solution automatically get the Scripts for signal R














3. Add Hub Class to the solution by Add -> New Item -> SignalR Hub Class(v2)
Name it as CountHub 








4. Then Modify the CountHub with following code
[HubName("hithub")]
   public class CountHub : Hub
   {
       public static int count = 0;
 
       /// <summary>
       /// Once user open window with this URL hitter called 
       /// </summary>
       public void Hitter()
       {
           count++;
           Clients.All.OnHit(count);
       }
 
       /// <summary>
       /// User disconnected OnDisconnected automatically fired 
       /// </summary>
       /// <param name="stopCalled"></param>
       /// <returns></returns>
       public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
       {
           count--;
           Clients.All.OnHit(count);
            return base.OnDisconnected(stopCalled);
       }
   }

in here HubName attribute should be start with simple letter. Otherwise it will not working

In here Client.All broadcast with all connected clients .

5. Then add Owin Start up class to build the start up with the web application Named it as StartUp



6. add Configuration for SingnalR in Startup
public void Configuration(IAppBuilder app)
       {
           app.MapSignalR();
       }

8. Now we are done with SignaR server side coding. Lets build HTML client for SignalR
Create html page in solution (default.html) and refer signalR and Jquery to the web page

<script src="Scripts/jquery-1.6.4.js"></script>
   <script src="Scripts/jquery.signalR-2.2.0.js"></script>
  
9. Then add following script after it . Comments discribes the code

<script type="text/javascript">
    $(function () {
        //Create hub connection 
        var conection = $.hubConnection();
 
        //create hub proxy 
        var hub = conection.createHubProxy("hithub");
 
        //get message with the hub proxy to latest update in count 
        hub.on("OnHit"function (count) {
            $('#count').text(count);
        });
 
        //Call hitter 
        conection.start(function()
        {
            hub.invoke('hitter')
        });
    })
</script> 
 
 
10. Modify the body of html as follows

<body>
    <h2 id="count">0</h2>
</body>
 
 

Run and enjoy,


Happy coding







Full Code 
http://bit.ly/1G1YOze

0 comments: