SignalR Message Conversation App Using ASP.NET MVC 5 In Real Time Scenario

Introduction

SignalR is an open library which can be used to integrate in real time in your applications. There are some areas where SignalR can come in handy to make your application integrated, and more responsive to the end user. Your server responds very quickly to the client when a request is made.

Description

SignalR gives two directional communication between server and client.

SignalR can be used in faster notification message to the end user and in another sense if any problem exists in the server side then it can be notified by using signalR concept.

SignalR can be used in file uploading , file downloading and how much percentage it has completed, and how much time it will take. So, in these fields we can implement signalR concept for better results.

In more cases signalR is used for Chat application purposes and in the integration of Facebook, Google Plus etc.

Most Used Fields

SignalR can be used to show the result of current actions made in server controls.

For example

In webgrid of Asp.Net MVC when we perform Crud operations the signalR shows the task the record using the Id entered , updated or deleted.

It just shows like system task manager.




There are two sides -- One is Server Side and another one is Client Side.

The Hub in server side invokes the client side function from Hub Proxy.

Here a response is made.


Here The Hub Proxy in Client Side invokes the server side function from Hub.

Here Request Is Made.

signalR can be hosted using Open Web Interface in .NET called OWIN in signalR In another sense it can be self-hosted. It has the ability to send the contents of a server to currently connected clients.

Remote Procedure Calls (RPC)

SignalR provides an API which helps in making the call between the server and the client. The server calls the functions on the client side and the client side calls the server side. That somehow is called "Server-Push".

SignalR Transport Medium

It is integrated with ASP.NET web applications, it can be implemented by other .NET Client side Application like Windows Phone or even Windows 8/10 application.

It has four transport mediums like >>

  1. WebSocket.
  2. Server-Sent Event.
  3. ForEver Frame.
  4. Long Polling.

Notes

SignalR initiates with HTTP and then upgrades to a WebSocket if the connection is available. An advantage of WebSocket is it can be used by both client and server applications. SignalR supports the transport based on the browser; i.e. which required transport the browser supports. Server Sent events are also called Event Source, which is not supported by only IE browser.

Create A SignalR Chat Based Application using MVC

Step 1

I have created one Asp.net mvc application using .Net Framework 4.5 and Visual Studio 2013 Edition.




Then The MVC 5 signalR application is created and named “SatyaMVCsignalR”




You can Check mvc version Here in Second right side Pic.

Step 2

Then add signalR Related DLL reference files from NuGet Package Manager.


After installation of these three files from NuGet Package manager you can check these signalR DLL files.


You can check also Open Web Interface in .NET called  “OWIN” related DLL files which are responsible for sending the contents of a server to currently connected clients.


Also you can check signalR related javascript files which already have been added.


The version of signalR Javascript files are the same as signalR DLL files.

See as mentioned below.


Step 3

Then I created one OWIN Startup class named “Startup.cs”.

Image Ref,


Code ref 

  1. using Microsoft.Owin;    
  2. using Owin;    
  3.     
  4. [assembly: OwinStartupAttribute(typeof(SatyaMVCsignalR.Startup))]    
  5. namespace SatyaMVCsignalR    
  6. {    
  7.     public partial class Startup    
  8.     {    
  9.         public void Configuration(IAppBuilder app)    
  10.         {    
  11.             app.MapSignalR();    
  12.         }    
  13.     }    
  14. } 

Code Description

To Enable signalR in the project we have to add StartUp Class.

OWIN Application has a startup class where you mention components for the application pipeline. There are various ways you can connect your startup class with the runtime, depending on the hosting models like (OwinHost, IIS, and IIS-Express).

OwinStartup Attribute is the most general class that is used by the developers to determine the Startup class.

  1. [assembly: OwinStartupAttribute(typeof(SatyaMVCsignalR.Startup))]   

Any connection or hub wire up and configuration should go here to this line of StartUp classes.

  1. app.MapSignalR();  

If you want to know all package related information including version and tergetFramework then go to packages.config file.


Step 4

Then add a controller named “HomeController.cs”.

Code Ref 

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. namespace SatyaMVCsignalR.Controllers    
  7. {    
  8.     public class HomeController : Controller    
  9.     {           
  10.         public ActionResult Chat()    
  11.         {    
  12.             return View();    
  13.         }   
  14.     }  
  15. } 

Code Description

Here I defined a controller action result method called Chat().

Step 5

In Solution Explorer, right-click the project, select Add > New Folder, and add a new folder named Hubs. Right-click the Hubs folder, click Add > New Item, select SignalR Hub Class (v2) from the center pane, and create a new hub named ChatHub.cs.


This class is used as a SignalR server hub that sends messages to all clients. You will use this class as a SignalR server hub that sends messages to all clients.

Code Ref

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using Microsoft.AspNet.SignalR;    
  6.     
  7. namespace SatyaMVCsignalR.Hubs    
  8. {    
  9.     public class ChatHub : Hub    
  10.     {    
  11.         public void Send(string name, string message)    
  12.         {    
  13.             Clients.All.addNewMessageToPage(name, message);    
  14.         }    
  15.     }    
  16. } 

Code Description

Here I added one namespace to access methods for response to client requests.

  1. using Microsoft.AspNet.SignalR;   

ChatHub class is derived from Hub base class.

Hub base class provides methods that communicates with signalR connections that are connected to this Hub base class.

  1. public class ChatHub : Hub   

Here I defined a method called Send access two parameter values to take User Name and User Message and Show this User Name and User Message to other users and Vice Versa.

  1. public void Send(string name, string message)  
  2. {  
  3.     Clients.All.addNewMessageToPage(name, message);  
  4. }  

SignalR chat application demonstrates two basic SignalR development things: Develop a hub as the main coordination object on the server, and using the SignalR jQuery library to send and receive messages.

You create public methods on your hub class and then access those methods by calling them from javascripts in a web page.

Clients call the method to send a new message.

ChatHub.Send

The hub in turn sends the name and message to all clients by calling.

Clients.All.addNewMessageToPage

Call a function on the client to update the clients.

Clients.All.addNewMessageToPage(name, message);

Use this property to access all clients connected to this hub.

Microsoft.AspNet.SignalR.Hub.Clients

This Send method of this ChatHub.cs class from the client with the parameters after the connection is fixed on the client side. Once the server receives that request from the client, it processes and sends that response to the client, using appendNewMessage. This appendNewMessage method is set on the client side to receive the response from server side and display it in the User Interface to the client side. 

  1. public void Send(string name, string message)  
  2. {  
  3.     Clients.All.addNewMessageToPage(name, message);  
  4. }  

Step 6

Then I have added a view named “Chat.cshtml” of Home Controller class.

Code Ref 

  1. @{  
  2.     ViewBag.Title = "Chat";  
  3. }  
  4. <fieldset>  
  5.     <legend style="color:orangered">Welcome To  Satya's signalR MVC Group Chat Club</legend>  
  6. </fieldset>  
  7. <div class="form-group col-xl-12">  
  8.     <label style="color: blue; font-style: oblique;font-size: medium" id="label1">Write Your Message Here!</label><br />  
  9.     <textarea class="form-control" rows="4" cols="40" id="message" placeholder="Share what's in your mind..."></textarea>  
  10.     <br />  
  11.     <input type="button" class="btn btn-primary" id="sendmessage" value="Send" />  
  12.     <br />  
  13.     <br />  
  14.     <label style="color: blue;font-style:oblique;font-size:medium" id="label2">Group Chat Conversations History</label>  
  15.     <div class="container chatArea">  
  16.         <input type="hidden" id="displayname" />  
  17.         <ul id="discussion"></ul>  
  18.     </div>  
  19. </div>  
  20. @section scripts {  
  21.     <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>  
  22.     <script src="~/signalr/hubs"></script>  
  23.     <script>  
  24.         $(function () {  
  25.             var chat = $.connection.chatHub;  
  26.             chat.client.addNewMessageToPage = function (name, message) {  
  27.                 $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>'  
  28.                     + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');  
  29.             };  
  30.             $('#displayname').val(prompt('Your Good Name Please:'''));  
  31.             $('#message').focus();  
  32.             $.connection.hub.start().done(function () {  
  33.                 $('#sendmessage').click(function () {  
  34.                     chat.server.send($('#displayname').val(), $('#message').val());  
  35.                     $('#message').val('').focus();  
  36.                 });  
  37.             });  
  38.         });  
  39.         function htmlEncode(value) {  
  40.             var encodedValue = $('<div />').text(value).html();  
  41.             return encodedValue;  
  42.         }  
  43.     </script>  
  44. }   

Code Description

  1. @{  
  2.     ViewBag.Title = "Chat";  
  3. }   

This above part where I added some title text in the browser title bar with addition of title text of “_Layout.cshtml”.

  1. <fieldset>  
  2.     <legend style="color:orangered">Welcome To  Satya's signalR MVC Group Chat Club</legend>  
  3. </fieldset>   

This above part is where I added some headline text of this chat application in signalR.

  1. <label style="color: blue; font-style: oblique;font-size: medium" id="label1">Write Your Message Here!</label>   

This above part is where I added one label control for message box.

  1. <textarea class="form-control" rows="4" cols="40" id="message" placeholder="Share what's in your mind..."></textarea>   

This above part is where I added multiline text box to let user enter messages.

  1. <input type="button" class="btn btn-primary" id="sendmessage" value="Send" />   

This above part is where I added one button control to send messages to other users after putting some messages in the multiline textbox.

  1. <label style="color: blue;font-style:oblique;font-size:medium" id="label2">Group Chat Conversations History</label>   

In the above part I added one label control for chat history area that means whatever messages are received and sent between receiver and sender. 

  1. <div class="container chatArea">  
  2.         <input type="hidden" id="displayname" />  
  3.         <ul id="discussion"></ul>  
  4. </div>   

This above part is where I added one chat area box that will show whatever  messages are received and sent between receiver and sender.

Then two ids,  one “displayname” and “discussion,” will show the receiver and sender names along with their conversations in the current forum session in the chat history area box. 

  1. <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>  
  2. <script src="~/signalr/hubs"></script>   

This above part is where I added script file references to access some signalR based scripting functionalities and show to the end user.

  1. <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>   

Script references. The jQuery library is required and is referenced by default in _Layout.cshtml Reference the SignalR library.

  1. <script src="~/signalr/hubs"></script>   

Reference the autogenerated SignalR hub script. 

  1. <script>  
  2.         $(function () {  
  3.             var chat = $.connection.chatHub;  
  4.             chat.client.addNewMessageToPage = function (name, message) {  
  5.                 $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>'  
  6.                     + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');  
  7.             };  
  8.             $('#displayname').val(prompt('Your Good Name Please:'''));  
  9.             $('#message').focus();  
  10.             $.connection.hub.start().done(function () {  
  11.                 $('#sendmessage').click(function () {  
  12.                     chat.server.send($('#displayname').val(), $('#message').val());  
  13.                     $('#message').val('').focus();  
  14.                 });  
  15.             });  
  16.         });  
  17.         function htmlEncode(value) {  
  18.             var encodedValue = $('<div />').text(value).html();  
  19.             return encodedValue;  
  20.         }  
  21.     </script>   

This is the SignalR script to update the chat page and send messages.

The Chat.cshtml shows how to use the SignalR jQuery library to contact with a SignalR hub. The codes are creating a reference to the Self-generated proxy for the hub, declaring a function that the server can call to push content to clients, and starting a connection to send messages to the hubs.

It is a reference to a hub proxy.

  1. var chat = $.connection.chatHub;

It references the auto-generated proxy for the hub.

Here “chatHub” is the Hub class to make connection related functionalities.

This shows howt to create a callback function in the script. The hub class on the server calls the function to push content updates to each client. The optional call to the htmlEncode function shows a path to HTML to encode the message content before displaying it in the page. As a result way it will prevent script injection.

  1. chat.client.addNewMessageToPage = function (name, message)

It creates a function that the hub can call back to display messages.Here the addNewMessageToPage method to update clients as defined in ChatHub class.

  1. $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>' + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');  

Add the message to the chat area box.

This above mentioned code will show the name and messages of the users in chat area textbox by taking two parameter values defined in addNewMessageToPage method.

  1. $('#displayname').val(prompt('Your Good Name Please:'''));   

Get the user name and store it to prepend to messages.

This part will ask your to mention your user name to process your valid message conversation part.

  1. $('#message').focus();   

It sets initial focus to message input box.

  1. $.connection.hub.start().done(function () {   

Here I added code to Start the connection.

  1. $('#sendmessage').click(function () {   

The “sendmessage” is the id of Button Send event.

  1. chat.server.send($('#displayname').val(), $('#message').val());   

Call the Send method on the hub.

  1. $('#message').val('').focus();   

Clear text box and reset focus for next comment. 

  1. function htmlEncode(value) {  
  2.             var encodedValue = $('<div />').text(value).html();  
  3.             return encodedValue;  
  4.         }   

This optional function html-encodes messages for displaying in the page.

This code shows a set to open a connection with the hubs. This code starts the connection and then transfers it to a function to handle the click event on the Send button in the Chat page. 

  1. $('#sendmessage').click(function () {  
  2.  chat.server.send($('#displayname').val(), $('#message').val());  
  3.  $('#message').val('').focus();  
  4.  });  

Step 7

Modify some code in “_Layout.cshtml” in Views > Shared folder

Code Ref 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - SATYA'S signalR Group Chat Application</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10. </head>  
  11. <body>  
  12.     <div class="container body-content">  
  13.         @RenderBody()  
  14.         <hr />  
  15.         <footer>  
  16.             <p>© @DateTime.Now.Year - SATYA'S signalR Group Chat Application</p>  
  17.         </footer>  
  18.     </div>  
  19.     @Scripts.Render("~/bundles/jquery")  
  20.     @Scripts.Render("~/bundles/bootstrap")  
  21.     @RenderSection("scripts", required: false)  
  22. </body>  
  23. </html>   

Code Description

  1. <title>@ViewBag.Title - SATYA'S signalR Group Chat Application</title>   

This title will be shown in “Chat.Cshtml” file.

  1. @Styles.Render("~/Content/css")   

Link to the css file to make styles  able to View cshtml file.

  1. @RenderBody()   

In Layout Pages it renders the portion of content page that is not within the named section. 

  1. <footer>  
  2.    <p>© @DateTime.Now.Year - SATYA'S signalR Group Chat Application</p>  
  3. </footer>   

This part will be shown in footer part of View UI.

  1. @Scripts.Render("~/bundles/jquery")  
  2. @Scripts.Render("~/bundles/bootstrap")  

This part will show you the Jquery and Bootstrap versions used in this app.

  1. @RenderSection("scripts", required: false)   

In layout pages , renders the content of a named section and specifies whether the section is required.


This “_Layout.cshtml” acts as a MasterPage in “Chat.cshtml” file. This file should be put in “_ViewStart.cshtml” file.

Code Ref 

  1. @{  
  2.     Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }   

Code Description

Here “_Layout.cshtml” file is used to add style format to UI of View Cshtml file.


Step 8

Then makes start page In “RouteConfig.cs” file.

Code ref 

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. using System.Web.Routing;    
  7.     
  8. namespace SatyaMVCsignalR    
  9. {    
  10.     public class RouteConfig    
  11.     {    
  12.         public static void RegisterRoutes(RouteCollection routes)    
  13.         {    
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    
  15.     
  16.             routes.MapRoute(    
  17.                 name: "Default",    
  18.                 url: "{controller}/{action}/{id}",    
  19.                 defaults: new { controller = "Home", action = "Chat", id = UrlParameter.Optional }    
  20.             );    
  21.         }    
  22.     }    
  23. } 

Code Description

  1. defaults: new { controller = "Home", action = "Chat", id=UrlParameter.Optional }  

 


Here Home the Controller Name and Chat the Controller Action Method Name.

Step 9

I have put my own C-Sharp Corner Profile icon file in this application as “favicon.ico”


Step 10

In “packages.config” you can check all versions of package files used in that application.


OUTPUT

The url is - http://localhost:56772/Home/Chat

Here Home the Controller Name and Chat the Controller Action Method Name.

When it loads the first time it asks for your user name.


I put my user name “SATYA” and clicked ok.


For “SATYA” I used Mozilla Firefox Browser

I put the same URL in Chrome browser and put another, New Names, to make chat conversations between “SATYA” names.

I opened three new tabs in Chrome browser and put the same url and put three different names, Like : KULU , KULU1 , KULU2


By using SATYA  I sent some message like below.


In the Chat History area it is showing what the SATYA user sends.

From satya : Good Morning bro….

Then using KULU , KULU1 , KULU2 user names I will send messages see what happens.

From KULU : Hey satya

From KULU1 : Hey satya

From KULU2 : Hey satya


It will show SATYA user message as well as KULU , KULU1 , KULU2 user messages in Chrome browser.That way every user can see every one else's sent messages in the chat history area.


In Mozilla Firefox browser I will check the KULU , KULU1 , KULU2 user messages in SATYA user’s chat history area.

Now SATAY user can see KULU , KULU1 , KULU2 user’s messages In GROUP CHAT.

Here I will show you Browser title bar text as well as Profile Icon file.


Here I will show you footer text used in this application.


Like this we can add an unlimited number of users using an unlimited number of new browsers as well as an unlimited number of tabs in the same browser, as well as different browsers in the Group Chat room as well as send and receive messages to and from all users in that session.

Summary

  1. What is SignalR.
  2. Active signalR features by adding some references.
  3. How to implement in Asp.net Mvc projects in real time scenarios.
  4. How to chat using billions of users using different browsers and the same browsers.


Similar Articles