Sending Notifications using ASP.NET SignalR

Introduction

Web applications needing real-time communication can use HTML5 features such as Web Sockets and Server Sent Events. While these techniques can be used in modern web applications they can't be used with browsers not supporting HTML5. Additionally, they can pose some difficulty in complex scenarios. ASP.NET SignalR is a library that allows you to perform real-time communication in web applications easily. In this article you will learn the basics of using SignalR in an ASP.NET web forms application. 

What is SignalR?

ASP.NET SignalR is a library for developing applications needing real-time communication. In such applications as soon as data is generated on the server or some interesting event happens on the server the client needs to be updated with the latest data. The traditional approach to achieve this functionality is to make Ajax calls to the server periodically. However, this approach has its own pitfalls. Another way is to use HTML5 Web Sockets or Server Sent Events (SSE) to perform real-time communication. However, both of these techniques work only on the browsers supporting HTML5. SignalR uses HTML5 Web Sockets if the target browser supports them, otherwise it falls back to other techniques. The best part is that - as a developer you need not know these internal implementation details. Additionally, SignalR makes connection management, grouping and authorization easy. You can work with the high level API exposed by SignalR in your web applications without worrying too much about the internals of the communication technique used.

You can use SignalR in variety of situations, some of them are listed below:

  • Chat applications where two or more end users chat with each other in real-time.
  • Broadcasting notifications or messages to all or selected clients.
  • Real-time gaming applications.
  • Social networking websites.
  • Discussion boards where admins or members can communicate to other admins or members.

Sample Application

To illustrate how SignalR can be used in an ASP.NET application you will develop a web form application as shown below:

Develop a web form application
Develop a web form application

The web application consists of two simple web forms, viz. AdminForm.aspx and ClientForm.aspx. The former web form is supposed to be used by an administrator to send notifications to all the clients connected at a given point of time. The later web form displays the notifications sent from the administrator to the end user. The notifications are displayed in a balloon that disappears after 5 seconds.

Getting SignalR

In order to develop the above application you should first install the SignalR library. You can get SignalR in couple of ways. Firstly you can install it as a NuGet package. To do so, open Tools > Library Package Manager > Package Manager Console and then issue the following command:

install-package Microsoft.AspNet.SignalR 

Not only easier, but the recommended way is to install Microsoft ASP.NET and Web Tools 2012.2. Doing so will add certain project item templates in the Add New Item dialog as shown below:

Add New Item
Add New Item

You can use these templates (more on that later) instead of manually creating the respective project items.

Developing the Admin Web Form

Now let's develop the admin web form first. Begin by creating a new blank ASP.NET web forms application. Then right click on the project in the Solution Explorer and select Add New Item. Then add a new SignalR Hub Class to the project. This creates a new class that inherits from Hub base class.

namespace SignalRDemo
{
    public class MyHub1 : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}

The Hub class resides in the Microsoft.AspNet.SignalR namespace. A hub class can have any number of developer defined methods. These methods can then be called from a client side script. SignalR hubs provide a higher level RPC framework for your application. Additionally, you will find certain script files under the Scripts folder.

Additional scripts
Additional scripts

In this example you need a method - SendNotifications() - inside the hub class as shown below:

public void SendNotifications(string message)
{
    Clients.All.receiveNotification(message);
}

As you can see, the SendNotifications() method accepts a string parameter. Inside, it uses the Clients.All property to access all of the clients currently connected with the server. The receiveNotification() is a client side callback function that you will write in your jQuery code later. This way a notification is broadcast to all the connected clients. How the clients make use of the message is governed by the receiveNotification() client side function.

Next, add a Global.asax file to your web application and write the following code in the Application_Start event handler.

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHubs();
}

The MapHubs() method registers default routes for SignalR hubs.

Now, add a web form to the project and name it as AdminForm.aspx. Add the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Admin Form Sending Notifications</title>

    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>

    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            $("#button1").click(function () {
                proxy.server.sendNotifications($("#text1").val());
            });

            $.connection.hub.start();
        });
    </script>

</head>
<body>
    <input id="text1" type="text" />
    <input id="button1" type="button" value="Send" />
</body>
</html>

The AdminForm.aspx refers SignalR script files in the head section. Notice the code marked in the bold letters. First a variable named proxy is declared to hold a reference to a proxy of the remote hub class (NotificationHub). Make sure that the client side code uses camel casing in naming conventions. For example, NotificationHub is referred as notificationHub in the client code.

Next, the click event handler of the button is wired to a function. The client event handler calls the sendNotifications() method on the proxy object and passes the notification message entered in the textbox (see earlier figure to know what the admin form looks like).

Finally, the start() method of the hub is called to start the connection.

Developing the Client Web Form

Now that you have completed AdminForm.aspx let's develop the client web form. Add another web form to the project and name it ClientForm.aspx. Key-in the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Client Form Receiving Notifications</title>
    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            proxy.client.receiveNotification = function (message) {
                $("#container").html(message);
                $("#container").slideDown(2000);
                setTimeout('$("#container").slideUp(2000);', 5000);
            };

            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <div class="notificationBalloon" id="container">
    </div>
</body>
</html>

The client code also declares a variable to hold a reference to the proxy hub object. It then wires a callback function receiveNotification (recollect that you used this name in the server side NotificationHub class). The receiveNotification() function receives the notification message sent by the server and displays it to the user after animating it using slideDown() and slideUp() jQuery functions. The notification message is automatically discarded after 5 seconds using the setTimeout() JavaScript function.

Finally, a connection is started by calling the start() method on the hub.

That's it! Run the AdminForm.aspx and load ClientForm.aspx in two or three browser windows or tabs. Now enter some message in the textbox from AdminForm.aspx and click on the Send button. All the browser windows showing ClientForm.aspx should show the notification message.

Summary

SignalR is a library that allows ASP.NET applications to perform real-time communication. If the target browser supports HTML5 SignalR uses Web Sockets otherwise fallback techniques are used. Additionally, SignalR provides an easy way for connection management, connection grouping and security for the communication. This article demonstrated a basic use of SignalR to send notifications to all the connected clients in real-time.



Related Articles

Downloads

Comments

  • who

    Posted by ppntsniiq on 07/03/2013 05:39am

    ghd straighteners cheap NSO$B81 ghd Oghd hair straightener L:WPI&0 cheap ray bans @QJJDRB cheap michael kors handbags

    Reply
  • sex знакомства интимные

    Posted by griegosic on 06/27/2013 09:01pm

    Я закрыла глаза — меня тошнило от раскачивающегося перед глазами потолка. Похоже, вы оба побывали в хорошей драке. Теперь только понял Жилло, почему в корзину нормальных, солидных мисок не положили. [url=http://chertovskie-znakomstva.ded-of.ru.com/znakomstva-besplatno-mozir.php]знакомства бесплатно мозырь[/url] Сквозь Катенькины громогласные аккорды слышались отрывистые реплики, принадлежавшие недавнему собеседнику Бориса. О том, что американская военщина претендует на господство в космосе, чтобы диктовать свои условия Земле. Кусков Оставим в таком случае эту тему. Лично я считаю его самым главным богом во Вселенной, и он тоже мне симпатизирует. [url=http://kniga-znakomstva.ded-of.ru.com/dating266.php]сургутский сайт знакомства[/url] В конце концов влюбленные оказались в спальне маркизы. Видя, что мать и сын вот-вот скроются с ее глаз, Юлька заспешила за ними.

    Reply
  • Impartial publishing unveil Couple of fresh stuff on mizuno that no-one is talking about.

    Posted by BobHotgloff on 05/16/2013 08:24pm

    A double strain on swimwear [url=http://plus-size-swimwear.webnode.com/]modest swimwear[/url] Infrequent post offers the leading points of swimwear which not very many persons are conscious of. [url=http://modest-swimwear.webnode.com/]retro swimwear[/url] Third party report shows Four brand new stuff for bikini that nobody is bringing up. [url=http://spanx-swimwear.webnode.com/]spanx swimwear[/url] The reasons most people are absolute wrong regarding bikini and as a consequence reasons why you must check this ebook. [url=http://vitamin-a-swimwear.webnode.com/]betsey johnson swimwear[/url] Reasons almost everything you've found out about swimwear is undoubtedly wrong and exactly what you need understand. All new swimwear Publication Reveals The Best Way To Dominate The swimwear Market [url=http://girls-swimwear.webnode.com/]girls swimwear[/url] Brand new questions on swimwear answered and consequently why you must definitely read through every single phrase of this post. [url=http://freya-swimwear.webnode.com/]freya swimwear[/url] Everything other people does relating to swimwear and consequently precisely what youshould do different. [url=http://victoria-secret-swimwear.webnode.com/]bra sized swimwear[/url] Upcoming swimwear Ebook Unearths How One Can Rule The swimwear World [url=http://cheap-swimwear.webnode.com/]swimwear sale[/url] Cutting edge guide explains the low down upon swimwear and then why you need to take action soon.[url=http://women-swimwear.webnode.com/]tan through swimwear[/url] Scarce report provides the main points on the swimwear that only a couple of visitors know.

    Reply
  • Nice

    Posted by Vincenzo Costa on 05/05/2013 07:19pm

    Hi... I use it on my current host (http://www.hostforlife.eu) and it work great. Thanks for your valuable information. Very easy to understand.

    Reply
  • Its always necessary keep your teeth clean

    Posted by tamrinnalon on 04/28/2013 02:18am

    A tooth (plural teeth) is a small, calcified, whitish form found in the jaws (or mouths) of many vertebrates and used to sever down food. Some animals, strikingly carnivores, also exercise teeth for the purpose hunting or for defensive purposes. The roots of teeth are covered by gums. Teeth are not made of bone, but rather of multiple tissues of varying density and hardness. The community design of teeth is alike resemble across the vertebrates, although there is respectable modifying in their shape and position. The teeth of mammals be struck by deep roots, and this figure is also create in some fish, and in crocodilians. In most teleost fish, manner, the teeth are spoken for to the outer outwardly of the bone, while in lizards they are fixed devoted to to the inner surface of the jaw alongside one side. In cartilaginous fish, such as sharks, the teeth are joined around rough ligaments to the hoops of cartilage that type the jaw.

    Reply
  • SignalR to sent notification to specific client

    Posted by Pinal Rana on 04/11/2013 02:17am

    HI... I have implemented this with database as any changes occurs it notify. This is very good example and explanation to start. In that using signalr I want to send notification to specific user/client like in facebook. It can be done using passing specific client id but.. every time it gives different client id...

    • Help Me

      Posted by Elango on 04/25/2013 06:14am

      could u give me some ideas about how you have used database notification in this demo?

      Reply
    • Database Implementation

      Posted by McOdo on 04/24/2013 05:10am

      Hi Could you please guide me to how i can do the database implementation? Sounds really cool :)

      • help me

        Posted by lakhan on 01/08/2014 02:23am

        please help my with database implementation

        Reply
      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IT departments are embracing cloud backup, but there's a lot you need to know before choosing a service provider. For example, did you know: That encryption doesn't guarantee privacy? That you could lose data by choosing the wrong cloud? That cloud backup doesn't have to be slow? Learn all the critical things you need to know by accessing the white paper, 5 Things You Didn't Know About Cloud Backup.

  • What can you do to break down silos and integrate social and mobile marketing with every other channel across your organization? Read this white paper to get 10 tips for coordinating your social and mobile marketing with traditional campaigns, and find out how you can deliver a consistent customer experience--one that drives conversions and boosts revenue. Some tips you'll find inside: Use data from social media to get a clear picture of your customers Use social sentiment, both aggregate and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds