Getting Started With SignalR in ASP.NET

In this article you will learn how to begin work with SignalR and how to exchange messages among multiples users.

What SignalR is: SignalR is an ASP.Net server library for adding real-time functionality to a web application. This includes client libraries for JavaScript and other clients.

Getting Started

The get started with SignalR:

  • Start Visual Studio
  • Create a new website
  • Provide the name and location of website
  • Click "Next"

Now add a new SignalR Hub class and give a name of class and click "Add".

Note: You will probably get this error message when you add the class:

"This template attempted to load component assembly 'NuGet.VisualStudio.Interop, Version=*, Culture=neutral, PublicKeyToken=*"

Follow this blog to remove this problem:

http://www.c-sharpcorner.com/Blogs/11651/%E2%80%98this-template-attempted-to-load-component-assembly-nuget-v.aspx

Or you can also add SignalR to a project by opening the "Tools" | "Library Package Manager" | "Package Manager Console" and running the command: "install-package Microsoft.AspNet.SignalR". Now again add the SignalR class.

img1.jpg

Image 1.

As you can see, many SignalR assemblies have been added in the Bin folder, so you are good to go.

img2.jpg

Image 2.

Now it is time to work on HubClass.

First of all add this namespace:

using Microsoft.AspNet.SignalR;

And now add this method:

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

Now add these namespaces in the global.asax file:

<%@ Import Namespace="System.Web.Routing" %>
<%@ Import Namespace="Microsoft.AspNet.SignalR" %>

Add this code in the "application_start" event:

RouteTable.Routes.MapHubs();

Now add a new HTML page and give a name and click "Ok".

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>SignalR Simple Message Broadcast Sample</title>

</head>

<body>

      <div style="background-color: #C0C0C0">

        <input type="text" id="messagetext" />

        <input type="button" id="btnsendmessage" value="Broadcast message" />

        <input type="hidden" id="displayname" />

        <ul id="loadmessages">

        </ul>

    </div>

    <!--Script references. -->

    <!--Reference the jQuery library. -->

    <script src="/Scripts/jquery-1.8.2.min.js" ></script>

    <!--Reference the SignalR library. -->

    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>

    <!--Reference the autogenerated SignalR hub script. -->

    <script src="/signalr/hubs"></script>

    <!--Add script to update the page and send messages.-->

    <script type="text/javascript">

        $(function () {

            // Declare a proxy to reference the hub.

            var chat = $.connection.chatHub;

            // Create a function that the hub can call to broadcast messages.

            chat.client.broadcastMessage = function (name, message) {

                // Html encode display name and message.

                var encodedName = $('<div />').text(name).html();

                var encodedMsg = $('<div />').text(message).html();

                // Add the message to the page.

                $('#loadmessages').append('<li><strong>' + encodedName

                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');

            };

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

            $('#displayname').val(prompt('Enter your name:', ''));

            // Set initial focus to message input box. 

            $('#messagetext').focus();

            // Start the connection.

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

                $('#btnsendmessage').click(function () {

                    // Call the Send method on the hub.

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

                    // Clear text box and reset focus for next comment.

                    $('#messagetext').val('').focus();

                });

            });

        });

    </script>

</body>

</html>

Time to run the application; press F5. I would suggest selecting Internet Explorer with debug.

img3.jpg

Image 3.

As you can see, two windows open; one for HTML content and the second asks for a name. Copy the browser URL and paste in another browser window then provide a name and click "OK".

Now copy that URL into another window.

img4.jpg

Image 4.

Now provide another name to that TextBox and click "OK".

So don't get confused; provide a different name to windows like this.

img5.jpg

Image 5.

Now type a message from the first window and respond from another window.

img6.jpg

Image 6.

As you will see, both windows are loading messages without delaying on their name that we provided.