public void ConnectAgent() { var userName = HttpContext.Current.User.Identity.Name; var fullName = getFullName(); var agent = Agents.SingleOrDefault(x => x.Key == userName); if (agent.Key == null) { var newAgent = new User { ConnectionID = Context.ConnectionId, UserName = userName, FullName = fullName, }; Agents.TryAdd(userName, newAgent); } //this happens if the agent opens a new tab of the support page without closing the other //remove all sessions with previous connection id, and update the Agents dict else { RemoveAgentSession(Agents[userName].ConnectionID, false); Agents[userName].ConnectionID = Context.ConnectionId; } }
public void StartChat() { //Let the user know if no agent is online if (Agents == null || Agents.Count == 0) { Clients.Caller.addMessage(FROM_ADMIN, NO_AGENT); return; } //get the agent with the fewest chat sessionss var inSessions = Agents.Select(session => new { AgentUserName = session.Value.UserName, SessionCount = ChatSessions.Count(x => x.Value == session.Value) }).OrderBy(x => x.SessionCount); if (inSessions != null) { var leastBusy = Agents.SingleOrDefault(x => x.Key == inSessions.FirstOrDefault().AgentUserName); var agent = leastBusy.Value; var visitor = new User { ConnectionID = Context.ConnectionId, UserName = HttpContext.Current.User.Identity.Name, FullName = getFullName(), }; ChatSessions.TryAdd(visitor, agent); //Notify the agent about the new chat request Clients.Client(agent.ConnectionID).newChat(visitor.ConnectionID, visitor.FullName); var agentMessage = string.Format("You are now chatting with {0}", visitor.FullName); var visitorMessage = string.Format("You are now chatting with {0}", agent.FullName); Clients.Client(agent.ConnectionID).addMessage(FROM_ADMIN, agentMessage, Context.ConnectionId); Clients.Caller.addMessage(FROM_ADMIN, visitorMessage); } }