Tracking SignalR connection ids to see if they really exist - asp.net

Currently, I am storing all connected user's connection ids inside my database by mapping them to actual application users. What I do is pretty simple here: I add the connection id to the database when OnConnected event is fired. Then, I remove that connection from the database when OnDisconnected event is fired.
However, at some cases (for example, when the process is terminated, etc.), I don't get the disconnect event. This makes my connection table unreliable because I cannot be sure if the user is connected on one or more clients. For example, here is a block of code on my OnDisconnected method:
HubConnection hubConnection = _hubConnectionRepository.GetAll()
.FirstOrDefault(conn => conn.ConnectionId == connectionId);
if (hubConnection != null)
{
_hubConnectionRepository.Delete(hubConnection);
_hubConnectionRepository.Save();
}
if (!_hubConnectionRepository.GetAll().Any(conn => conn.UserId == user.Id))
{
Clients.Others.userDisconnected(username);
}
As you see, I check if there is any other connections associated to that user just after I remove his/her current connection. Depending on the case, I broadcast a message to all connected clients.
What I want here is something like this: to be able to poll the SignalR system with an array of connection ids and get back the disconnected ones so that I can remove them from my connection list inside the database. As far as I remember from my conversation with David Fowler, this's not possible today but what's the preferred approach on such cases?

This is just an idea.
On server:
Clients.All.ping()
On clients:
hub.client.ping = function() {
hub.server.pingResponse();
}
On Server:
void pingResponse()
{
Context.ConnectionId; //update database
}

This is what I did:
I have a class HubConnectionManager:
public class HubConnectionManager
{
static HubConnectionManager()
{
connections = new Dictionary<string, List<string>>();
users = new List<Login>();
}
#region Static Fields
private static Dictionary<string, List<string>> connections;
private static List<Login> users;
#endregion
#region Public Properties
public static Dictionary<string, List<string>> Connections
{
get
{
return connections;
}
}
#endregion
#region Public Methods and Operators
public static void AddConnection(Login login, string connectionId)
{
if (!connections.ContainsKey(login.LoginName))
{
connections.Add(login.LoginName, new List<string>());
if (!users.Contains(login))
{
users.Add(login);
}
}
// add with new connection id
connections[login.LoginName].Add(connectionId);
}
public static bool IsOnline(string connectionId)
{
return connections.Any(x => !string.IsNullOrEmpty(x.Value.FirstOrDefault(y => y == connectionId)));
}
public static void RemoveConnection(string user, string connectionId)
{
if (connections.ContainsKey(user))
{
connections[user].Remove(connectionId);
if (connections[user].Count == 0)
{
connections.Remove(user);
// remove user
users.RemoveAll(x => x.LoginName == user);
}
}
}
public static int GetAllConnectionsCount()
{
return connections.Keys.Sum(user => connections[user].Count);
}
public static Login GetUser(string connectionId)
{
string userName = connections.FirstOrDefault(x => x.Value.Any(y => y == connectionId)).Key;
return users.FirstOrDefault(x => x.LoginName == userName);
}
#endregion
}
I'm using a dictionary that holds UserName and it's list of connections (this is because like you said sometimes OnDisconnected doesn't fire properly:
connections = new Dictionary<string, List<string>>();
Then in your hub, you can check if a connection is still "connected"/ valid:
public class TaskActionStatus : Hub
{
public void SendMessage()
{
if (HubConnectionManager.IsOnline(Context.ConnectionId))
{
this.Clients.Client(Context.ConnectionId).actionInit("test");
}
}
...
}

Related

How to send message via SignalR to a specific User(Identity Id)?

In my Startup.Auth.cs:
private static void ConfigSignalR(IAppBuilder appBuilder)
{
appBuilder.MapSignalR();
var idProvider = new PrincipalUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
}
My UserHub.cs:
public class UserHub : Hub
{
}
On the server-side, in one of my API Controller action (a Put related to a Grid Update):
[...]
var userHub = GlobalHost.ConnectionManager.GetHubContext<UserHub>();
// Line below does not work
// userHub.Clients.User(userId).send("Hi");
// But this line below works when sending the message to everybody
userHub.Clients.All.send("Hi");
return Request.CreateResponse(HttpStatusCode.OK);
On the JS View client-side:
#Request.IsAuthenticated
{
<script>
$(function() {
var userHub = $.connection.userHub;
console.log(userHub.client);
userHub.client.send = function(message) {
alert('received: ' + message);
};
$.connection.hub.start().done(function() {
});
});
</script>
}
Why when passing the userId my client receives nothing?
(also tried passing the userName, with the same outcome).
[EDIT]
Technically the right way to achieve that is to leverage the implementation of the IUserIdProvider:
https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections#IUserIdProvider
SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*
However, I've noticed that in my case the User property of the IRequest object passed to the GetUserId method is always set to null...
The solution was actually already given for another issue, right here: https://stackoverflow.com/a/22028296/4636721
The problem was all about the initialization order in the Startup.Auth.cs:
SignalR must be initialized after the cookies and the OwinContext initialization, such as that IUserIdProvider passed to GlobalHost.DependencyResolver.Register receives a IRequest containing a non-null User for its GetUserId method:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder appBuilder)
{
// Order matters here...
// Otherwise SignalR won't get Identity User information passed to Id Provider...
ConfigOwinContext(appBuilder);
ConfigCookies(appBuilder);
ConfigSignalR(appBuilder);
}
private static void ConfigOwinContext(IAppBuilder appBuilder)
{
appBuilder.CreatePerOwinContext(ApplicationDbContext.Create);
appBuilder.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
appBuilder.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
appBuilder.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
appBuilder.CreatePerOwinContext(LdapAdEmailAuthenticator.Create);
}
private static void ConfigCookies(IAppBuilder appBuilder)
{
appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>
(
TimeSpan.FromHours(4),
(manager, user) => user.GenerateUserIdentityAsync(manager)
)
}
});
appBuilder.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
appBuilder.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
appBuilder.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
private static void ConfigSignalR(IAppBuilder appBuilder)
{
appBuilder.MapSignalR();
var idProvider = new HubIdentityUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
}
}
Using the IUserIdProvider below, I explicit declared that I want to use the UserId and not the UserName as given by the default implementation of the IUserIdProvider, aka PrincipalUserIdProvider:
public class HubIdentityUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
return request == null
? throw new ArgumentNullException(nameof(request))
: request.User?.Identity?.GetUserId();
}
}

Sending a message to a specific user via signalr

I am trying to use the new User Id provider specified in signalr 2 to send messages to a specific user. When I call the Clients.All method, I see this working as my javascript code gets called from the server and the ui produces some expected text for my test case. However, when I switch to Clients.User the client side code is never called from the server. I followed the code outlined in this example: SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*.
NotificationHub.cs:
public class NotificationHub : Hub
{
[Authorize]
public void NotifyUser(string userId, int message)
{
Clients.User(userId).DispatchMessage(message);
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
}
IUserIdProvider.cs:
public class UserIdProvider : IUserIdProvider
{
MemberService _memberService;
public UserIdProvider()
{
}
public string GetUserId(IRequest request)
{
long UserId = 0;
if (request.User != null && request.User.Identity != null &&
request.User.Identity.Name != null)
{
var currenUser = Task.Run(() => _memberService.FindByUserName(request.User.Identity.Name)).Result;
UserId = currenUser.UserId;
}
return UserId.ToString();
}
}
Startup.cs
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Routes.MapHttpRoute(
"Default2",
"api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
"DefaultApi2",
"api/{controller}/{id}",
new { id = RouteParameter.Optional });
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var idProvider = new UserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new QueryStringOAuthBearerAuthenticationProvider()
});
var hubConfiguration = new HubConfiguration
{
};
map.RunSignalR(hubConfiguration);
});
app.MapSignalR();
QuerstringOAuthBearerAuthenticationProvider:
public class QueryStringOAuthBearerAuthenticationProvider
: OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context == null) throw new ArgumentNullException("context");
// try to find bearer token in a cookie
// (by default OAuthBearerAuthenticationHandler
// only checks Authorization header)
var tokenCookie = context.OwinContext.Request.Cookies["BearerToken"];
if (!string.IsNullOrEmpty(tokenCookie))
context.Token = tokenCookie;
return Task.FromResult<object>(null);
}
}
Do I need to map the user to the connections myself using the IUserIdProvider through the OnConnected, OnDisconnected, etc. or does this happen automatically behind the scenes? Is there someone wrong in my posted code that could be a problem as well? I am running signalr from the same environment as my web api rest services, don't know if this makes a difference and using the default bearer token setup web api is using.
It would be far easier for you to create a group based on the connectionid of the connecting client, in the onConnected event and broadcast to the group that matches the connected id, that way if the client disconnects, when they reconnect they would simply belong to a new group the themselves. Unless of course you are required to have an authenticated user.

Adding username to groups in SignalR

Is it possible to use the IUserIDProvider instead of ConnectionID when working with Groups? I have already found an answer here, but that concerns the SignalR 1.0 version. I wonder, whether things have changed in 2.0.
So far, I was using the conventional
Groups.Add(Context.ConnectionId, "groupName");
However, it was difficult to keep track of the connected users when their connectionID was changed (the client is a Xamarin Android app and somehow, reconnection always resulted in creation of a new ConnectionID). Thus, when the client is connecting, I have added a header:
public async Task<bool> Login(int waitMilis, string name)
{
var cts = new CancellationTokenSource();
try
{
cts.CancelAfter(waitMilis);
_connection.Headers.Add("userName", name);
await _connection.Start();
return true;
}
catch(Exception ex)
{
CallFailure(ex);
return false;
}
}
And on server side, implemented the IUserIdProvider:
public class MyUserProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
else if (request.Headers != null && request.Headers["userName"] != null)
return request.Headers["userName"].ToString();
else return null;
}
}
Now, I would like to do something like
Groups.Add("userName", "groupName");
but the Add method does not have an overload for IUserIdProvider. So, is there a possibility to combine the IUserIdProvider and working with Groups, or am I stuck to creating a ConcurrentDictionary and then calling this?
foreach(User user in group.Users)
{
Clients.User(user.Name).SendMessage(message,
group.LastUpdateIndex
);
}
It ruins the whole beauty and simplicity of the SignalR code :-/
Unfortunately, there isn't currently a method like Groups.Add("userName", "groupName"); in SignalR.
I suggest adding users to their appropriate group(s) in OnConnected:
public class MyHub : Hub
{
public override async Task OnConnected()
{
var userName = MyUserHelper.GetUserId(Context.Request);
foreach (var groupName in GroupManager.GetJoinedGroups(userName))
{
await Groups.Add(Context.ConnectionId, groupName);
}
}
// ...
}
If you need to add an already connected user to a group, then you will likely need to send a message to the user using something like Clients.User(userName).joinGroup(groupName). Each client with userName could then call the appropriate hub method to join groupName.

SignalR PersistentConnection Cathcing Ping or Send Custom Ping by js client

On server side I have
public class Global : System.Web.HttpApplication
{
private static List<UserInfo> _Users;
public static List<UserInfo> Users
{
get { return Global._Users; }
set
{
lock (_Users)
{
Global._Users = value;
}
}
}
...
public class RawHub : PersistentConnection
{
protected override Task OnConnected(IRequest request, string connectionId)
{
var UserID = request.QueryString.Where(t => t.Key == "U");
if (!string.IsNullOrEmpty(UserID.First().Value))
{
var ui = new Guid(UserID.First().Value);
var user = Global.Users.FirstOrDefault(x => x.USERID == ui);
if (user == null)
{
var us = new UserInfo();
us.USERID = ui;
us.ConnectionId = connectionId;
Global.Users.Add(us);
}
else
{
user.ConnectionId=connectionId;
}
return Connection.Send(user.ConnectionId,"Good To Go");
}
}
I want to tryout send users their specific infos user by user with Send ...
bu I have to clean up Global.Users when they are disconnected.
Q: Is that possible to catch pings ? from js client or must i have to ping to client to detect live or not ?
What is the best approach
thnks
May br you can send custom i am alive messages from js client. Becouse some times ping doesnot come from client as expected. Usually when network is busy this happens...
good luck
Not sure what exactly is the problem here but you can simply listen for messages/pings in OnReceived
asp.net/signalr

SignalR cross-domain connection - connecting connection Id's with users

I'm hosting my signalr hub on a separate domain and making cross domain connection to hub from my main application. When a user logs into the main application, signalr connection is established. Now, the problem I'm having is how to identify the connected user inside the hub.
If my Hub was within the main application then I could use the Context.User of the logged in user and maintain a dictionary and update them on Connect and Disconnect events.
But being a cross-domain connection, I don't have the Context.User and no way for me to know to whom that connection ID belongs to. I'm lost here.
What am I missing here?
You should keep users credentials and connections ids yourself. You should define List<ClientsEntity> or something like that. Then override onConnected and onDisconnected methods. Client has to send querystring for connecting to your Hub as Lars said.
for example clients send to you like this
$.connection.hub.qs = { 'token' : 'id' };
In the Hub Class:
public class ChatHub : Hub
{
static List<ClientsEntity> clientsList = new List<ClientsEntity>();
public override Task OnConnected()
{
string connectionID = Context.ConnectionId;
string token = Context.QueryString["token"];
ClientsEntity clientItem = new ClientsEntity();
clientItem.connectionId = connectionID;
clientItem.token = token;
clientItem.connectionTime = DateTime.Now;
clientsList.Add(clientItem);
return base.OnConnected();
}
public override Task OnDisconnected()
{
ClientsEntity item = clientsList.FirstOrDefault(c => c.connectionId == Context.ConnectionId);
if (item != null) {
clientsList.Remove(item);
}
return base.OnDisconnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
public void Send(string token, string message)
{
ClientsEntity user = clientsList.FirstOrDefault(c => c.token == token);
if (user != null)
Clients.Client(user.connectionId).sendMessage(token, message);
}
public void GetConnectedClients(string token) {
ClientsEntity user = clientsList.FirstOrDefault(c => c.token == token);
if(token.Equals("-1") && user != null)
Clients.Client(user.connectionId).getConnClients(clientsList);
}
}
You could assign a unique connection token to the user once they log in; then make the client send that in the query string:
$.connection.hub.qs = { 'token' : id };

Resources