Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple Weather Notification using SignalR

0.00/5 (No votes)
6 Aug 2016 1  
Creating simple weather app using signalr that will notify all users about the weather change

Introduction

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

The GitHub URL for SignalR is -  https://github.com/signalr. 

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

Background

You should have basic knowledge of

  • C# 
  • Asp.net
  • JavaScript
  • Jquery
  • Socket Communication (Not necessary)

Using the code

Create a New project

create a new web project with the name WeatherAppDemo with .net framewrok 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 because i am going to use this namespace throughout the article.

<img src="1115408/NewProject.png" style="width: 630px; height: 337px;" />

I am creating an Asp.net mvc project but you can create webform or any asp.net technology project.

Adding Signalr Library

1. Open nuget package manager

<img src="1115408/OpenNugetPackage.png" style="width: 630px; height: 337px;" />

 

2. Search signalr in nuget search and click on First Search Result

<img src="1115408/AddingSignalR.png" style="width: 630px; height: 354px;" />

 

It will install all the library needed for creating the signalr Application. It will add both the server library and javascript client library.

You will notice there are many results of signalr search, so the question will be- what will happen if you click on others. Actually they are seperate library of signalr for different purpose 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 name SignalR

<img src="1115408/Addnewfolder.png" style="width: 630px; height: 354px;" />

I am doing this because i want to keep the code related to signalr to a different folder.

Configuring Signalr

1.Creating Hub class

Add a new class in the SignalR folder with name ChatHub and paste the below code

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WeatherAppDemo.SignalR
{
    public class ChatHub:Hub
    {
        [HubMethodName("change_weather")]
        public void ChangeWeather(int temperature)
        {
             //Clients is ConnectionContext, it holds the information about all the connection.
            //Others in 'Clients.Others' is holding the list of all connected user except the 
            // caller user (the user which has called this method) 
            //NotifyUser is a function on the clientside, you will understand it later.

            Clients.Others.NotifyUser(temperature);

        }

    }
}

What we are doing here -

  1. The class chathub is inhereting a hub class, that means we are making the ChatHub class to act like 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 the parameter temperature. 

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

using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
[assembly: OwinStartup(typeof(WeatherAppDemo.SignalR.StartUp))]

namespace WeatherAppDemo.SignalR
{
    public class StartUp
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

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 with url. The url of the signalr is in the form of- <websiteurlwithport>/signalr. 

e.g- codeproject.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 some javascript code. If you are able to see javascript code, then you have successfully configured a signalr server.

<img src="1115408/SignarTest.png" style="width: 630px; height: 354px;" />

Creating Client

So, we need to create two client

  • First who will change the weather
  • Second who will receive the notification

Step to create a Basic javascript client 

  • Create a html page.
  • Include jquery.js library into the html page. (You will find jquery into the script folder)
  • Include signalr.js library into the html page.(You will find signalr  into 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 next paragraph).

Create ChangeWeather client

Follow the steps to create a basic javascript client and in the last step paste the below code in the script tag-

var SignalrConnection;

function Connect() {
    //This will hold the connection to the signalr hub
    SignalrConnection = $.connection.chatHub;

    //connecting the client to the signalr hub
    $.connection.hub.start().done(function () {
        alert("Connected to Signalr Server");
    })
    .fail(function () {
        alert("failed in connecting to the signalr server");
    })

}

function ChangeWeather() {
    //get the temperature from a textfield with id txtTemprature
    var Temperature = document.getElementById('txtTemperature').value;

    //calling the ChangeWeather function on the signalr server
    SignalrConnection.server.change_weather(Temperature)
}

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 our html page design, just copy the below code

<body onload="Connect();">
<div style="text-align:center;">
    <input type="text" id="txtTemperature" />
    <button id="btnChange" onclick="ChangeWeather();">Change Weather</button>
</div>
</body>

I assume you understand the above html code, so i am not describing this. 

So,finally we have created the client who will change the weather.

Create RecieveWeatherNotification client

Follow the steps to create a basic javascript client and in the last step paste the below code in the script tag-

var SignalrConnection
function Connect() {
    //This will hold the connection to the signalr hub
    SignalrConnection = $.connection.chatHub;

    //This will be called by signalr
    SignalrConnection.client.NotifyUser = function (temperature) {
        $('span').text(temperature);
    }

    //connecting the client to the signalr hub
    $.connection.hub.start().done(function () {
        alert("Connected to Signalr Server");
    })
    .fail(function () {
        alert("failed in connecting to the signalr server");
    })

}

Notice that "NotifyUser" in the code- "SignalrConnection.client.NotifyUser" is a function which wil be called by signalr server, so try not to mismatch the word.

the html page design is very simple, check out the below code

<div style="text-align:center;">
    Temperature : <span></span></div>

now, we have everything that we need. It's time to check out - 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 will 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 -

  1. We need to keep the temperature in a static variable, so that it will be same for all the object of ChatHub.
  2. When the RecieveWeatherNotification.html will be connected to signalr server, it will call the signalr 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 more feature

Updating ChatHub

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

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WeatherAppDemo.SignalR
{
    public class ChatHub:Hub
    {
        //keeping temperature variable static will make the value temperature to be stored in         
        //memory permanently and will be equal to all the object of chathub.
        static int Temperature;
        
        [HubMethodName("change_weather")]
        public void ChangeWeather(int temperature)
        {
            //change the temperature
            Temperature = temperature;

            //Clients is ConnectionContext, it holds the information about all the connection.
            //Others in 'Clients.Others' is holding the list of all connected user except the             
            //caller user (the user which has called this method) 
            //NotifyUser is a function on the clientside, you will understand it later.
            Clients.Others.NotifyUser(temperature);
            
        }

        [HubMethodName("get_weather")]
        public void GetWeather()
        {
            //pushing the data only to the user which has called this method.
            Clients.Caller.NotifyUser(Temperature);
        }

    }
}

so, we have updated the ChatHub class, now let's call the GetWeather method in client side. 

Updating RecieveWeatherNotification.html

copy the below code and update with previous code-

var SignalrConnection
function Connect() {
    //This will hold the connection to the signalr hub
    SignalrConnection = $.connection.chatHub;

    //This will be called by signalr
    SignalrConnection.client.NotifyUser = function (temperature) {
        $('span').text(temperature);
    }

    //connecting the client to the signalr hub
    $.connection.hub.start().done(function () {
        GetWeather();
        alert("Connected to Signalr Server");
    })
    .fail(function () {
        alert("failed in connecting to the signalr server");
    })

}

function GetWeather() {
    //calling the GetWeather function on the signalr server
    SignalrConnection.server.get_weather()
}

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.

so, compile the code and check out everything.

This is a very simple app, but you can create also real time complex application like -

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

Points of Interest

Have you noticed we are neither using any form nor any ajax request, so how we are getting the data. Actually we are establishing a socket channel with server which is a bidirectinal communication, so we can call the method on the signalr server and server can also call method on the client side. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here