public override async Task OnConnected() { var name = Context.User.Identity.Name; using (var db = new UserContext()) { var user = db.Users .Include(u => u.Connections) .SingleOrDefault(u => u.UserName == name); if (user == null) { user = new User { UserName = name, Connections = new List<Connection>() }; db.Users.Add(user); } user.Connections.Add(new Connection { ConnectionId = Context.ConnectionId, UserAgent = Context.Request.Headers["User-Agent"], LastActivity = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(); } }
public override async Task OnReconnected() { using (var db = new UserContext()) { var connection = await db.Connections.FindAsync(Context.ConnectionId); // Ensure the connection exists if (connection == null) { db.Connections.Add(new Connection { ConnectionId = Context.ConnectionId, UserAgent = Context.Request.Headers["User-Agent"], LastActivity = DateTimeOffset.UtcNow, UserName = Context.User.Identity.Name }); } else { connection.LastActivity = DateTimeOffset.UtcNow; } await db.SaveChangesAsync(); } }
public override async Task OnDisconnected() { using (var db = new UserContext()) { var connection = await db.Connections.FindAsync(Context.ConnectionId); db.Connections.Remove(connection); await db.SaveChangesAsync(); } }
private void Check() { using (var db = new UserContext()) { // Get all connections on this node and update the activity foreach (var trackedConnection in _heartbeat.GetConnections()) { if (!trackedConnection.IsAlive) { continue; } Connection connection = db.Connections.Find(trackedConnection.ConnectionId); // Update the client's last activity if (connection != null) { connection.LastActivity = DateTimeOffset.UtcNow; } else { // We have a connection that isn't tracked in our DB! // This should *NEVER* happen // Debugger.Launch(); } } // Now check all db connections to see if there's any zombies // Remove all connections that haven't been updated based on our threshold var zombies = db.Connections.Where(c => SqlFunctions.DateDiff("ss", c.LastActivity, DateTimeOffset.UtcNow) >= _zombieThreshold); // We're doing ToList() since there's no MARS support on azure foreach (var connection in zombies.ToList()) { db.Connections.Remove(connection); } db.SaveChanges(); } }