Follow the code below:
NotificationHub: Hub
private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();
public void SendNotification(string who)
{
foreach (var connectionId in _connections.GetConnections(who))
{
var result = Clients.Client(connectionId);
Clients.Client(connectionId).addNotification(who);
}
}
Components.cs:
void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
//from here we will send notification message to client
NotificationHub notHub = new NotificationHub();
notHub.SendNotification(Who);
//...
}
_Layout:
$(function () {
var connection = $.connection.notificationHub;
//signalr method for push server message to client
connection.client.addNotification = function (who) {
//send notification here
console.info("Send Notification")
};
// Start hub
$.connection.hub.start().done(function () {
console.log("SignalR Started")
});
});
In class Hub
and line var result = Clients.Client(connectionId);
is returning some fields as null.
Image: link
The following code works with the click
function of jquery:
$(function () {
var connection = $.connection.notificationHub;
//signalr method for push server message to client
connection.client.addNotification = function (who) {
//send notification here
console.info("Send Notification")
};
// Start hub
$.connection.hub.start().done(function () {
$("#testeclick").click(function () {
connection.server.sendNotification("User15248");
});
console.log("SignalR Started")
});
});
Follow the result after the jQuery% function: link
The click
function works perfectly. I just can not make it work with click
when doing database change.
The idea is: After doing an "update" in the database, show a notification for client with signalr.
Any solution?
UPDATE: (Nearly solved problem)
NotificationHub: Hub
public static void SendNotification(string who)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
foreach (var connectionId in _connections.GetConnections(who))
{
var result = context.Clients.Client(connectionId);
if (result != null)
{
result.addNotification(who);
}
}
}
Components.cs:
void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
//from here we will send notification message to client
NotificationHub.SendNotification("User1586");
//...
}
Problem almost solved, if it has 50 users, it sends the notification 50 times to user "User1586". If you have 1000 users, send notification 1000 times.
With this line problem: SqlDep_OnChange
(passes multiple times)