SignalR save sender Id and receiver Id in ASP.NET MVC C# - c#

I am following this Signal R tutorial from Microsoft. I have already configured everything for SignalR to be working and it does work.
This is my Front End script to call SignalR
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
As you can see in the microsoft tutorial, I require to create a hub class with this method.
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
My question is, given an mvc application with login (each user have its own Id), how can I send the receiver Id to my backend so I can save it into my database?
I have already tried to modify the Send function
public class chat
{
public int Id { get; set; }
public string Message { get; set; }
public string Name { get; set; }
public Guid receiverId { get; set; }
}
public void Send(string name, string message,string receiverId)
{
// Call the addNewMessageToPage method to update clients.
chatultimo chat = new chatultimo();
chat.Name = name;
chat.Message = message;
chat.Id = Guid.NewGuid();
_dbContext.chatultimo.Add(chat);
_dbContext.SaveChanges();
Clients.All.addNewMessageToPage(name, message);
}
I also made a modification in my function in the front end
chat.client.addNewMessageToPage = function (name, message)
you can see that the Send function is being called in the front end, but after modifying the send function my application is not hiting the backend.
chat.client.addNewMessageToPage = function (name, message,receiverId)
Another thing is I do not think it is a good idea to modify the send function. I think it is much better to do the database job in the $.connection.hub.start().done(function () ...
to make sure it is only executed after the handshake.

Related

How to update only specific page's Likes count using SignalR in MVC

I have a problem in implementing SignalR in my MVC application. I am updating my posts like count every time a person clicks on like button of a specific album post page. But I am facing a problem here that when I click on Like button of a specific page, the likes count of the other pages is also incremented.
so here is my NotificationHub code:
public class NotificationHub : Hub
{
public void Like(Guid albumId, Guid managerId)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
var LikeCounter = SaveLike(albumId, managerId);
Clients.All.updateLikeCount(LikeCounter);
}
public int? SaveLike(Guid albumId, Guid managerId)
{
// my implementation code
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
}
This is my jQuery code:
$(function () {
var albumClient = $.connection.notificationHub;
albumClient.client.updateLikeCount = function (likes) {
var counter = $(".like-count");
$(counter).fadeOut(function () {
$(this).text(likes);
$(this).fadeIn();
});
};
$(".like-button").on("click", function () {
var albumId = $(this).attr("data-id");
var managerId = $(this).attr("id");
albumClient.server.like(albumId, managerId);
});
$.connection.hub.start();
});
So kindly help me what I am doing wrong or what modifications are needed in this code.
First let me point out few mistakes in the code.
$(function () {
var albumClient = $.connection.notificationHub;
albumClient.client.updateLikeCount = function (likes) {
var counter = $(".like-count"); //selects all like button. Thats why every page buttons are updated.
$(counter).fadeOut(function () {
$(this).text(likes);
$(this).fadeIn();
});
};
$(".like-button").on("click", function () {
var albumId = $(this).attr("data-id");
var managerId = $(this).attr("id");
albumClient.server.like(albumId, managerId); // you are calling the server method and the server has no clue of which button to update.
});
$.connection.hub.start();
});
So as pointed out in the comments. Firstly you are calling the server by passing some data which is fine. But the server has to later send ping to the client and update what?? which button?? it has no clue. And you are using a class selector for the buttons $(".like-count") which will select all the buttons with that class name, And later you update all the buttons because of this.
So the solution is each of your button must have a unique id like to which page it belongs or any other data which makes it unique. You can still have the same class and same event binded to on click. Only change would be like below.
$(".like-button").on("click", function () {
var albumId = $(this).attr("data-id");
var managerId = $(this).attr("id");
albumClient.server.like(albumId, managerId, $(this).attr('id')); //pass the id of the like button as well to your signalR code
});
Modify your SignalR code to below.
public void Like(Guid albumId, Guid managerId,string buttonID) //include parameter to accept button Id
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
var LikeCounter = SaveLike(albumId, managerId);
Clients.All.updateLikeCount(LikeCounter,buttonID); //pass back the button id as well.
}
Now to the last change.
albumClient.client.updateLikeCount = function (likes,btnId) { // input parameter
//directly change the button likes.
$('#'+btnId).fadeOut(function () {
$(this).text(likes);
$(this).fadeIn();
});
};
let me know if this helps
You need to add Users to a Groups on page load:
this.Groups.Add(this.Context.ConnectionId, postName)
then:
Clients.Group(postName).updateLikeCount(LikeCounter);

SignalR Javascript Client: Cannot Start Connection

My connection does not start.
This code worked in 1.x but in version 2 is not working.
SignalR seems to be trying to connect but without success.
The hub method is never called.
Attached sending an image with SignalR debug.
Javascript:
<script type="text/javascript">
$.connection.hub.logging = true;
var options = { transport: ['webSockets', 'longPolling'] };
$(function() {
var userHub = $.connection.userHub;
//Iniciar connecção
window.hubReady = $.connection.hub.start(options);
window.hubReady.done(function () {
userHub.server.ini();
});
userHub.client.iniDone = function (connectionId) {
console.log(connectionId);
};
$.connection.hub.connectionSlow(function() {
console.log('slow connection...');
});
window.hubReady.fail(function(error) {
console.log(error);
});
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 2000);
});
});
</script>
Hub:
[HubName("userHub")]
public class UserHub : Hub
{
public void Ini()
{
Clients.Client(Context.ConnectionId).iniDone(string.Format("Conectado com o id: {0}", Context.ConnectionId));
}
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var email = string.IsNullOrWhiteSpace(Context.User.Identity.Name) ? Context.Headers["email"] : Context.User.Identity.Name;
if (email != null && connectionId != null)
UserData.GetInstance(email).ConnectionsIds.Add(connectionId);
return base.OnConnected();
}
public override Task OnDisconnected()
{
var connectionId = Context.ConnectionId;
var email = string.IsNullOrWhiteSpace(Context.User.Identity.Name) ? Context.Headers["email"] : Context.User.Identity.Name;
if (email != null && connectionId != null)
UserData.GetInstance(email).ConnectionsIds.Remove(connectionId);
return base.OnDisconnected();
}
}
Debug:
SignalR Debug Image
EDIT:
I found the problem! The GetInstance method of my Singleton has problems.
public static UserData GetInstance(string username)
{
if (_sharedUsers == null)
lock (_lockCreate)
_sharedUsers = new Dictionary<string, UserData>();
if (!_sharedUsers.ContainsKey(username))
lock (_lockAdd)
_sharedUsers.Add(username, new UserData(username));
return _sharedUsers[username];
}
the method stops always here: lock (_lockAdd)
I want to save all user connectionsIds Any ideas?
Thanks
Try moving the client method subscription to be before you connect. If it's not registered by the time the connection is started, then it will not be callable from the server.
So change it to the following:
$(function() {
var userHub = $.connection.userHub;
//Register Client handlers first
userHub.client.iniDone = function (connectionId) {
console.log(connectionId);
};
//Now you can connect.
window.hubReady = $.connection.hub.start(options);
window.hubReady.done(function () {
userHub.server.ini();
});
$.connection.hub.connectionSlow(function() {
console.log('slow connection...');
});
window.hubReady.fail(function(error) {
console.log(error);
});
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 2000);
});
});
Edit
Based on your comment around a server error in the OnConnected method, it seems like you may have a two problems then. Isolate the connection tracking part out (just comment it out) to get the full round-trip going between client and server. Then add back the connection tracking which is possibly a DB connection error - check the server logs.
Edit
In terms of storing the user connections, you've a few options.
Use ConcurrentDictionary:
One of the simplest is storing in a static ConcurrentDictionary, similar to what you have. Try to avoid the use of so many locks - using a ConcurrentDictionary means you'll actually end up with none.
e.g.
public class UserData
{
public UserData(string username)
{
UserName = username;
ConnectionIds = new HashSet<string>();
}
public string UserName { get; private set; }
public HashSet<string> ConnectionIds { get; private set; }
}
public static class ConnectionStore
{
private static readonly ConcurrentDictionary<string, UserData> _userData = new ConcurrentDictionary<string, UserData>();
public static void Join(string username, string connectionId)
{
_userData.AddOrUpdate(username,
u => new UserData(u), /* Lambda to call when it's an Add */
(u, ud) => { /* Lambda to call when it's an Update */
ud.ConnectionIds.Add(connectionId);
return ud;
});
}
}
See MSDN for more info: http://msdn.microsoft.com/en-us/library/ee378675(v=vs.110).aspx
Use a database:
The other option is to store in a database (using Entity Framework) which has the added benefit of tracking user data across server recycles.
Have a look at http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections which shows all these options a couple of others.
Had the same problem for so long, so gave up the whole signalR at some point, but had to pick it up again for our project:
I have written an answer which might lead you and others on the right track (step by step)...In the answer I am using PersistentConnection rather than Hub, but the principle should be the same:
https://stackoverflow.com/a/25304790/3940626

How to obtain connection ID of signalR client on the server side?

I need to get the connection ID of a client. I know you can get it from the client side using $.connection.hub.id. What I need is to get in while in a web service I have which updates records in a database, in turn displaying the update on a web page. I am new to signalR and stackoverflow, so any advice would be appreciated. On my client web page I have this:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notify = $.connection.notificationHub;
// Create a function that the hub can call to broadcast messages.
notify.client.broadcastMessage = function (message) {
var encodedMsg = $('<div />').text(message).html();// Html encode display message.
$('#notificationMessageDisplay').append(encodedMsg);// Add the message to the page.
};//end broadcastMessage
// Start the connection.
$.connection.hub.start().done(function () {
$('#btnUpdate').click(function () {
//call showNotification method on hub
notify.server.showNotification($.connection.hub.id, "TEST status");
});
});
});//End Main function
</script>
everything works up until I want to update the page using signalR. The show notification function in my hub is this:
//hub function
public void showNotification(string connectionId, string newStatus){
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
string connection = "Your connection ID is : " + connectionId;//display for testing
string statusUpdate = "The current status of your request is: " + newStatus;//to be displayed
//for testing, you can display the connectionId in the broadcast message
context.Clients.Client(connectionId).broadcastMessage(connection + " " + statusUpdate);
}//end show notification
how can I send the connectionid to my web service?
Hopefully I'm not trying to do something impossible.
When a client invokes a function on the server side you can retrieve their connection ID via Context.ConnectionId. Now, if you'd like to access that connection Id via a mechanism outside of a hub, you could:
Just have the Hub invoke your external method passing in the connection id.
Manage a list of connected clients aka like public static ConcurrentDictionary<string, MyUserType>... by adding to the dictionary in OnConnected and removing from it in OnDisconnected. Once you have your list of users you can then query it via your external mechanism.
Ex 1:
public class MyHub : Hub
{
public void AHubMethod(string message)
{
MyExternalSingleton.InvokeAMethod(Context.ConnectionId); // Send the current clients connection id to your external service
}
}
Ex 2:
public class MyHub : Hub
{
public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>();
public override Task OnConnected()
{
MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId });
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
MyUserType garbage;
MyUsers.TryRemove(Context.ConnectionId, out garbage);
return base.OnDisconnected(stopCalled);
}
public void PushData(){
//Values is copy-on-read but Clients.Clients expects IList, hence ToList()
Clients.Clients(MyUsers.Keys.ToList()).ClientBoundEvent(data);
}
}
public class MyUserType
{
public string ConnectionId { get; set; }
// Can have whatever you want here
}
// Your external procedure then has access to all users via MyHub.MyUsers
Hope this helps!
Taylor's answer works, however, it doesn't take into consideration a situation where a user has multiple web browser tabs opened and therefore has multiple different connection IDs.
To fix that, I created a Concurrent Dictionary where the dictionary key is a user name and the value for each key is a List of current connections for that given user.
public static ConcurrentDictionary<string, List<string>> ConnectedUsers = new ConcurrentDictionary<string, List<string>>();
On Connected - Adding a connection to the global cache dictionary:
public override Task OnConnected()
{
Trace.TraceInformation("MapHub started. ID: {0}", Context.ConnectionId);
var userName = "testUserName1"; // or get it from Context.User.Identity.Name;
// Try to get a List of existing user connections from the cache
List<string> existingUserConnectionIds;
ConnectedUsers.TryGetValue(userName, out existingUserConnectionIds);
// happens on the very first connection from the user
if(existingUserConnectionIds == null)
{
existingUserConnectionIds = new List<string>();
}
// First add to a List of existing user connections (i.e. multiple web browser tabs)
existingUserConnectionIds.Add(Context.ConnectionId);
// Add to the global dictionary of connected users
ConnectedUsers.TryAdd(userName, existingUserConnectionIds);
return base.OnConnected();
}
On disconnecting (closing the tab) - Removing a connection from the global cache dictionary:
public override Task OnDisconnected(bool stopCalled)
{
var userName = Context.User.Identity.Name;
List<string> existingUserConnectionIds;
ConnectedUsers.TryGetValue(userName, out existingUserConnectionIds);
// remove the connection id from the List
existingUserConnectionIds.Remove(Context.ConnectionId);
// If there are no connection ids in the List, delete the user from the global cache (ConnectedUsers).
if(existingUserConnectionIds.Count == 0)
{
// if there are no connections for the user,
// just delete the userName key from the ConnectedUsers concurent dictionary
List<string> garbage; // to be collected by the Garbage Collector
ConnectedUsers.TryRemove(userName, out garbage);
}
return base.OnDisconnected(stopCalled);
}
I beg to differ on the reconnect. The client remains in the list but the connectid will change. I do an update to the static list on reconnects to resolve this.
As Matthew C is not completely thread safe in situation of one user request multiple connection at same time, I used this code:
public static Dictionary<string, List<string>> ConnectedUsers = new ();
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var userId = Context.User.Identity.Name; // any desired user id
lock(ConnectedUsers)
{
if (!ConnectedUsers.ContainsKey(userId))
ConnectedUsers[userId] = new();
ConnectedUsers[userId].Add(connectionId);
}
}
public override Task OnDisconnected(bool stopCalled)
{
var connectionId = Context.ConnectionId;
var userId = Context.User.Identity.Name; // any desired user id
lock (ConnectedUsers)
{
if (ConnectedUsers.ContainsKey(userId))
{
ConnectedUsers[userId].Remove(connectionId);
if (ConnectedUsers[userId].Count == 0)
ConnectedUsers.Remove(userId);
}
}
}

SignalR .Net client: How do I send a message to a Group?

I am using the sample Chat application from the SignalR Wiki Getting Started Hubs page. I have extended it to add Group support and it is working fine.
However, now I want to send a message to the group from an external Console application. Here is my code for the Console app and below that my code for Groups. How do I send a message to a Group from a proxy? Is it possible?
// Console App
using System;
using Microsoft.AspNet.SignalR.Client.Hubs;
namespace SignalrNetClient
{
class Program
{
static void Main(string[] args)
{
// Connect to the service
var connection = new HubConnection("http://localhost:50116");
var chatHub = connection.CreateHubProxy("Chat");
// Print the message when it comes in
connection.Received += data => Console.WriteLine(data);
// Start the connection
connection.Start().Wait();
chatHub.Invoke("Send", "Hey there!");
string line = null;
while ((line = Console.ReadLine()) != null)
{
// Send a message to the server
connection.Send(line).Wait();
}
}
}
}
SignalR Web App Host:
namespace SignalrServer.Hubs
{
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.All.addMessage(message);
Clients.Group("RoomA").addMessage("Group Message " + message);
}
//server
public void Join(string groupName)
{
Groups.Add(Context.ConnectionId, groupName);
}
}
}
Default.aspx
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.1.min.js" type="text/javascript"></script>
<!-- If this is an MVC project then use the following -->
<!-- <script src="~/signalr/hubs" type="text/javascript"></script> -->
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
$.connection.hub.start(function () {
chat.server.join("RoomA");
});
// Start the connection
$.connection.hub.start().done(function () {
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val());
});
});
});
</script>
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
</div>
What I have done with something similar is to create a method which accepts an object of your choice, e.g.
Your new class
public class MyMessage{
public string Msg { get; set; }
public string Group { get; set; }
}
Then create a method in the Hub that accepts this object.
public void Send(MyMessage message)
{
// Call the addMessage method on all clients
Clients.All.addMessage(message.Msg);
Clients.Group(message.Group).addMessage("Group Message " + message.Msg);
}
Then from your client, you can then pass this object in.
chatHub.Invoke<MyMessage>("send", new MyMessage() { Msg = "Hello World", Group = "RoomA" });
You can then also call this from the JS client
chat.server.send({ Msg: "Hello World", Group: "RoomA" });

Accidently Sending Multiple Messages with SignalR

I'm new to SignalR but I understand the concept.
My goal is to expose web services which when called will update all connected clients. I've built a little knockout js to connect to the hub and that works well. When I click my start button it sends a message to each of the clients connected like it is supposed to. Here is the code for a background.
Hub:
[HubName("realTimeData")]
public class RealTimeDataHub : Hub
{
public void UpdateFlash(string message)
{
Clients.flashUpdated(message);
}
public void clear()
{
Clients.cleared();
}
}
JS:
function viewModel(){
var self = this;
self.messages = ko.observableArray([]);
self.hub = $.connection.realTimeData;
self.hub.flashUpdated = function (m) {
self.messages.push(new message(m));
};
self.hub.cleared = function () {
self.messages.removeAll();
};
self.Start = function () {
self.hub.updateFlash("Updated Flashed from client");
};
self.Stop = function () {
self.hub.clear();
};
$.connection.hub.start();
}
ko.applyBindings(new viewModel());
MVC API:
public class HomeController : Controller
{
public ActionResult Update()
{
GetClients().updateFlash("From server");
return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
private static dynamic GetClients()
{
return GlobalHost.ConnectionManager.GetHubContext<RealTimeData.Hubs.RealTimeDataHub>().Clients;
}
}
The problem:
When I call the "Update" method from my controller (Home/Update, not a real API yet) it sends one signal for each of the clients connected. So if I have 2 clients connected, I will get 2 "From Server" messages to each client and so on. I would only like the one...
Any suggestions? Anything is appreciated
Thanks,
Matt
Solution:
Must import 'using SignalR.Client;'
public ActionResult Update()
{
hub.Invoke("UpdateFlash", "From the Home Controller");
//GetClients().updateFlash("From server");
return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
Here is where I found the solution:
https://github.com/SignalR/SignalR/wiki/SignalR-Client-Hubs
I hope this can help somebody out.
Matt

Categories