Skip to main content

SignalR Tutorial: Your first SignalR chat application with ASP.net MVC 4

In last post I explained what SignalR, why do us need it is and what are the prerequisites.

In this tutorial we’ll use ASP.NET SignalR to create a real-time chat application.

First of all we’ll add SignalR library to an MVC 4 application and then create hub class (to push content to client) and after that we’ll use SignalR jQuery library to send messages and display updates from the hub.

·         Open Visual Studio -> Select ASP.NET MVC4 Web Application template (under Web Templates) and enter the name of application as “MVCSignalRApp” and then click OK.


·         On the next screen select “Internet Application” template and then click OK.


·         Your basic MVC application is ready to use, now we need to add SignalR libraries to this application. To add SignalR libraries open Package Manager Console (TOOLS - >Library Package Manager -> Package Manager Console) and then run following command.

install-package Microsoft.AspNet.SignalR


·         It’ll add all the required SignalR libraries to our application. For instance you can check SignalR JavaScript files under Script folder. Application references are also updated in our application.


·         In Solution Explorer, right-click on the project, select Add -> New Folder, and name the new folder as “SignalRHub”.

·         Under this folder Add a new class and give it a name as “ChatHub.cs” and replace the code of this class with the following code:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace MvcSignalRApp.SignalRHub
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the 'addNewMessageToPage' method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}

Understand the code of ChatHub class:

§        In the above code the ChatHub class derives from the Hub (under Microsoft.AspNet.SignalR namespace) class. Deriving from the Hub class is a useful way to build a SignalR application.
§        We can create public methods in hub class and then we can access those methods by calling them from jQuery scripts in a web page. In this case we have defined one public method “Send”; clients call the ChatHub.Send method to send a new message. In the “send” method jQuery “addNewMessageToPage“(through “Clients.All”) method is called through which the hub sends the message to all clients.
§        In the “addNewMessageToPage” method display name of user and message entered by user is sent to browser to display for all other clients.

·         Open the Global.asax file and add a call to the method RouteTable.Routes.MapHubs() in the “Application_Start” method to register the default route for SignalR hubs. This code must be called before you register any other routes through Global.asax.

protected void Application_Start()
{
    // Register the default hubs route: ~/signalr/hubs
    RouteTable.Routes.MapHubs();

    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
}

·         Open the Controllers -> HomeController.cs and add the “ChatApp” method to the class. This method returns the ChatApp view that we’ll create in a later step.

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

·         Right-click on the ChatApp method you just created, and click Add View to create a new view file.

·         On the next screen give your view a name and mark the “Use a layout or master page” checkbox to check and click on Add.


·         Open the view file ChatApp.cshtml. And After the <h2> tag, paste the mentioned below <div> section and @section scripts code block into the page. This script enables the page to send chat messages and display messages from the server.

<div class="container">
    <h3>UserName:
        <label id="userName" style="display: inline;"></label>
    </h3>
    <input type="text" id="messageBox" />
    <input type="button" id="sendMessage" value="Send" />
    <ul id="messageList" style="list-style: none; padding-left: 0px;">
    </ul>
</div>

@section scripts {
    <!--Script references. -->
    <!--The jQuery library are referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>

    <!--SignalR script to update the ChatApp page and send messages.-->
    <script>
        $(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 user message to the page.
                $('#messageList').append('<li><strong>'
                    + encodeHtml(name) + '</strong>: '
                    + encodeHtml(message) + '</li>');
            };

            // Get the user name and store it to prepend to messages.
            $('#userName').text(prompt('Enter your name:', ''));

            // Set initial focus to message input box. 
            $('#messageBox').focus();

            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendMessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#userName').text()
                        , $('#messageBox').val());
                    // Clear text box and reset focus for next comment.
                    $('#messageBox').val('').focus();
                });
            });
        });

        // This optional function html-encodes messages
        // for display in the page.
        function encodeHtml(value) {
            var ecValue = $('<div />').text(value).html();
            return ecValue;
        }
    </script>
}

“Comments have been added to code for better understanding, however please make sure that the script references in your code match the versions of the script libraries installed in your project as VS Package manager might install most recent versions of the scripts than the versions shown in this post.”

·         Save all of your work and then press F5 to see our SignalR chat application in action.

·         By default you’ll see home screen of application, I have added Chat link (on top right corner after Contact link) to navigate user to chat page. Click on this link to open chat.

·         Once you navigate to the chat page, it’ll ask for your name that will display against your chat messages, enter the name and click OK.


·         Open this page in different browser and same way enter the name, so now we have two users ready for real time chat.


·         Enter the message from any of the browser window and you can see that message in both windows against the display name of user.


This sample chat application does not maintain discussion context on the server and user cannot see the old messages.

Summary:

In this tutorial we have learned:
·         How to add SignalR libraries to an ASP.NET MVC 4 application
·         Create and use the hub class.
·         Register the default route for SignalR hubs.
·         Send and receive messages from the hub

You can download the source code of this sample for reference.

That’s it for now, hope you have enjoyed learning SignalR; it’s an awesome framework to create real-time, multi-user interactive web applications.

Comments

  1. where to find autogenerated hub script?

    ReplyDelete
  2. Thank you Kumar, it's very usefull for me

    ReplyDelete
  3. Hello sir i'm newbie, while creating the above application the following error is occurred,

    Error 1 'System.Web.Routing.SignalRRouteExtensions.MapHubs(System.Web.Routing.RouteCollection)' is obsolete: 'Use IAppBuilder.MapSignalR in an Owin Startup class. See http://go.microsoft.com/fwlink/?LinkId=320578 for more details.' c:\users\t.sandeep\documents\visual studio 2013\Projects\MvcSignalRApp\MvcSignalRApp\Global.asax.cs 19 13 MvcSignalRApp


    Plz help me out ASAP
    thanks in advance

    ReplyDelete
  4. Prajakta ChaudhariJune 8, 2015 at 4:30 PM

    Nice article. Do you have any example which save data in sql server database?

    ReplyDelete

Post a Comment

Popular posts from this blog

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...