add

Thursday, 14 June 2018

How To Create Application Configuration With Two SignalR Hubs


How To Create Application Configuration With Two SignalR Hubs

1).first You Need to Create Owin Startup Class At Root Of the Project

 Note: before doing code first you need to change sql database where notification table exist write this code in sql 

ALTER DATABASE [DBNAME] SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE

using Microsoft.Owin;
using Owin;


[assembly: OwinStartupAttribute(typeof(PowerHMS.Startup))]
namespace PowerHMS
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();


}
}
}


2).Set up Code Withing Global.aspx class 


using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MyProject
{
public class MvcApplication : System.Web.HttpApplication
{
//string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;

protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//SqlDependency.Start(con);
////new Code
NotificationComponent nc = new NotificationComponent();
var currentTime = DateTime.Now;
nc.RegisterNotification(currentTime);
}
protected void Session_Start(object sender, EventArgs e)
{
var currentTime = DateTime.Now;
HttpContext.Current.Session["LastUpdated"] = currentTime;
}
protected void Application_End()
{
//here we will stop Sql Dependency
// SqlDependency.Stop(con);
}

}
}


3).Create A connection Class For SignalR



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Threading.Tasks;

using Microsoft.AspNet.SignalR;

namespace MyProject
{
public class NotificationHub : Hub
{
public readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();


public override Task OnConnected()
{
string name = Context.User.Identity.Name;

_connections.Add(name, Context.ConnectionId);

return base.OnConnected();
}

public override Task OnDisconnected(bool stopCalled)
{
string name = Context.User.Identity.Name;

_connections.Remove(name, Context.ConnectionId);

return base.OnDisconnected(stopCalled);
}

public override Task OnReconnected()
{
string name = Context.User.Identity.Name;

if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
{
_connections.Add(name, Context.ConnectionId);
}

return base.OnReconnected();
}
}

}

4).Create A Notification Component Class


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Microsoft.AspNet.SignalR;


namespace MyProject
{

public class NotificationComponent
{
//Here we will add a function for register notification (will add sql dependency)
public void RegisterNotification(DateTime currentTime)
{
string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
string sqlCommand = @"select [NotiMessage],[SenderID],[Recivers],[NofiTable],[NotiColumn],[NotiValue],[AddedOn],[ReadOn],[IsDeleted] from [dbo].[Notification] ";
//you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlCommand, con);
//cmd.Parameters.AddWithValue("@AddedOn", currentTime);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
cmd.Notification = null;
SqlDependency sqlDep = new SqlDependency(cmd);
sqlDep.OnChange += sqlDep_OnChange;
//we must have to execute the command here
using (SqlDataReader reader = cmd.ExecuteReader())
{
// nothing need to add here now
}
}
}

void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= sqlDep_OnChange;

var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

foreach (var user in NotificationHub._connections.GetEnumerator())
{

foreach (var ids in NotificationHub._connections.GetConnections(user))
{
notificationHub.Clients.Client(ids).notify("added");
}

}

RegisterNotification(DateTime.Now);

}
}

GetNotificationsUser
}
}

5). Create Hubs

          a).Schedulehub.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;

namespace MyProject
{
public class scheduleHub : Hub
{
public void Modify(string action, Object data)
{
Clients.Others.AddToSchedul(action, data);
}
public void Send(string GroupName,string message)
{
Clients.Others.addNewMessageToPage(HttpContext.Current.User.Identity.Name, message);
}
}
}

      B).Notificationhub.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Threading.Tasks;

using Microsoft.AspNet.SignalR;

namespace MyProject
{
public class NotificationHub : Hub
{
public readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();


public override Task OnConnected()
{
string name = Context.User.Identity.Name;

_connections.Add(name, Context.ConnectionId);

return base.OnConnected();
}

public override Task OnDisconnected(bool stopCalled)
{
string name = Context.User.Identity.Name;

_connections.Remove(name, Context.ConnectionId);

return base.OnDisconnected(stopCalled);
}

public override Task OnReconnected()
{
string name = Context.User.Identity.Name;

if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
{
_connections.Add(name, Context.ConnectionId);
}

return base.OnReconnected();
}
}

}

6). Finally Create Code for Hub in javascript to communicate Dom



$(function () {

//Create SignalR Hub Server Connection
var connection = $.hubConnection("/signalr",
{
seDefaultPath: false
});

//Creating Proxy Hub For "ScheduleHub" Hub
var scheduleHubProxy = connection.createHubProxy('scheduleHub');
//Creating Proxy Hub For "NotificationHub" Hub
var notificationHub = connection.createHubProxy('notificationHub');

notificationHub.on('notify', function (message) {
if (message && message.toLowerCase() == "added") {
}
});
scheduleHubProxy.on('AddToSchedul', function (action, data) {
if (data != null) {
$("#Schedule1").ejSchedule('instance').notifyChanges(action, data);
var schedule = $("#Schedule1").data("ejSchedule");
}
});
connection.start().done(function () {
window.actionComplete = function (args) {
if (args.methodType == "public")
args.appointment = null;
if (args.methodType != "public" && (args.type == "appointmentCreated" || args.type == "appointmentEdited" || args.type == "appointmentDeleted" || args.type == "drag" || args.type == "navigation")) {
scheduleHubProxy.invoke('modify', args.type, args.appointment);
}
};
});
});

No comments: