SignalR in the loop - signalr

I am using SignalR in loop like this:
int itemsCount = 100;
for (int i = 0; i <= itemsCount; i++)
{
Thread.Sleep(100);
SummaryHub.SendMessages("test", i.ToString());
}
and client site is:
$(function () {
var notifications = $.connection.SummaryHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.broadcastMessage = function (name, message) {
console.log(name);
console.log(message);
};
// Start the connection.
$.connection.hub.start().done(function () {
// $.connection.hub.start({ waitForPageLoad: false }).done(function () {
console.log("connection started")
}).fail(function (e) {
alert(e);
});
});
[HubName("SummaryHub")]
public class SummaryHub : Hub
{
[HubMethodName("sendMessages")]
public static void SendMessages(string name, string message)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SummaryHub>();
context.Clients.All.broadcastMessage(name, message);
}
}
Problem is that client receive messages after loop is done, not during the loop. How can I fix that? Thanks

I find out. It was ajax call with async:false and that was preventing sending messages to the client. Change async to true solved the problem

Related

SignalR - sending push notification to a specific user

I'm working on a PoC for a notification engine. I'm able to successfully connect and call Hub functions from JS, but I can't seem to get push notifications to work. I'm getting an Object reference not set to an instance of an object error.
Triggering class
// I was able to confirm that the connectionIds are valid
public void HandleEvent(NewNotificationEvent eventMessage)
{
// _connections handles connectionids of a user
// multiple connection ids to handle multiple open tabs
var connectionIds = _connections.GetConnectionsByUser(eventMessage.Notification.UserId);
foreach(var connectionId in connectionIds)
{
// a client is returned, but aside from the connectionid, all the properties are either null or empty
var client = _notificationHub.Clients.Client(connectionId);
///// ERROR HAPPENS HERE
///// I'm guessing NewNotification() isn't defined somewhere, but I don't know where.
client.NewNotification("Hello");
}
}
View.cshtml
var notificationHub = $.connection.NotificationHub;
$.connection.hub.qs="userId=#userId"
// Initialization
$.connection.hub.start().done(function () {
// get count unread notification count
notificationHub.invoke("unReadNotificationsCount")
.done((unreadCount) => {
if (unreadCount > 0) {
$('#notificationBadge').html(unreadCount);
hasNewNotification = true;
}
console.log('SignalR connected!');
})
.fail((data) => {
console.log('Unable to reach server');
console.log(data);
})
.always(() => $('#dropdownNotificationOptions').show());
});
// also tried notificationHub.NewNotification()
notificationHub.client.NewNotification = function (notification) {
console.log(notification);
}
NotificationHub.cs
[HubName("NotificationHub")]
public class NotificationHub : Hub
{
//ctor
public override Task OnConnected()
{
var userId = Context.QueryString["userid"];
if(userId.IsNotNullOrEmpty())
_connections.Add(Context.ConnectionId, Guid.Parse(userId));
else
_connections.Add(Context.ConnectionId, Guid.NewGuid());
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled = true)
{
_connections.Remove(Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
Guid userId;
if (Guid.TryParse(Context.QueryString["userid"],out userId))
{
//var userId = _workContext.CurrentUser.Id;
var userConnection = _connections.GetUserByConnection(Context.ConnectionId);
if (userConnection == null || userConnection.IsNotNullOrEmpty())
{
_connections.Add(Context.ConnectionId, userId);
}
}
return base.OnReconnected();
}
}
You should have your NewNotification before the $.connection.hub.start() such as:
var notificationHub = $.connection.NotificationHub;
$.connection.hub.qs="userId=#userId"
// Moved to define before the connection start
notificationHub.client.NewNotification = function (notification) {
console.log(notification);
}
// Initialization
$.connection.hub.start().done(function () {
// get count unread notification count
notificationHub.invoke("unReadNotificationsCount")
.done((unreadCount) => {
if (unreadCount > 0) {
$('#notificationBadge').html(unreadCount);
hasNewNotification = true;
}
console.log('SignalR connected!');
})
.fail((data) => {
console.log('Unable to reach server');
console.log(data);
})
.always(() => $('#dropdownNotificationOptions').show());
});

SignalR : How can I broadcast message to Other page of the application

I am creating a test app, where one can download some files and on download success notification will be propagated to admin ,something like notification in
www.ge.tt,or panel notification in Facebook.
I have two pages
a)Download.aspx
b)LandingPage.aspx
In Download.aspx
function PushNotification() {
alert("I ran Upto Here");
//Declare a proxy to Reference a Hub
var notification = $.connection.notificationHub;
//Start a Connection
$.connection.hub.start().done(function () {
notification.server.send(21);
//$("#hdnFileId").val()
alert("I ran Upto Here 2 ");
});
notification.client.broadcastMessage = function (FileID) {
alert("file was Downloaded" + FileID);
};
}
Here two different tabs/browser are working Fine showing alert message if page Loads.
but i want to use the brodcast message in my LandingPage.aspx
here is the Js
$(function () {
var notification = $.connection.notificationHub;
notification.client.broadcastMessage = function (FileID) {
alert("file was Downloaded" + FileID);
};
});
And my hubclass ..
namespace TestApplication.Entities
{
public class NotificationHub : Hub
{
//public void Hello()
//{
// Clients.All.hello();
//}
public void Send(int FileID)
{
Clients.All.broadcastMessage(FileID);
}
}
}
but the notification is not coming here, whats wrong Here?
You didn't start connection in LandingPage.aspx
Try like this in LandingPage.aspx
var notification = $.connection.notificationHub;
$.connection.hub.start();
notification.client.broadcastMessage = function (FileID) {
alert("file was Downloaded" + FileID);
};

Return count of connected clients in SignalR. Not firing client function

I am trying to return the count of all connections to a web client with SignalR. I increment and persist the client count by firing logic on the hub OnConnected() method.
public class PopHub : Hub
{
public static List<string> Users = new List<string>();
public override Task OnConnected()
{
var clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
Send(Users.Count);
return base.OnConnected();
}
public void Send(int count)
{
Clients.All.updateUsersOnlineCount(count);
}
stepping through my code with an external console client (to trigger OnConnected()) shows that I am traversing through Send(int count) with a count of 1.
On my web client, I configure my JS as such
$(function() {
var hub = $.connection.popHub;
hub.client.updateUsersOnlineCount = function(count) {
console.log(count);
};
$.connection.hub.start().done(function() {
console.log('connected');
});
}());
And lastly my snippet from the generated js
proxies.popHub = this.createHubProxy('popHub');
proxies.popHub.client = { };
proxies.popHub.server = {
popClient: function (message) {
return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["PopClient"], $.makeArray(arguments)));
},
query: function () {
return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["Query"], $.makeArray(arguments)));
},
send: function (count) {
return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["Send"], $.makeArray(arguments)));
}
};
**Note that Popclient and Query are unrelated server side events, of which do work giving me somewhat of a sanity check. Any idea why my clients updateUsersOnlineCount function is not logging the count of connections as I expect?
Instead of doing it in the OnConnected, please give this a try, it might be that the Base.OnConnected has not been executed yet, so it's not ready to broadcast to clients.
//Client
$.connection.hub.start().done(function() {
console.log('connected');
hub.server.ClientCount();
});
//Hub
public static List<string> Users = new List<string>();
public override Task OnConnected()
{
var clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
//Send(Users.Count); //not calling this since it's not working
return base.OnConnected();
}
public void ClientCount()
{
Clients.All.updateUsersOnlineCount(Users.Count);
}

Older asynchronous messages overwriting newer ones

We are developing a document collaboration tool in SignalR where multiple users can update one single WYSIWYG form.
We are struggling getting the app to work using the KeyUp method to send the changes back to the server. This causes the system to overwrite what the user wrote after his first key stroke when it sends the message back.
Is there anyway to work around this problem?
For the moment I tried to set up a 2 seconds timeout but this delays all updates not only the "writer" page.
public class ChatHub : Hub
{
public ChatHub()
{
}
public void Send(int id,string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(id,message); //id is for the document id where to update the content
}
}
and the client:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
// Add the message to the page.
if (encodedValue == $('#hdnDocId').val()) {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content); //send a push to server
}
typewatch(Chat, 2000);
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
</script>
Hello, here is an update of the client KeyUp code. It seems to be working but I would like your opinion. I've used a global variable to store the timeout, see below:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
var currenttime = new Date().getTime() / 1000 - 2
if (typeof window.istyping == 'undefined') {
window.istyping = 0;
}
if (encodedValue == $('#hdnDocId').val() && window.istyping == 0 && window.istyping < currenttime) {
function Update() {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
// tinyMCE.get('txtContent').setContent(message);
window.istyping = 0
}
Update();
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
//alert("Call");
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content);
window.istyping = new Date().getTime() / 1000;
}
Chat();
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
Thanks,
Roberto.
Is there anyway to work around this problem?
Yes, by not sending the entire document to the server, but document elements like paragraphs, table cells, and so on. You can synchronize these after the user has stopped typing for a period, or when focus is lost for example.
Otherwise add some incrementing counter to the messages, so older return values don't overwrite newer ones arriving earlier.
But you're basically asking us to solve a non-trivial problem regarding collaborated document editing. What have you tried?
"This causes the system to overwrite what the user wrote"
that's because this code isn't making any effort to merge changes. it is just blindly overwriting whatever is there.
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message);
as #CodeCaster hinted, you need to be more precise in the messages you send - pass specific changes back and forth rather re-sending the entire document - so that changes can be carefully merged on the receiving side

Signalr Owin simple example javascript client not being called

I have a 5.3.0 version of signalr self hosting that is being upgraded to a newer version of signalr.
Using https://github.com/SignalR/SignalR/wiki/Self-host example i have created a simple example, but i can’t get it to work.
I can get a connection to the hub on the server and call methods on the hub, but i can’t get the hub to call the javascript client.
When looking at it in fiddler I never see a response come back from the hub.
Here is the code
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8080/";
using (WebApplication.Start<Startup>(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
}
using Microsoft.AspNet.SignalR;
using Owin;
namespace ConsoleApplication3
{
class Startup
{
// This method name is important
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration
{
EnableCrossDomain = true,
EnableJavaScriptProxies = true
};
app.MapHubs(config);
}
}
}
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace ConsoleApplication3.Hubs
{
public class Chat : Hub
{
public override Task OnConnected()
{
Notify(Context.ConnectionId);
return new Task(() => { });
}
public void RunTest()
{
Notify(Context.ConnectionId);
}
public void Notify(string connectionId)
{
dynamic testMessage = new
{
Count = 3,
Message = "Some test message",
Timestamp = DateTime.Now
};
String json = JsonConvert.SerializeObject(testMessage);
var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
context.Clients.Client(connectionId).sendNotification(json);
}
}
}
And here is the client side
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/json2.js"></script>
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/jquery.signalR-1.0.1.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script>
$(function () {
// Proxy created on the fly
var notification = $.connection.chat;
$.connection.hub.logging = true;
// Declare functions that can be run on the client by the server
notification.client.sendNotification = onAddNotification;
notification.client.disconnected = function (connectionid) {
console.log(connectionid);
};
// Testing code only
$("#testButton").click(function () {
// Run test function on server
notification.server.runTest();
});
jQuery.support.cors = true;
// Map the onConnect and onDisconnect functions
notification.client.connected = function () {
alert("Notification system connected");
};
notification.client.disconnected = function () { };
$.connection.hub.url = "http://localhost:8080/signalr";
//$.connection.hub.start();
$.connection.hub.start(function () {
alert("Notification system connected");
});
});
// Process a newly received notification from the server
function onAddNotification(message) {
// Convert the passed json message back into an object
var obj = JSON.parse(message);
var parsedDate = new Date(parseInt(obj.Timestamp.substr(6)));
// Update the notification list
$('#notifications').prepend('<li>' + obj.Message + ' at ' + parsedDate + '</li>');
};
</script>
</head>
<body>
Send test
<ul class="unstyled" id="notifications">
</ul>
</body>
Any ideas would be appreciated, since i am fairly stuck.
Few things in your code:
Change this:
public override Task OnConnected()
{
Notify(Context.ConnectionId);
return new Task(() => { });
}
To:
public override Task OnConnected()
{
Notify(Context.ConnectionId);
return base.OnConnected();
}
Also in your hub:
This function is trying too hard:
public void Notify(string connectionId)
{
dynamic testMessage = new
{
Count = 3,
Message = "Some test message",
Timestamp = DateTime.Now
};
String json = JsonConvert.SerializeObject(testMessage);
var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
context.Clients.Client(connectionId).sendNotification(json);
}
I'm not even sure why you're passing the connection id (maybe it was meant to be static?)
public void Notify()
{
dynamic testMessage = new
{
Count = 3,
Message = "Some test message",
Timestamp = DateTime.Now
};
Clients.Client(Context.ConnectionId).sendNotification(testMessage);
}
You don't need to serialize twice, we already do it for you.
Remove:
jQuery.support.cors = true;
Never set that.
Also:
// Map the onConnect and onDisconnect functions
notification.client.connected = function () {
alert("Notification system connected");
};
notification.client.disconnected = function () { };
These aren't mapping anything client side. You can't map connected and disconnected from the server to the client. The client has its own events.
Other things:
This should be inside of the start callback so that you don't hit it before it's ready:
$.connection.hub.start().done(function() {
// Testing code only
$("#testButton").click(function () {
// Run test function on server
notification.server.runTest();
});
});

Resources