Weather Notification App Using SignalR

Introduction

SignalR is a library for .NET developers for adding real time functionality to the applications made using .NET technology (ASP.NET applications, C# console applications, WPF applications, Windows phone applications etc.). It is open source and you can download it from GitHub.

Here, we are going to create a simple weather notification app that will instantly notify all connected users about the changed weather (in real time).

Prerequisites

You should have the basic knowledge of the following.

  • C#
  • ASP.NET
  • JavaScript
  • jQuery
  • Socket Communication (not necessary). Check out this article, if you want to understand the basics of socket communication.

Let’s start.

Create a new project

Create a new web project with the name WeatherAppDemo, using .NET Framework version 4.5. I am using .NET 4.5 because this will let us use the latest SignalR 2.x version.

Please do not change the name as I am going to use this namespace throughout the article.



I am creating an ASP.NET MVC project but you can create Web form or any ASP.NET technology project.

Adding SignalR Library

  1. Open NuGet Package Manager.



  2. Search SignalR in NuGet search and click on the very first Search Result, i.e. Microsoft ASP.NET SignalR.



    It will install all the libraries needed for creating the SignalR application. It will add both the server libraries and JavaScript client libraries.

    You must have noticed that there are many results of SignalR search. So, the question is what will happen if you click on others? Actually, they are separate libraries of SignalR for different purposes but we need the complete package because we are going to create SignalR Server as well as Client.

  3. Add new folder in the project with the name of SignalR



    We are doing this in order to keep the code related to SignalR in a different folder.

Configuring SignalR

  1. Creating hub class

    Add a new class in the SignalR folder with the name ChatHub and paste the below code.
    1. using Microsoft.AspNet.SignalR;  
    2. using Microsoft.AspNet.SignalR.Hubs;  
    3. using System;  
    4. using System.Collections.Generic;  
    5. using System.Linq;  
    6. using System.Web;  
    7. namespace WeatherAppDemo.SignalR {  
    8.     public class ChatHub: Hub {  
    9.         [HubMethodName("change_weather")]  
    10.         public void ChangeWeather(int temperature) {  
    11.             //Clients is ConnectionContext, it holds the information   
    12.             //about all the connection.   
    13.             //Others in 'Clients.Others' is holding the list of all   
    14.             //connected user except the caller user   
    15.             //(the user which has called this method).   
    16.             //NotifyUser is a function on the clientside, you will   
    17.             //understand it later.   
    18.             Clients.Others.NotifyUser(temperature);  
    19.         }  
    20.     }  
    21. }  
    What we are doing here -

    1. The class ChatHub is inheriting a hub class, that means we are making the ChatHub class to act like a hub of the communication.
    2. We have defined a ChangeWeather function which is taking a parameter, temperature, and it is calling NotifyUser of the client side with this parameter.

  2. Mapping hubs to the SignalR pipeline

    Add a new class in the SignalR folder with name StartUp and paste below code in the StartUp.cs
    1. using Microsoft.Owin;  
    2. using Owin;  
    3. using System;  
    4. using System.Collections.Generic;  
    5. using System.Linq;  
    6. using System.Web;  
    7. [assembly: OwinStartup(typeof(WeatherAppDemo.SignalR.StartUp))]  
    8. namespace WeatherAppDemo.SignalR {  
    9.     public class StartUp {  
    10.         public void Configuration(IAppBuilder app) {  
    11.             app.MapSignalR();  
    12.         }  
    13.     }  
    14. }  
    What we are doing here -

    1. We are calling OwinStartup with parameter WeatherAppDemo.SignalR.StartUp, which will initialize our StartUp class.
    2. In the StartUp class, we are using app.MapSignalR() – it will map SignalR hubs to the app builder pipeline. Simply, what it does is that it will add the hubs to the SignalR pipeline, so that you can access it through a URL. The URL of the SignalR is in the form of- <websiteurlwithport>/signalr.

      e.g-abc.com/signalr

So basically, we are doing two things- we are first starting the StartUp class and adding the hubs to the SignalR pipeline.

Now, compile the code and append this "/signalr/hubs" at the URL. You will have to add some JavaScript code. If you are able to see the JavaScript code, then you have successfully configured a SignalR Server.



Creating Client

Now, we need to create two clients,

  • The first will change the weather while the second one will receive the notification.

Steps to create a basic JavaScript Client

  • Create an HTML page.
  • Include jquery.js library into that page. (You will find jQuery in the script folder).
  • Include signalr.js library into that page.(You will find SignalR in the script folder).
  • Add a script with the src=”/signalr/hubs”. (It is a JavaScript proxy generated by SignalR Server).
  • Write some JS code to talk with the SignalR Server (I am going to write this code in the next paragraph).

Create ChangeWeather Client (ChangeWeather.html)

Follow the steps to create a basic JavaScript client and in the last step, paste the below code in the script tag.

  1. var SignalrConnection;  
  2.   
  3. function Connect() {  
  4.     //This will hold the connection to the signalr hub   
  5.     SignalrConnection = $.connection.chatHub;  
  6.     //connecting the client to the signalr hub   
  7.     $.connection.hub.start().done(function() {  
  8.         alert("Connected to Signalr Server");  
  9.     }).fail(function() {  
  10.         alert("failed in connecting to the signalr server");  
  11.     })  
  12. }  
  13.   
  14. function ChangeWeather() {  
  15.     //get the temperature from a textfield with id txtTemprature   
  16.     var Temperature = document.getElementById('txtTemperature').value;  
  17.     //calling the ChangeWeather function on the signalr server   
  18.     SignalrConnection.server.change_weather(Temperature)  
  19. }  
In the above code, I have described most of the parts with comments.

Now, you must be wondering about some jQuery code which is not the part of jQuery like -“$.connection”. So, how we are using this? Actually, the script which we included using src=”/signalr/hubs” is extending the jQuery and making this possible.

It’s time for us to design the HTML page. Just copy the below code.
  1. <body onload="Connect();">  
  2.     <div style="text-align:center;"> <input type="text" id="txtTemperature" /> <button id="btnChange" onclick="ChangeWeather();">Change Weather</button> </div>  
  3. </body>  
I assume that you understand the above code. So, I am not describing this. Finally, we have created the client who will change the weather.

Create Receive Weather Notification Client (ReceiveWeatherNotification.html)

Follow the steps to create a basic JS client and in the last step, paste the below code in the script tag.
  1. var SignalrConnection  
  2.   
  3. function Connect() {  
  4.     //This will hold the connection to the signalr hub   
  5.     SignalrConnection = $.connection.chatHub;  
  6.     //This will be called by signalr   
  7.     SignalrConnection.client.NotifyUser = function(temperature) {  
  8.             $('span').text(temperature);  
  9.         }  
  10.         //connecting the client to the signalr hub   
  11.     $.connection.hub.start().done(function() {  
  12.         alert("Connected to Signalr Server");  
  13.     }).fail(function() {  
  14.         alert("failed in connecting to the signalr server");  
  15.     })  
  16. }  
Notice that “NotifyUser” in the code- “SignalrConnection.client.NotifyUser” is a function which will be called by SignalR Server. Try not to mismatch the word.

The HTML page design is very simple. Check out the below code.
  1. <div style="text-align:center;"> Temperature : <span></span> ℃   
  2.   </div>  
Now, we have everything that we need. It’s time to check what we have made. Perform the following steps.
  • Compile the code.
  • Open the ChangeWeather.html.
  • Open RecieveWeatherNotification in other tabs (open in multiple tab or multiple browser).
  • Change the weather in ChangeWeather.html and observe the temperature in the RecieveWeatherNotification.html.

Notice that when you open the RecieveWeatherNotification.html for the first time, there is no temperature, which is not good – I mean there should be some initial temperature. So, what we need to do is -

  1. We need to keep the temperature in a static variable, so that it will be same for all the objects of ChatHub.
  2. When the RecieveWeatherNotification.html is connected to SignalR Server, it will call the server to get the current temperature.
  3. We will have to create a function (HubMethod) in Chathub, which will be called by RecieveWeatherNotification.html to get the current temperature.The function will call the NotifyUser of the client side to set the temperature.

Adding Extra Feature(Making more real)

I have described above what I am going to do. So, just copy the below code and update the ChatHub class.

  1. using Microsoft.AspNet.SignalR;  
  2. using Microsoft.AspNet.SignalR.Hubs;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. namespace WeatherAppDemo.SignalR {  
  8.     public class ChatHub: Hub {  
  9.         //keeping temperature variable static will make the value temperature   
  10.         //to be stored in memory permanently and will be equal to all the   
  11.         //object of chathub.   
  12.         static int Temperature;  
  13.         [HubMethodName("change_weather")]  
  14.         public void ChangeWeather(int temperature) {  
  15.                 //change the temperature   
  16.                 Temperature = temperature;  
  17.                 //Clients is ConnectionContext, it holds the information about all   
  18.                 //the connection.   
  19.                 //Others in 'Clients.Others' is holding the list of all connected   
  20.                 //user except the caller user (the user which has called this method)   
  21.                 //NotifyUser is a function on the clientside, you will understand it   
  22.                 //later.   
  23.                 Clients.Others.NotifyUser(temperature);  
  24.             }  
  25.             [HubMethodName("get_weather")]  
  26.         public void GetWeather() {  
  27.             //pushing the data only to the user which has called this method.   
  28.             Clients.Caller.NotifyUser(Temperature);  
  29.         }  
  30.     }  
  31. }  
So, we have updated the ChatHub class. Now, let’s call the GetWeather method in client side.

Updating ReceiveWeatherNotification.html

Copy the below code and update with previous code.
  1. var SignalrConnection  
  2.   
  3. function Connect() {  
  4.     //This will hold the connection to the signalr hub   
  5.     SignalrConnection = $.connection.chatHub;  
  6.     //This will be called by signalr   
  7.     SignalrConnection.client.NotifyUser = function(temperature) {  
  8.             $('span').text(temperature);  
  9.         }  
  10.         //connecting the client to the signalr hub   
  11.     $.connection.hub.start().done(function() {  
  12.         GetWeather();  
  13.         alert("Connected to Signalr Server");  
  14.     }).fail(function() {  
  15.         alert("failed in connecting to the signalr server");  
  16.     })  
  17. }  
  18.   
  19. function GetWeather() {  
  20.     //calling the GetWeather function on the signalr server   
  21.     SignalrConnection.server.get_weather()  
  22. }  
What we have done here.

 I have created a method GetWeather which will call the chathubmethod “get_weather”.

  • I am calling the GetWeather, when the client is connected to the SignalR.

Compile the code and check out everything.

This is a very simple app, but you can create real time complex application too. For example - 

  • Chat application
  • Real time notification like facebook
  • High frequency update to an online game, etc.


Similar Articles