using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; using Now.Business; using Now.Entities; using Now.Web.Tickers; namespace Now.Web.Hubs { public class DcPickingTimeStatisticsHub : Hub { private static readonly ConcurrentDictionary _groupMembers = new ConcurrentDictionary(); private readonly static ConnectionMapping _connections = new ConnectionMapping(); public DcPickingTimeStatisticsHub() : this(DcPickingTimeStatisticsTicker.Instance) { } public DcPickingTimeStatisticsHub(DcPickingTimeStatisticsTicker consolidationsTicker) { } internal static string[] GetGroups() { try { return _groupMembers.Values.GroupBy(g => g).Select(country => country.Key).ToArray(); } catch { return null; } } public void JoinBroadcastingGroup(string groupName) { var group = string.IsNullOrEmpty(groupName) ? "All_week" : groupName; if (_groupMembers.ContainsKey(Context.ConnectionId)) { string previousGroup; if (_groupMembers.TryGetValue(Context.ConnectionId, out previousGroup) && group != previousGroup) { Groups.Remove(Context.ConnectionId, previousGroup); _groupMembers.TryRemove(Context.ConnectionId, out previousGroup); } } Groups.Add(Context.ConnectionId, group); _groupMembers.TryAdd(Context.ConnectionId, group); } public override Task OnConnected() { string name = Context.User.Identity.Name; var lc = Context.QueryString["locationCode"]; var locationCode = string.IsNullOrEmpty(lc) ? "ALL" : lc; var interval = string.IsNullOrEmpty(Context.QueryString["interval"]) ? "week" : Context.QueryString["interval"]; JoinBroadcastingGroup(locationCode + "_" + interval); _connections.Add(name, Context.ConnectionId); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { if (Context.User != null) { string name = Context.User.Identity.Name; _connections.Remove(name, Context.ConnectionId); } string country; _groupMembers.TryRemove(Context.ConnectionId, out country); return base.OnDisconnected(stopCalled); } public override Task OnReconnected() { string name = Context.User.Identity.Name; if (!_connections.GetConnections(name).Contains(Context.ConnectionId)) { _connections.Add(name, Context.ConnectionId); } return base.OnReconnected(); } } }