Saturday, 25 October 2014

Create a Push notification service using the SignalR with sample Rectangle Drag application from various users

              In this article we are going to see how to create a Push notification service , First of all what is an Push notification means, in generally speaks in some social networking sites you have seen that updates of others persons notifies you in real time data, how it is notifies an client ? when the server reaches any changes from the clients then it is pushes the changes from the server to all users, ie is known as Push notification, or server to client push mechanism.

    First in this sample we are going to create a application which an rectangle that can be drag and moved to any part of the browser using jquery UI plugin. After creating the Application launch the App in two different browers or more than that to test the Push notification, Now where is the Push notification present here ?

    Whenever an Rect is drag and move in any browser , then the position of the Rect in that browser while moving is indicates to all clients who are al1 using that link other than same browser , so now the position of that Rect is sends to all browser as notifications, in client part when we receive the updates we are moving the Rect of the browser to that position along with some text indication.

     First we using the IE to drag , then we can see the push notification result in Chrome browser that Rect moves along with some text info indication, Then in the second term now try to move in Chrome browser now we can see that Rect in IE starts move along with some text information indication.


First create a Empty MVC project , Then install a SignalR from the Manage-Nuget-Packages , Now you can see that two Js are download in  scripts folder.

1. Jquery.min.js 
2. Jquery.SignalR.min.js

In this sample we are using the Jquery UI along with this.

1.  jquery-1.6.4.min.js
2.  jquery.signalR-2.1.2.min.js
3.  jquery-ui.min-1.11.1.js

Dowload this Js files from Jquery exclude the Signalr, we can get the SignalR from the NugetPackages

Create a class called Startup to indicates that this a startup class 


using Microsoft.Owin;
using Owin;
using MyWebApplication;

[assembly: OwinStartup(typeof(MyWebApplication.Startup))]
namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}



Then Starts write the Server and client code for the notifications

1. Create a Cs file to create a Hub.
2. Create a Html file to create a client code.

Now add the following lines in the Html first before start the sample

     <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui.min-1.11.1.js"></script>

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

Then start write the code in Hub cs, Create a class which must be inherit from the Hub class, then implement some function which can be called from the client.Then create an method which can be called from server to push data , but how the server knews the method, to avoid this problem all method indication in server or client must be dynamic, ie is method are binded and called at runtime.

In client side add a script tag which is created at runtime and added.
      <script src="signalr/hubs"></script>

some times you can see that this script is not found or showing 404 error number , this can resolve by following steps 

This issue is generally due to a missing or invalid script reference to the auto-generated Hub JavaScript proxy at '~/signalr/hubs'.

Please make sure that the Hub route is registered before any other routes in your application.

In ASP.NET MVC 4 you can do the following:

      <script src="~/signalr/hubs"></script
some times ~/ doesnt need in my app also doesnt needed.

If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:

        <script src="@Url.Content("~/signalr/hubs")"></script>

If you're writing a regular ASP.NET application use ResolveClientUrl for your script references or register them via the ScriptManager using a app root relative path (starting with a '~/'):

<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>

Now  
In client create a method updateContainer to push the data from the server to client, then create a method in server MoveContainer to indicates the changes from the client to server.create a hub name SmartMoveHub and gives it a custom name by using attribute HubName.

When we run the application we can see that js signalr/hubs that has created at runtime , which consits of many information regarding the server communication from the client.

Normally Signalr uses the websockets,server sentevents for communication [HTML5], if it is not avaliable for the client then it tries for forever frames,Ajax Long polling for comet long held connection.

HTML5
***************
Websockets,
Server Sent Events

LongHeld connection
*********************
Forever Frames
Ajax LongPolling


HTML Code:
***************


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <style type="text/css">
        #divcontainer{
            width:100px;
            height:100px;
            background-color:orangered;
            cursor:move;
        }
    </style>

</head>
<body>
    <div  id="datapush">
       
    </div>
    <div id="divcontainer">

    </div>

    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui.min-1.11.1.js"></script>
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
   
    <script src="signalr/hubs"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            var smartmovehub = $.connection.smartMove;

            smartmovehub.client.updateContainer = function (x, y) {
                $('#datapush').html('Rect is moved to Top :' + x + ', Left :' + y + ' By Push Notification From other users');
                $('#divcontainer').css('top', x).css('left', y);
            };

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

                $('#divcontainer').draggable({
                    drag: function (evt,ui) {
                        smartmovehub.server.moveContainer(ui.position.top,ui.position.left);
                    }
                });
               
            });

        });
    </script>



</body>

</html>

Hub Code:
**************

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

namespace SampleSignalR
{
    [HubName("smartMove")]
    public class SmartMoveHub:Hub
    {
        public void MoveContainer(int x, int y)
        {
            Clients.Others.updateContainer(x, y);
        }
    }

}


Startup code:
**************


using Microsoft.Owin;
using Owin;
using MyWebApplication;

[assembly: OwinStartup(typeof(MyWebApplication.Startup))]
namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}



Open the Url in Different Browser like IE and Chrome,Now
Drag the Rectangle In IE Browser, you can see that Rect in Chrome gets change the Postion by indication the position in Chrome



Now Drag the Rectangle in Chrome , now you can see the same changes in the IE



This kind of Push notification services using the Chatting applications , notification etc. From this post  you can able to read an  information about Signalr and it Usage in Real time applications.










1 comment:

  1. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Dot Net Training in Chennai. or learn thru ASP.NET Online Training . Nowadays Dot Net has tons of job opportunities on various vertical industry.

    ReplyDelete