Working examples using Signalr and asp.net MVC3

//Working examples using Signalr and asp.net MVC3

Working examples using Signalr and asp.net MVC3

By |2012-11-25T15:41:36+00:00November 25th, 2012|Categories: Programming|1 Comment

In this tutorial  I am going to talk about a real examples that we need to implement in most of projects.

Step 1: Create Application

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application “Internet Application” (Make sure it’s .Net Framework 4).

Step 2: Add SignalR Package

Right click on references and click Manage NuGet Packages. Search for SignalR and click install. Or use NuGet package manager concole and install the SignalR package using

Install-Package SignalR

Step 3: Add Hub

Create a new Class named Chat in a new folder in the solution “Name it as u want”

 [HubName("chat")]
 public class Chat : Hub
 {
 }

Note the attribute HubName above the class name, that attribute is for naming the hub during calls as we going to see later

Step 4: Add Sending Functions

[HubName("chat")]
public class Chat : Hub, IDisconnect
{
  public void Send(string message, string clientId = "", string group = "")
  {
     if (!string.IsNullOrWhiteSpace(group))
     {
           //All clients in that group
           Clients[group].addMessage(message);
      }
      else if (string.IsNullOrWhiteSpace(clientId))
      {
           //All Clients
           Clients.addMessage(message);
      }
      else if (!string.IsNullOrWhiteSpace(clientId))
      {
           //The current caller
           Caller.addMessage(message);
           //The client with the clientId
           Clients[clientId].addMessage(message);
       }
   }
}

You can notice that the function has three parameters a required parameter message,two optional parameters clientId and group so if we need to send message to all users live in the application we can send only message to send function and leave, if we need to send message to only one user all we have to do is to add client id with message if we want to send a message to a specific group send group name with message only

Step 5: Change user Id

the main problem for us now is the client id, Because it is changeable with each single request to the page so we need to identify users so we can add to helpers the following helper class that will help us to resetting the connection id in hub

 public class UserIdClientIdFactory : IConnectionIdGenerator
    {
        public string GenerateConnectionId(IRequest request)
        {
            //Generates user GUID Id to identify each user with a unique id
            return Membership.GetUser().ProviderUserKey.ToString();
        }
    }

because i am using membership to login and security i used membership.GetUser function to get user id. Remember id here is a Guid so if you are using your own implementation and not using membership you have to generate a unique Guid id for each person.

Step 6: Register new user id to Application

Now we have to register the newly generated user id to the application we are going to add the following code in Global.asax

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

// register user id to SignalR Global Host
GlobalHost.DependencyResolver.Register(typeof(IConnectionIdGenerator), () => new UserIdClientIdFactory());
        }

Now in application start and while user opened a new session to your application the new Id we just made will be assigned to him and we can ue it to identify each user and send.

Step 7: Adding user to group

To add user to group i used action method in my HomeController to do that work

 public void AddToGroup(string groupName)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
            context.Groups.Add(Membership.GetUser().ProviderUserKey.ToString(), groupName);
        }

Step 8: Add client code

Append javascript references to the head of the page as follows

<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>

As you can notice there is a /signalr/hubs file included but its not in the project because its dynamically generated file in run time

Append the following javascript

<script type="text/javascript">

    $(function () {
        // Create connection with name chat. chat is hub name that we declared in Hub
        var connection = $.connection.chat;

        // Declare a function on the chat hub so the server can invoke it. Add message method is responsible for adding messages to the client
        connection.addMessage = function (message) {
            $('#messages').append('<li>' + message + '</li>');
        };

        // Send message
        $("#broadcast").click(function () {
            // Call the chat method on the server
            connection.send($('#msg').val(), $('#userId').val(), $('#group').val());
        });

        var timeout = null;
        var interval = 5000;

        // Event that will fire when server state changed
        $.connection.hub.stateChanged(function (change) {
            if (change.newState === $.signalR.connectionState.reconnecting) {
                timeout = setTimeout(function () {
                    $('#state').css('backgroundColor', 'red')
                    .html('The server is unreachable...');
                }, interval);
            }
            else if (timeout && change.newState === $.signalR.connectionState.connected) {
                $('#state').css('backgroundColor', 'green')
                        .html('The server is online');

                clearTimeout(timeout);
                timeout = null;
            }
        });

        // Start the connection
        $.connection.hub.start().done(function () {
            // Fetch client id and display
            var myClientId = $.connection.hub.id;

            $('#my-id').html(myClientId);
        });

    })
</script>

I added commented lines above each line to declare how it works.

Append the following Html to your page

<div>
    User ID
    <div id="my-id">
        0
    </div>
</div>
<div>
    Message:
    <input type="text" id="msg" />
    User Id:
    <input type="text" id="userId" />
    Group:
    <input type="text" id="group" />
    <input type="button" id="broadcast" value="broadcast" />
    <ul id="messages">
    </ul>
</div>

You can download the sample code from here

About the Author:

One Comment

  1. vikram 4th December 2013 at 3:23 pm - Reply

    nice blog….can u pls upload sending,accepting and rejecting friend request in asp.net mvc3 or 4 pls…thanks in advance

Leave A Comment