MVC, Programming

SignalR to create a simple Chat system in MVC5

In this post I am trying to demonstrate the basic of SignalR and how it works. All I am going to do is create a simple Chat Messaging System using SignalR in MVC5 and demonstrate the output in my mobile simulator in two separate instances. But before that let me give you a brief of what SignalR is and for more details you can have a look into Microsoft site to get an insight of SignalR.

SignalR provides a facility to have server code push content to connected clients instantly instead of having the server to wait for a client to request new data. It is a simple API for creating server-to-client remote procedure calls (RPC) that calls the JavaScript functions in client browsers from server side .NET code. It uses available WebSocket transport. We can use SignalR to build modern websites and apps with live, two-way communication like stock applications, auctions, voting capabilities, quizzes and polls, games, etc., and it is build on OWIN (Open Web Interface) specification for .NET. It works like a Hub and Spoke or rather should I say hubs and clients.

Now that you know a little bit of what SignalR is, lets get started with the Chat application development.

Create a new MVC5 application without any Authentication mode in Visual Studio 2013.

image

Once the application is created, install SignalR package using Nuget Package manager console with the following command install-package Microsoft.AspNet.SignalR

PM> install-package Microsoft.AspNet.SignalR
Attempting to resolve dependency 'Microsoft.AspNet.SignalR.JS (≥ 2.1.2)'.
Attempting to resolve dependency 'jQuery (≥ 1.6.4)'.
Attempting to resolve dependency 'Microsoft.AspNet.SignalR.SystemWeb (≥ 2.1.2)'.
Attempting to resolve dependency 'Microsoft.AspNet.SignalR.Core (≥ 2.1.2)'.
Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.4)'.
Attempting to resolve dependency 'Owin (≥ 1.0)'.
Attempting to resolve dependency 'Microsoft.Owin (≥ 2.0.1)'.
Attempting to resolve dependency 'Microsoft.Owin.Security (≥ 2.0.1)'.
Attempting to resolve dependency 'Microsoft.Owin.Host.SystemWeb (≥ 2.0.1)'.
Installing 'Microsoft.AspNet.SignalR.JS 2.1.2'.
You are downloading Microsoft.AspNet.SignalR.JS from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.SignalR.JS 2.1.2'.
Installing 'Newtonsoft.Json 6.0.6'.
Successfully installed 'Newtonsoft.Json 6.0.6'.
Installing 'Owin 1.0'.
Successfully installed 'Owin 1.0'.
Installing 'Microsoft.Owin 2.0.2'.
You are downloading Microsoft.Owin from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/aspnetcomponent_rtw_enu.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.Owin 2.0.2'.
Installing 'Microsoft.Owin.Security 2.0.2'.
You are downloading Microsoft.Owin.Security from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/aspnetcomponent_rtw_enu.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.Owin.Security 2.0.2'.
Installing 'Microsoft.AspNet.SignalR.Core 2.1.2'.
You are downloading Microsoft.AspNet.SignalR.Core from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.SignalR.Core 2.1.2'.
Installing 'Microsoft.Owin.Host.SystemWeb 2.0.2'.
You are downloading Microsoft.Owin.Host.SystemWeb from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/aspnetcomponent_rtw_enu.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.Owin.Host.SystemWeb 2.0.2'.
Installing 'Microsoft.AspNet.SignalR.SystemWeb 2.1.2'.
You are downloading Microsoft.AspNet.SignalR.SystemWeb from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.SignalR.SystemWeb 2.1.2'.
Installing 'Microsoft.AspNet.SignalR 2.1.2'.
You are downloading Microsoft.AspNet.SignalR from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.SignalR 2.1.2'.
Adding 'Microsoft.AspNet.SignalR.JS 2.1.2' to SignalR.Demo1.
Successfully added 'Microsoft.AspNet.SignalR.JS 2.1.2' to SignalR.Demo1.
Removing 'Newtonsoft.Json 5.0.6' from SignalR.Demo1.
Successfully removed 'Newtonsoft.Json 5.0.6' from SignalR.Demo1.
Adding 'Newtonsoft.Json 6.0.6' to SignalR.Demo1.
Successfully added 'Newtonsoft.Json 6.0.6' to SignalR.Demo1.
Adding 'Owin 1.0' to SignalR.Demo1.
Successfully added 'Owin 1.0' to SignalR.Demo1.
Adding 'Microsoft.Owin 2.0.2' to SignalR.Demo1.
Successfully added 'Microsoft.Owin 2.0.2' to SignalR.Demo1.
Adding 'Microsoft.Owin.Security 2.0.2' to SignalR.Demo1.
Successfully added 'Microsoft.Owin.Security 2.0.2' to SignalR.Demo1.
Adding 'Microsoft.AspNet.SignalR.Core 2.1.2' to SignalR.Demo1.
Successfully added 'Microsoft.AspNet.SignalR.Core 2.1.2' to SignalR.Demo1.
Adding 'Microsoft.Owin.Host.SystemWeb 2.0.2' to SignalR.Demo1.
Successfully added 'Microsoft.Owin.Host.SystemWeb 2.0.2' to SignalR.Demo1.
Adding 'Microsoft.AspNet.SignalR.SystemWeb 2.1.2' to SignalR.Demo1.
Successfully added 'Microsoft.AspNet.SignalR.SystemWeb 2.1.2' to SignalR.Demo1.
Adding 'Microsoft.AspNet.SignalR 2.1.2' to SignalR.Demo1.
Successfully added 'Microsoft.AspNet.SignalR 2.1.2' to SignalR.Demo1.
Uninstalling 'Newtonsoft.Json 5.0.6'.
Successfully uninstalled 'Newtonsoft.Json 5.0.6'.

Once the package is installed Right-click the project and add an OWIN Startup Class with the following code.

image

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
    }
}

Now add an Action result in the HomeController named Chat and create a View out of it.

public ActionResult Chat()
{
    return View();
}

Once the View got created, create another folder named Hubs and add a class named ChatHub.cs with the following code

image

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        Clients.All.addNewMessageToPage(name, message);
    }
}

Now we need to open our _Layout.cshtml page and add the following script references at the bottom in Scripts.Render section.

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("/Scripts/jquery.signalR-2.1.2.min.js")
@Scripts.Render("/signalr/hubs")
@Scripts.Render("~/bundles/bootstrap")

All set we need to update our Chat.chtml view with code to input a user name and then send messages to another user. The client script in this view will be called by the Hub we have created which means two way communication will happen with client calling the Send method from the Hub and then displaying the message after the call back function.

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

Enter your name:
    </div> @section scripts { $(function () { // Reference the auto-generated proxy for the hub. var chat = $.connection.chatHub; // Create a function that the hub can call back to display messages. chat.client.addNewMessageToPage = function (name, message) { // Add the message to the page. $('#discussion').append('
  • ' + htmlEncode(name) + ': ' + htmlEncode(message) + '
  • '); }; // Get the user name and store it to prepend to messages. $("#Submit").click(function () { $('#displayname').val($("#name").val()); }); //$('#displayname').val(prompt('Enter your name:', '')); // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); }); // This optional function html-encodes messages for display in the page. function htmlEncode(value) { var encodedValue = $('
    ').text(value).html(); return encodedValue; } }

    Now what I am trying to do is open two instances of my mobile simulator and send messages between two users Joy and Sam. What you will see is when you try to send a message from Joy to Sam, the mobile instance of Sam will display the message and vice-versa will happen. I am using my Electric Plum Simulator which is a good option to review responsive UI in various devices. You can download the same from this link but you need to get a paid version to use it.

    This is the output of the two instances of the simulator from two users

    image

    That’s all for the basic implementation of SignalR

    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