"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Mapping SignalR Users to Connections in SignalR 1.x

by Patrick Fletcher, Tom FitzMacken

This topic shows how to retain information about users and their connections.

Introduction

Each client connecting to a hub passes a unique connection id. You can retrieve this value in the Context.ConnectionId property of the hub context. If your application needs to map a user to the connection id and persist that mapping, you can use one of the following:

Each of these implementations is shown in this topic. You use the OnConnected, OnDisconnected, and OnReconnected methods of the Hub class to track the user connection status.

The best approach for your application depends on:

The following table shows which approach works for these considerations.

More than one server Get list of currently connected users Persist information after restarts Optimal performance
In-memory
Single-user groups
Permanent, external

In-memory storage

The following examples show how to retain connection and user information in a dictionary that is stored in memory. The dictionary uses a HashSet to store the connection id. At any time a user could have more than one connection to the SignalR application. For example, a user who is connected through multiple devices or more than one browser tab would have more than one connection id.

If the application shuts down, all of the information is lost, but it will be re-populated as the users re-establish their connections. In-memory storage does not work if your environment includes more than one web server because each server would have a separate collection of connections.

The first example shows a class that manages the mapping of users to connections. The key for the HashSet will be the user’s name.

[!code-csharpMain]

   1:  using System.Collections.Generic;
   2:  using System.Linq;
   3:   
   4:  namespace BasicChat
   5:  {
   6:      public class ConnectionMapping<T>
   7:      {
   8:          private readonly Dictionary<T, HashSet<string>> _connections =
   9:              new Dictionary<T, HashSet<string>>();
  10:   
  11:          public int Count
  12:          {
  13:              get
  14:              {
  15:                  return _connections.Count;
  16:              }
  17:          }
  18:   
  19:          public void Add(T key, string connectionId)
  20:          {
  21:              lock (_connections)
  22:              {
  23:                  HashSet<string> connections;
  24:                  if (!_connections.TryGetValue(key, out connections))
  25:                  {
  26:                      connections = new HashSet<string>();
  27:                      _connections.Add(key, connections);
  28:                  }
  29:   
  30:                  lock (connections)
  31:                  {
  32:                      connections.Add(connectionId);
  33:                  }
  34:              }
  35:          }
  36:   
  37:          public IEnumerable<string> GetConnections(T key)
  38:          {
  39:              HashSet<string> connections;
  40:              if (_connections.TryGetValue(key, out connections))
  41:              {
  42:                  return connections;
  43:              }
  44:   
  45:              return Enumerable.Empty<string>();
  46:          }
  47:   
  48:          public void Remove(T key, string connectionId)
  49:          {
  50:              lock (_connections)
  51:              {
  52:                  HashSet<string> connections;
  53:                  if (!_connections.TryGetValue(key, out connections))
  54:                  {
  55:                      return;
  56:                  }
  57:   
  58:                  lock (connections)
  59:                  {
  60:                      connections.Remove(connectionId);
  61:   
  62:                      if (connections.Count == 0)
  63:                      {
  64:                          _connections.Remove(key);
  65:                      }
  66:                  }
  67:              }
  68:          }
  69:      }
  70:  }

The next example shows how to use the connection mapping class from a hub. The instance of the class is stored in a variable name _connections.

[!code-csharpMain]

   1:  using System.Threading.Tasks;
   2:  using Microsoft.AspNet.SignalR;
   3:   
   4:  namespace BasicChat
   5:  {
   6:      [Authorize]
   7:      public class ChatHub : Hub
   8:      {
   9:          private readonly static ConnectionMapping<string> _connections = 
  10:              new ConnectionMapping<string>();
  11:   
  12:          public void SendChatMessage(string who, string message)
  13:          {
  14:              string name = Context.User.Identity.Name;
  15:   
  16:              foreach (var connectionId in _connections.GetConnections(who))
  17:              {
  18:                  Clients.Client(connectionId).addChatMessage(name + ": " + message);
  19:              }
  20:          }
  21:   
  22:          public override Task OnConnected()
  23:          {
  24:              string name = Context.User.Identity.Name;
  25:   
  26:              _connections.Add(name, Context.ConnectionId);
  27:   
  28:              return base.OnConnected();
  29:          }
  30:   
  31:          public override Task OnDisconnected()
  32:          {
  33:              string name = Context.User.Identity.Name;
  34:   
  35:              _connections.Remove(name, Context.ConnectionId);
  36:   
  37:              return base.OnDisconnected();
  38:          }
  39:   
  40:          public override Task OnReconnected()
  41:          {
  42:              string name = Context.User.Identity.Name;
  43:   
  44:              if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
  45:              {
  46:                  _connections.Add(name, Context.ConnectionId);
  47:              }
  48:   
  49:              return base.OnReconnected();
  50:          }
  51:      }
  52:  }

Single-user groups

You can create a group for each user, and then send a message to that group when you want to reach only that user. The name of each group is the name of the user. If a user has more than one connection, each connection id is added to the user’s group.

You should not manually remove the user from the group when the user disconnects. This action is automatically performed by the SignalR framework.

The following example shows how to implement single-user groups.

[!code-csharpMain]

   1:  using Microsoft.AspNet.SignalR;
   2:  using System;
   3:  using System.Threading.Tasks;
   4:   
   5:  namespace BasicChat
   6:  {
   7:      [Authorize]
   8:      public class ChatHub : Hub
   9:      {
  10:          public void SendChatMessage(string who, string message)
  11:          {
  12:              string name = Context.User.Identity.Name;
  13:   
  14:              Clients.Group(who).addChatMessage(name + ": " + message);
  15:          }
  16:   
  17:          public override Task OnConnected()
  18:          {
  19:              string name = Context.User.Identity.Name;
  20:   
  21:              Groups.Add(Context.ConnectionId, name);
  22:   
  23:              return base.OnConnected();
  24:          }
  25:      }
  26:  }

Permanent, external storage

This topic shows how to use either a database or Azure table storage for storing connection information. This approach works when you have multiple web servers because each web server can interact with the same data repository. If your web servers stop working or the application restarts, the OnDisconnected method is not called. Therefore, it is possible that your data repository will have records for connection ids that are no longer valid. To clean up these orphaned records, you may wish to invalidate any connection that was created outside of a timeframe that is relevant to your application. The examples in this section include a value for tracking when the connection was created, but do not show how to clean up old records because you may want to do that as background process.

Database

The following examples show how to retain connection and user information in a database. You can use any data access technology; however, the example below shows how to define models using Entity Framework. These entity models correspond to database tables and fields. Your data structure could vary considerably depending on the requirements of your application.

The first example shows how to define a user entity that can be associated with many connection entities.

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.Data.Entity;
   5:   
   6:  namespace MapUsersSample
   7:  {
   8:      public class UserContext : DbContext
   9:      {
  10:          public DbSet<User> Users { get; set; }
  11:          public DbSet<Connection> Connections { get; set; }
  12:      }
  13:   
  14:      public class User
  15:      {
  16:          [Key]
  17:          public string UserName { get; set; }
  18:          public ICollection<Connection> Connections { get; set; }
  19:      }
  20:   
  21:      public class Connection
  22:      {
  23:          public string ConnectionID { get; set; }
  24:          public string UserAgent { get; set; }
  25:          public bool Connected { get; set; }
  26:      }
  27:  }

Then, from the hub, you can track the state of each connection with the code shown below.

[!code-csharpMain]

   1:  using System;
   2:  using System.Data.Entity;
   3:  using System.Linq;
   4:  using System.Threading.Tasks;
   5:  using System.Collections.Concurrent;
   6:  using Microsoft.AspNet.SignalR;
   7:   
   8:  namespace MapUsersSample
   9:  {
  10:      [Authorize]
  11:      public class ChatHub : Hub
  12:      {
  13:          public void SendChatMessage(string who, string message)
  14:          {
  15:              var name = Context.User.Identity.Name;
  16:              using (var db = new UserContext())
  17:              {
  18:                  var user = db.Users.Find(who);
  19:                  if (user == null)
  20:                  {
  21:                      Clients.Caller.showErrorMessage("Could not find that user.");
  22:                  }
  23:                  else
  24:                  {
  25:                      db.Entry(user)
  26:                          .Collection(u => u.Connections)
  27:                          .Query()
  28:                          .Where(c => c.Connected == true)
  29:                          .Load();
  30:   
  31:                      if (user.Connections == null)
  32:                      {
  33:                          Clients.Caller.showErrorMessage("The user is no longer connected.");
  34:                      }
  35:                      else
  36:                      {
  37:                          foreach (var connection in user.Connections)
  38:                          {
  39:                              Clients.Client(connection.ConnectionID)
  40:                                  .addChatMessage(name + ": " + message);
  41:                          }
  42:                      }
  43:                  }
  44:              }
  45:          }
  46:   
  47:          public override Task OnConnected()
  48:          {
  49:              var name = Context.User.Identity.Name;
  50:              using (var db = new UserContext())
  51:              {
  52:                  var user = db.Users
  53:                      .Include(u => u.Connections)
  54:                      .SingleOrDefault(u => u.UserName == name);
  55:                  
  56:                  if (user == null)
  57:                  {
  58:                      user = new User
  59:                      {
  60:                          UserName = name,
  61:                          Connections = new List<Connection>()
  62:                      };
  63:                      db.Users.Add(user);
  64:                  }
  65:   
  66:                  user.Connections.Add(new Connection
  67:                  {
  68:                      ConnectionID = Context.ConnectionId,
  69:                      UserAgent = Context.Request.Headers["User-Agent"],
  70:                      Connected = true
  71:                  });
  72:                  db.SaveChanges();
  73:              }
  74:              return base.OnConnected();
  75:          }
  76:   
  77:          public override Task OnDisconnected()
  78:          {
  79:              using (var db = new UserContext())
  80:              {
  81:                  var connection = db.Connections.Find(Context.ConnectionId);
  82:                  connection.Connected = false;
  83:                  db.SaveChanges();
  84:              }
  85:              return base.OnDisconnected();
  86:          }
  87:      }
  88:  }

Azure table storage

The following Azure table storage example is similar to the database example. It does not include all of the information that you would need to get started with Azure Table Storage Service. For information, see How to use Table storage from .NET.

The following example shows a table entity for storing connection information. It partitions the data by user name, and identifies each entity by the connection id, so a user can have multiple connections at any time.

[!code-csharpMain]

   1:  using Microsoft.WindowsAzure.Storage.Table;
   2:  using System;
   3:   
   4:  namespace MapUsersSample
   5:  {
   6:      public class ConnectionEntity : TableEntity
   7:      {
   8:          public ConnectionEntity() { }        
   9:   
  10:          public ConnectionEntity(string userName, string connectionID)
  11:          {
  12:              this.PartitionKey = userName;
  13:              this.RowKey = connectionID;
  14:          }
  15:      }
  16:  }

In the hub, you track the status of each user’s connection.

[!code-csharpMain]

   1:  using Microsoft.AspNet.SignalR;
   2:  using Microsoft.WindowsAzure;
   3:  using Microsoft.WindowsAzure.Storage;
   4:  using Microsoft.WindowsAzure.Storage.Table;
   5:  using System;
   6:  using System.Linq;
   7:  using System.Threading.Tasks;
   8:   
   9:  namespace MapUsersSample
  10:  {
  11:      public class ChatHub : Hub
  12:      {
  13:          public void SendChatMessage(string who, string message)
  14:          {
  15:              var name = Context.User.Identity.Name;
  16:              
  17:              var table = GetConnectionTable();
  18:   
  19:              var query = new TableQuery<ConnectionEntity>()
  20:                  .Where(TableQuery.GenerateFilterCondition(
  21:                  "PartitionKey", 
  22:                  QueryComparisons.Equal, 
  23:                  who));
  24:   
  25:              var queryResult = table.ExecuteQuery(query).ToList();
  26:              if (queryResult.Count == 0)
  27:              {
  28:                  Clients.Caller.showErrorMessage("The user is no longer connected.");
  29:              }
  30:              else
  31:              {
  32:                  foreach (var entity in queryResult)
  33:                  {
  34:                      Clients.Client(entity.RowKey).addChatMessage(name + ": " + message);
  35:                  }
  36:              }
  37:          }
  38:   
  39:          public override Task OnConnected()
  40:          {
  41:              var name = Context.User.Identity.Name;
  42:              var table = GetConnectionTable();
  43:              table.CreateIfNotExists();
  44:   
  45:              var entity = new ConnectionEntity(
  46:                  name.ToLower(), 
  47:                  Context.ConnectionId);
  48:              var insertOperation = TableOperation.InsertOrReplace(entity);
  49:              table.Execute(insertOperation);
  50:              
  51:              return base.OnConnected();
  52:          }
  53:   
  54:          public override Task OnDisconnected()
  55:          {
  56:              var name = Context.User.Identity.Name;
  57:              var table = GetConnectionTable();
  58:   
  59:              var deleteOperation = TableOperation.Delete(
  60:                  new ConnectionEntity(name, Context.ConnectionId) { ETag = "*" });
  61:              table.Execute(deleteOperation);
  62:   
  63:              return base.OnDisconnected();
  64:          }
  65:   
  66:          private CloudTable GetConnectionTable()
  67:          {
  68:              var storageAccount =
  69:                  CloudStorageAccount.Parse(
  70:                  CloudConfigurationManager.GetSetting("StorageConnectionString"));
  71:              var tableClient = storageAccount.CreateCloudTableClient();
  72:              return tableClient.GetTableReference("connection");
  73:          }
  74:      }
  75:  }





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/signalr/overview/older-versions/mapping-users-to-connections.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>