Home > asp.net features > Broadcasting website data using SignalR in MVC

Broadcasting website data using SignalR in MVC

SignalR is a cool API in dotnet framework which you can use to show real time data in your application. You can broadcast real time data to all the connected clients(browsers) once data is ready on server side.

It generates javascripts when rendering on the client side. But you don’t have to worry about all the proxy javascripts as signalR takes care of all those things. All you have to do is just call your javascript function from the server side.

To add signalR in your project go to Nuget Package Manager and search for signalR , you will  see Microsoft ASP.NET SignalR at the top of the list just click install. It will add all the references required to run it. If your project doesn’t have a Scripts folder it will add a Scripts folder and import jquery and jquery-signalR libraries.

At this stage you’ve got all the required references and scripts now its time to add the SignalR startup class so we can tell the OWIN so it can configure it.

Startup class is like;


using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(DeepASP.SignalRMVC.SignalRStartup))]
namespace DeepASP.SignalRMVC
{
public partial class SignalRStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

I added this startup class in App_Start folder as MVC has already created this folder with the startup classes. But you can keep wherever you want. Now add the SignalR Hub class. If you right click and add new item it should be under signalR templates but if it is not, don’t worry just add a new class and inherit it from abstract class–

 Microsoft.AspNet.SignalR.Hub

Lets name this class as “SignalRHub”. You can name anything but just remember this is the hub which you will use in the javascript side. Although you can change the display name by decorating this class with attribute

 [Microsoft.AspNet.SignalR.Hubs.HubName("DisplayName")].

This class looks like;

namespace DeepASP.SignalRMVC
{
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
[HubName("Broadcaster")]
public class SignalRHub : Hub
{ }
}

Logically that’s all you needed for signalR. Now you want to access the Hub so you can call javascript function from server side, right? YES. OK lets add another class Broadcast.cs as;


namespace DeepASP.SignalRMVC
{
    using Microsoft.AspNet.SignalR;
    using System;

    public class Broadcast
    {
        private static Lazy<IHubContext> context = new Lazy<IHubContext>(() => GlobalHost.ConnectionManager.GetHubContext<SignalRHub>());

        private static IHubContext Broadcaster
        {
            get
            {
                return context.Value;
            }
        }

        public static bool SendDataToAllConnectedClients(string data)
        {
            Broadcaster.Clients.All.JavaScriptFunction(data);
            return true;
        }
    }
}

SendDataToAllConnectedClients method calls javascript function “JavaScriptFunction” passing a string parameter. You can pass as many complex objects in JSON format as you want. Just for clarity I call the javascript side function name as JavascriptFunction but you will give a meaningful and purposeful name. Now we will write this javascript function. Like for this post I created another controller called BroadcastController.cs and its view. Now as because this view will be responsible for broadcasting the message sent from server we will add the required .js libraries in this view:

<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/signalr/hubs"></script> 
<script> 
var broadcaster = $.connection.Broadcaster; 
broadcaster.client.JavaScriptFunction = function (d) { 
   document.getElementById("data").innerHTML = d; 
} 
$.connection.hub.start(); 
</script> 

Order of javascript libraries DOES matter. Now this is where we are subscribing the javascript function “JavaScriptFunction” which we are calling from server side. For this demo I was just sending a string html from server side but you can write your logic for this function here when you are subscribing.

Yep that’s all signalR is about. If you are interested in downloading this demo just click here.

Well here are some important things to remember before you going to move into production.

Pre-requisites of SignalR2:

  • Dotnet Framework 4.5
  • The user for which Application (IIS) is running must have full trust
  • IIS must be running in Managed mode NOT  Classic.
  • IIS 7 or greater (Websocket requires IIS8)
  • jQuery version must be greater  than 1.6

If you want more control on server side then you might want to look into this http://socket.io/docs/.

Well here are some of the cool articles I came across while researching some of the issues when I was working on my signalR project;

http://www.asp.net/signalr/overview/getting-started/supported-platforms

http://bradwilson.typepad.com/blog/2012/07/webstack-of-love.html

http://www.asp.net/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr

Advertisements
Categories: asp.net features
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s