public static async Task <ConnectionStatus> UserCancelInteraction(string noticeHubId, string hubId, string peerId, string userId, string connectId, string languages)
        {
            var cntx = Cntx;
            MemberCallbackServiceProxy mbcsvc = new MemberCallbackServiceProxy();
            ConnectionStatus           status = new ConnectionStatus();
            var notifier = await mbcsvc.LoadEntityByKeyAsync(cntx, "System", noticeHubId, AppId, peerId);

            if (notifier != null && notifier.ConnectionID != null && !notifier.IsDisconnected)
            {
                status.peerNotifier = notifier;
                status.status       = PeerStatus.Notifiable;
            }
            UserServiceProxy usvc = new UserServiceProxy();
            var u = await usvc.LoadEntityByKeyAsync(cntx, userId);

            var mbsvc  = new UserAppMemberServiceProxy();
            var peerMb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, peerId);

            MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy();
            var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, 3);

            var peerCb = await mbcsvc.LoadEntityByKeyAsync(cntx, userId, hubId, AppId, peerId);

            string title = string.Format(ResourceUtils.GetString("cdc8520b5121c757e6eb79e098d6baef", "{0} cancelled chatting invitation.", peerMb.AcceptLanguages), u.Username);

            if (peerCb == null || peerCb.ConnectionID == null || peerCb.IsDisconnected)
            {
                MemberNotification n = new MemberNotification
                {
                    ID            = Guid.NewGuid().ToString(),
                    Title         = title,
                    CreatedDate   = DateTime.UtcNow,
                    PriorityLevel = 0,
                    ReadCount     = 0,
                    ApplicationID = AppId,
                    TypeID        = 3,
                    UserID        = peerId
                };
                n.NoticeMsg          = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + title + "\", \"isCancel\": true, \"isDisconnect\": false }";
                n.IsNoticeDataLoaded = true;
                MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
                var r = await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), new MemberNotification[] { n });

                status.noticeType  = ntype.TypeName;
                status.noticeMsg   = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + title + "\", \"isCancel\": true, \"isDisconnect\": false }";
                status.noticeRecId = r.ChangedEntities[0].UpdatedItem.ID;
            }
            else
            {
                status.noticeMsg = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + title + "\", \"isCancel\": true, \"isDisconnect\": true }";
            }
            status.peer = peerCb;
            return(status);
        }
        public static async Task <MemberCallback[]> ListConnectIds(string hubId, string groupId, bool direct = false)
        {
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
            var cntx = Cntx;

            cntx.DirectDataAccess = direct;
            var qexpr = getConnectedGroupMemberFilter(hubId, groupId);
            var peers = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToList();

            await _listSupervisors(hubId, groupId, peers);

            return(peers.ToArray());
        }
        private static async Task _groupMembersRecurs(string hubId, CallContext cntx, EntityAbs <UserGroup> g, List <MemberCallback> callbacks, bool drillDown = false)
        {
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
            var qexpr = getConnectedGroupMemberFilter(hubId, g.DataBehind.ID);
            var list  = await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr);

            if (list.Count() > 0)
            {
                callbacks.AddRange(list);
            }
            if (drillDown && g.ChildEntities != null)
            {
                foreach (var c in g.ChildEntities)
                {
                    await _groupMembersRecurs(hubId, cntx, c, callbacks);
                }
            }
        }
        private static async Task _listSupervisors(string hubId, string groupId, List <MemberCallback> list)
        {
            var cntx = Cntx;
            UserGroupServiceProxy      gsvc = new UserGroupServiceProxy();
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
            var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);

            while (g.ParentID != null)
            {
                g = await gsvc.MaterializeUpperRefAsync(cntx, g);

                var qexpr = getConnectedGroupMemberFilter(hubId, g.ID, true);
                var peers = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
                if (peers.Length > 0)
                {
                    list.AddRange(peers);
                }
            }
        }
        public static async Task <string[]> ListConnectedMembers(string hubId, string groupId)
        {
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
            var           cntx      = Cntx;
            var           qexpr     = getConnectedGroupMemberFilter(hubId, groupId);
            var           peers     = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
            List <string> jsonPeers = new List <string>();

            if (peers.Length > 0)
            {
                for (int i = 0; i < peers.Length; i++)
                {
                    // retrieve the related entity graph
                    peers[i] = await cbsv.LoadEntityGraphRecursAsync(cntx, groupId, hubId, AppId, peers[i].UserID, null, null);

                    jsonPeers.Add(GetJsonPeer(peers[i]));
                }
            }
            return(jsonPeers.ToArray());
        }
        public static async Task <MemberCallback> FindPeer(string chatHubId, string userId, string peerId)
        {
            var cntx = Cntx;
            MembershipPlusServiceProxy svc = new MembershipPlusServiceProxy();
            DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);
            MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
            var qexpr = new QueryExpresion();

            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UserID"
                },
                new QToken {
                    TkName = "asc"
                }
            });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "HubID == \"" + chatHubId + "\" && ChannelID == \"" + userId + "\" && ConnectionID is not null && IsDisconnected == false"
                },
                new QToken {
                    TkName = "&&"
                },
                new QToken {
                    TkName = "ApplicationID == \"" + AppId + "\" && UserID == \"" + peerId + "\""
                },
                new QToken {
                    TkName = "&&"
                },
                new QToken {
                    TkName = "UserAppMemberRef.LastActivityDate > " + svc.FormatRepoDateTime(dt)
                }
            });
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();

            return((await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).SingleOrDefault());
        }
        public static async Task <MemberCallback> OnUserDisconnected(string hubId, string connectId)
        {
            if (string.IsNullOrEmpty(connectId))
            {
                return(null);
            }
            var cntx = Cntx;
            MemberCallbackServiceProxy cbksvc = new MemberCallbackServiceProxy();
            QueryExpresion             qexpr  = new QueryExpresion();

            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UserID"
                },
                new QToken {
                    TkName = "asc"
                }
            });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "ApplicationID == \"" + AppId + "\" && HubID == \"" + hubId + "\" && ConnectionID == \"" + connectId + "\""
                }
            });
            var cbk = (await cbksvc.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).FirstOrDefault();

            if (cbk != null)
            {
                // top level entity does not need to set 'StartAutoUpdating' since it is done by the proxy:
                // cbk.StartAutoUpdating = true;
                cbk.ConnectionID   = null;
                cbk.LastActiveDate = DateTime.UtcNow;
                cbk.IsDisconnected = true;
                await cbksvc.AddOrUpdateEntitiesAsync(cntx, new MemberCallbackSet(), new MemberCallback[] { cbk });
            }
            return(cbk);
        }
 public static async Task<MemberCallback> FindPeer(string chatHubId, string userId, string peerId)
 {
     var cntx = Cntx;
     MembershipPlusServiceProxy svc = new MembershipPlusServiceProxy();
     DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);
     MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
     var qexpr = new QueryExpresion();
     qexpr.OrderTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "UserID" },
         new QToken { TkName = "asc" }
     });
     qexpr.FilterTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "HubID == \"" + chatHubId + "\" && ChannelID == \"" + userId + "\" && ConnectionID is not null && IsDisconnected == false" },
         new QToken { TkName = "&&" },
         new QToken { TkName = "ApplicationID == \"" + AppId + "\" && UserID == \"" + peerId + "\"" },
         new QToken { TkName = "&&" },
         new QToken { TkName = "UserAppMemberRef.LastActivityDate > " + svc.FormatRepoDateTime(dt) }
     });
     MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
     return (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).SingleOrDefault();
 }
 public static async Task<PeerShotMessage> UpdateUserMessage(string chatHubId, string userId, string peerId, string msgId, string message)
 {
     var cntx = Cntx;
     UserServiceProxy usvc = new UserServiceProxy();
     var u = await usvc.LoadEntityByKeyAsync(cntx, userId);
     var peer = await usvc.LoadEntityByKeyAsync(cntx, peerId);
     ShortMessageServiceProxy msvc = new ShortMessageServiceProxy();
     PeerShotMessage m = new PeerShotMessage();
     ShortMessage msg = await msvc.LoadEntityByKeyAsync(cntx, msgId);
     if (msg == null || msg.FromID != userId || msg.ToID != peerId)
         return null;
     var now = DateTime.UtcNow;
     msg.MsgText = message;
     msg.LastModified = now;
     var r = await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });
     var _msg = r.ChangedEntities[0].UpdatedItem;
     _msg.User_FromID = u;
     m.msg = GetJsonMessage(_msg, userId, peer, false);
     UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
     var utop = await uasvc.LoadEntityByKeyAsync(cntx, userId, peerId, ApplicationContext.ChatAssocTypeId);
     if (utop != null)
     {
         utop.InteractCount = utop.InteractCount == null ? 1 : utop.InteractCount + 1;
         utop.LastInteract = DateTime.UtcNow;
         await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), new UserAssociation[] { utop });
     }
     MembershipPlusServiceProxy svc = new MembershipPlusServiceProxy();
     DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);
     MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
     var qexpr = new QueryExpresion();
     qexpr.OrderTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "UserID" },
         new QToken { TkName = "asc" }
     });
     qexpr.FilterTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "HubID == \"" + chatHubId + "\" && ChannelID == \"" + userId + "\" && ConnectionID is not null && IsDisconnected == false" },
         new QToken { TkName = "&&" },
         new QToken { TkName = "ApplicationID == \"" + AppId + "\" && UserID == \"" + peerId + "\"" },
         new QToken { TkName = "&&" },
         new QToken { TkName = "UserAppMemberRef.LastActivityDate > " + svc.FormatRepoDateTime(dt) }
     });
     MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
     m.peer = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).SingleOrDefault();
     return m;
 }
 public static async Task<ConnectionStatus> UserCancelInteraction(string noticeHubId, string hubId, string peerId, string userId, string connectId, string languages)
 {
     var cntx = Cntx;
     MemberCallbackServiceProxy mbcsvc = new MemberCallbackServiceProxy();
     ConnectionStatus status = new ConnectionStatus();
     var notifier = await mbcsvc.LoadEntityByKeyAsync(cntx, "System", noticeHubId, AppId, peerId);
     if (notifier != null && notifier.ConnectionID != null && !notifier.IsDisconnected)
     {
         status.peerNotifier = notifier;
         status.status = PeerStatus.Notifiable;
     }
     UserServiceProxy usvc = new UserServiceProxy();
     var u = await usvc.LoadEntityByKeyAsync(cntx, userId);
     var mbsvc = new UserAppMemberServiceProxy();
     var peerMb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, peerId);
     MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy();
     var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, 3);
     var peerCb = await mbcsvc.LoadEntityByKeyAsync(cntx, userId, hubId, AppId, peerId);
     string title = string.Format(ResourceUtils.GetString("cdc8520b5121c757e6eb79e098d6baef", "{0} cancelled chatting invitation.", peerMb.AcceptLanguages), u.Username);
     if (peerCb == null || peerCb.ConnectionID == null || peerCb.IsDisconnected)
     {
         MemberNotification n = new MemberNotification
         {
             ID = Guid.NewGuid().ToString(),
             Title = title,
             CreatedDate = DateTime.UtcNow,
             PriorityLevel = 0,
             ReadCount = 0,
             ApplicationID = AppId,
             TypeID = 3,
             UserID = peerId
         };
         n.NoticeMsg = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + title + "\", \"isCancel\": true, \"isDisconnect\": false }";
         n.IsNoticeDataLoaded = true;
         MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
         var r = await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), new MemberNotification[] { n });
         status.noticeType = ntype.TypeName;
         status.noticeMsg = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + title + "\", \"isCancel\": true, \"isDisconnect\": false }";
         status.noticeRecId = r.ChangedEntities[0].UpdatedItem.ID;
     }
     else
     {
         status.noticeMsg = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + title + "\", \"isCancel\": true, \"isDisconnect\": true }";
     }
     status.peer = peerCb;
     return status;
 }
        public static async Task <ShotMessageNotice> UpdateUserMessage(string noticeHubId, string chatHubId, string userId, string groupId, string msgId, string message)
        {
            var cntx = Cntx;
            UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
            var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);

            ShortMessageServiceProxy msvc = new ShortMessageServiceProxy();
            var msg = await msvc.LoadEntityByKeyAsync(cntx, msgId);

            if (msg == null || msg.FromID != userId)
            {
                return(null);
            }
            if (msg.MsgText == message)
            {
                return(null);
            }
            var now = DateTime.UtcNow;

            msg.MsgTitle     = GetLeadText(message);
            msg.MsgText      = message;
            msg.LastModified = now;
            await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });

            UserServiceProxy usvc = new UserServiceProxy();
            var u = await usvc.LoadEntityByKeyAsync(cntx, userId);

            msg.User_FromID = u;
            UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy();
            var cond = new UserGroupMemberSetConstraints
            {
                UserGroupIDWrap = new ForeignKeyData <string> {
                    KeyValue = groupId
                }
            };
            var qexpr = new QueryExpresion();

            qexpr.OrderTks = new List <QToken>(new QToken[] { new QToken {
                                                                  TkName = "UserID"
                                                              } });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken
                {
                    TkName = "SubscribedTo is not null && SubscribedTo == true"
                }
            });
            var gmbs = await gmsvc.ConstraintQueryAsync(cntx, new UserGroupMemberSet(), cond, qexpr);

            List <MemberNotification>  notices  = new List <MemberNotification>();
            List <MemberCallback>      noteCbks = new List <MemberCallback>();
            MemberCallbackServiceProxy mcbsvc   = new MemberCallbackServiceProxy();
            string noticeMsg = "Group message by " + u.Username + " updated in " + g.DistinctString;
            MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy();
            var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.NewMessageNoticeTypeId);

            foreach (var m in gmbs)
            {
                if (m.ActivityNotification.HasValue && m.ActivityNotification.Value)
                {
                    var cb = await mcbsvc.LoadEntityByKeyAsync(cntx, groupId, noticeHubId, AppId, m.UserID);

                    if (cb.ConnectionID != null && !cb.IsDisconnected)
                    {
                        cb.UserAppMemberRef = await mcbsvc.MaterializeUserAppMemberRefAsync(cntx, cb);

                        noteCbks.Add(cb);
                    }
                }
                notices.Add(new MemberNotification
                {
                    ID            = Guid.NewGuid().ToString(),
                    Title         = noticeMsg,
                    CreatedDate   = now,
                    PriorityLevel = 0,
                    ReadCount     = 0,
                    ApplicationID = AppId,
                    TypeID        = ApplicationContext.NewMessageNoticeTypeId,
                    UserID        = userId
                });
            }
            var peers = await ListConnectIds(chatHubId, groupId);

            List <ShortMessageAudience> laud = new List <ShortMessageAudience>();

            foreach (var peer in peers)
            {
                if (peer.UserID != userId)
                {
                    var a = new ShortMessageAudience
                    {
                        MsgID     = msg.ID,
                        UserID    = peer.UserID,
                        VoteCount = 0
                    };
                    laud.Add(a);
                }
            }
            if (laud.Count > 0)
            {
                ShortMessageAudienceServiceProxy audsvc = new ShortMessageAudienceServiceProxy();
                await audsvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageAudienceSet(), laud.ToArray());
            }
            if (notices.Count > 0)
            {
                MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
                await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), notices.ToArray());
            }
            return(new ShotMessageNotice {
                msg = GetJsonMessage(msg, userId, g, false), brief = noticeMsg, categ = ntype, peers = peers, callbacks = noteCbks
            });
        }
 public static async Task<dynamic> LoadRoomSummary(string hubId, string id)
 {
     UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
     var cntx = Cntx;
     string descr = await gsvc.LoadEntityGroupDescriptionAsync(cntx, id);
     MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
     var qexpr = getConnectedGroupMemberFilter(hubId, id);
     long cnt = await mcbsvc.QueryEntityCountAsync(cntx, new MemberCallbackSet(), qexpr);
     UserGroupMemberServiceProxy uigsvc = new UserGroupMemberServiceProxy();
     qexpr = new QueryExpresion();
     qexpr.OrderTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "UserID" }
     });
     qexpr.FilterTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "UserGroupID == \"" + id + "\" && SubscribedTo is not null && SubscribedTo == true"  }
     });
     long scnt = await uigsvc.QueryEntityCountAsync(cntx, new UserGroupMemberSet(), qexpr);
     qexpr = new QueryExpresion();
     qexpr.OrderTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "Username" }
     });
     qexpr.FilterTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "UsersInRole_UserID.RoleRef.UserGroupAdminRole.GroupID == \"" + id + "\"" }
     });
     UserServiceProxy usvc = new UserServiceProxy();
     var admins = await usvc.QueryDatabaseAsync(cntx, new UserSet(), qexpr);
     List<dynamic> ladms = new List<dynamic>();
     if (admins.Count() > 0)
     {
         RoleServiceProxy rsvc = new RoleServiceProxy();
         foreach (var u in admins)
         {
             qexpr = new QueryExpresion();
             qexpr.OrderTks = new List<QToken>(new QToken[] { 
                 new QToken { TkName = "ID" }
             });
             qexpr.FilterTks = new List<QToken>(new QToken[] { 
                 new QToken { TkName = "UserGroupAdminRole.GroupID == \"" + id + "\" && UsersInRole.UserID == \"" + u.ID + "\"" }
             });
             var role = (await rsvc.QueryDatabaseAsync(cntx, new RoleSet(), qexpr)).First();
             ladms.Add(new { id = u.ID, name = u.Username, role = role.DisplayName });
         }
     }
     dynamic r = new { descr = descr, active = cnt, subscribers = scnt, admins = ladms };
     return r;
 }
 public static async Task<ChatRoomVM> LoadChatRoom(string hubId, string groupId, string userId, int maxMessages, bool dialog = false)
 {
     UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
     var cntx = Cntx;
     ChatRoomVM m = new ChatRoomVM() { RoomExists = false, DialogMode = dialog };
     if (!string.IsNullOrEmpty(groupId))
     {
         var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);
         if (g != null)
         {
             m.RoomExists = true;
             m.ID = groupId;
             m.RoomPath = g.DistinctString.Split('/');
             m.RoomInfo = await gsvc.LoadEntityGroupDescriptionAsync(cntx, g.ID);
             UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy();
             UserGroupMember uig = await gmsvc.LoadEntityByKeyAsync(cntx, groupId, userId);
             if (uig == null)
             {
                 uig = new UserGroupMember
                 {
                     UserID = userId,
                     UserGroupID = groupId,
                     SubscribedTo = false,
                     ActivityNotification = false
                 };
                 await gmsvc.AddOrUpdateEntitiesAsync(cntx, new UserGroupMemberSet(), new UserGroupMember[] { uig });
             }
             cntx.DirectDataAccess = true;
             MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
             var qexpr = getConnectedGroupMemberFilter(hubId, g.ID);
             var peers = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
             List<string> jsonPeers = new List<string>();
             if (peers.Length > 0)
             {
                 for (int i = 0; i < peers.Length; i++)
                 {
                     // retrieve the related entity graph
                     peers[i] = await cbsv.LoadEntityGraphRecursAsync(cntx, groupId, hubId, AppId, peers[i].UserID, null, null);
                     jsonPeers.Add(GetJsonPeer(peers[i]));
                 }
             }
             m.ActivePeers = jsonPeers.ToArray();
             cntx.DirectDataAccess = false;
             ShortMessageServiceProxy msgsvc = new ShortMessageServiceProxy();
             var cond = new ShortMessageSetConstraints
             {
                 ApplicationIDWrap = new ForeignKeyData<string> { KeyValue = AppId },
                 TypeIDWrap = new ForeignKeyData<int> { KeyValue = ApplicationContext.ChatShortMsgTypeId },
                 GroupIDWrap = new ForeignKeyData<string> { KeyValue = groupId }
             };
             UserGroupMemberServiceProxy uigsvc = new UserGroupMemberServiceProxy();
             qexpr = new QueryExpresion();
             qexpr.OrderTks = new List<QToken>(new QToken[] { 
                 new QToken { TkName = "UserID" }
             });
             qexpr.FilterTks = new List<QToken>(new QToken[] { 
                 new QToken { TkName = "UserGroupID == \"" + g.ID + "\" && SubscribedTo is not null && SubscribedTo == true"  }
             });
             m.Subscribers = (int)(await uigsvc.QueryEntityCountAsync(cntx, new UserGroupMemberSet(), qexpr));
             var svc = new MembershipPlusServiceProxy();
             DateTime dt = DateTime.UtcNow.AddMinutes(-InitMsgTimeWindow);
             qexpr = new QueryExpresion();
             qexpr.OrderTks = new List<QToken>(new QToken[] { 
                 new QToken { TkName = "CreatedDate" },
                 new QToken { TkName = "desc" }
             });
             qexpr.FilterTks = new List<QToken>(new QToken[] {
                 new QToken { TkName = "ToID is null && CreatedDate > " + svc.FormatRepoDateTime(dt) }
             });
             if (dialog)
             {
                 qexpr.FilterTks.Add(new QToken { TkName = " && ReplyToID is null" });
             }
             var msgs = (await msgsvc.ConstraintQueryLimitedAsync(cntx, new ShortMessageSet(), cond, qexpr, maxMessages)).ToArray();
             List<string> jsonMsgs = new List<string>();
             if (msgs.Length > 0)
             {
                 for (int i = msgs.Length - 1; i >= 0; i--)
                 {
                     EntitySetType[] excludes;
                     if (dialog)
                     {
                         excludes = new EntitySetType[]
                         {
                             EntitySetType.UserGroup,
                             //EntitySetType.ShortMessageAudience,
                             EntitySetType.ShortMessageAttachment
                         };
                     }
                     else
                     {
                         excludes = new EntitySetType[]
                         {
                             EntitySetType.UserGroup,
                             //EntitySetType.ShortMessageAudience,
                             EntitySetType.ShortMessageAttachment,
                             EntitySetType.ShortMessage
                         };
                     }
                     msgs[i] = await msgsvc.LoadEntityGraphRecursAsync(cntx, msgs[i].ID, excludes, null);
                     jsonMsgs.Add(GetJsonMessage(msgs[i], userId, g, dialog));
                 }
             }
             m.RecentMsgs = jsonMsgs.ToArray();
         }
     }
     return m;
 }
        public static async Task <string> GetMembers(string nhubId, string userId, string set, string qexpr, string prevlast, bool outgoing)
        {
            JavaScriptSerializer jser = new JavaScriptSerializer();
            dynamic sobj = jser.DeserializeObject(set) as dynamic;
            DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion));
            DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(User));
            var ser3 = new JavaScriptSerializer();

            System.IO.MemoryStream strm = new System.IO.MemoryStream();
            byte[] sbf = System.Text.Encoding.UTF8.GetBytes(qexpr);
            strm.Write(sbf, 0, sbf.Length);
            strm.Position = 0;
            var _qexpr            = ser1.ReadObject(strm) as QueryExpresion;
            UserServiceProxy svc  = new UserServiceProxy();
            UserSet          _set = new UserSet();

            _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]);
            _set.PageSize_     = int.Parse(sobj["pageSize"]);
            if (sobj.ContainsKey("setFilter"))
            {
                _set.SetFilter = sobj["setFilter"];
            }
            User _prevlast = null;

            if (!string.IsNullOrEmpty(prevlast))
            {
                strm = new System.IO.MemoryStream();
                sbf  = System.Text.Encoding.UTF8.GetBytes(prevlast);
                strm.Write(sbf, 0, sbf.Length);
                strm.Position = 0;
                _prevlast     = ser2.ReadObject(strm) as User;
            }
            var cntx   = Cntx;
            var result = await svc.GetPageItemsAsync(cntx, _set, _qexpr, _prevlast);

            var    ar    = new List <dynamic>();
            string appId = ApplicationContext.App.ID;
            UserAppMemberServiceProxy   mbsvc = new UserAppMemberServiceProxy();
            MemberCallbackServiceProxy  cbsvc = new MemberCallbackServiceProxy();
            UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
            DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);

            foreach (var e in result)
            {
                var cond = new UserAppMemberSetConstraints
                {
                    ApplicationIDWrap = new ForeignKeyData <string> {
                        KeyValue = appId
                    },
                    UserIDWrap = new ForeignKeyData <string> {
                        KeyValue = e.ID
                    }
                };
                var  memb = (await mbsvc.ConstraintQueryAsync(cntx, new UserAppMemberSet(), cond, null)).SingleOrDefault();
                bool notify;
                if (outgoing)
                {
                    var notifier = await cbsvc.LoadEntityByKeyAsync(cntx, "System", nhubId, appId, e.ID);

                    notify = memb.LastActivityDate > dt && notifier != null && notifier.ConnectionID != null && !notifier.IsDisconnected;
                }
                else
                {
                    notify = false;
                }
                var cond2 = new UserAssociationSetConstraints();
                if (!outgoing)
                {
                    cond2.FromUserIDWrap = new ForeignKeyData <string> {
                        KeyValue = userId
                    };
                    cond2.ToUserIDWrap = new ForeignKeyData <string> {
                        KeyValue = e.ID
                    };
                    cond2.TypeIDWrap = null;
                }
                else
                {
                    cond2.FromUserIDWrap = new ForeignKeyData <string> {
                        KeyValue = e.ID
                    };
                    cond2.ToUserIDWrap = new ForeignKeyData <string> {
                        KeyValue = userId
                    };
                    cond2.TypeIDWrap = null;
                }
                var assocs = await uasvc.ConstraintQueryAsync(cntx, new UserAssociationSet(), cond2, null);

                var a = new
                {
                    data    = e,
                    member  = memb,
                    hasIcon = memb != null && !string.IsNullOrEmpty(memb.IconMime),
                    notify  = notify,
                    types   = new List <int>()
                };
                foreach (var assoc in assocs)
                {
                    a.types.Add(assoc.TypeID);
                }
                ar.Add(a);
            }
            string json = ser3.Serialize(ar);

            return(json);
        }
 public static async Task<string[]> ListConnectedMembers(string hubId, string groupId)
 {
     MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
     var cntx = Cntx;
     var qexpr = getConnectedGroupMemberFilter(hubId, groupId);
     var peers = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
     List<string> jsonPeers = new List<string>();
     if (peers.Length > 0)
     {
         for (int i = 0; i < peers.Length; i++)
         {
             // retrieve the related entity graph
             peers[i] = await cbsv.LoadEntityGraphRecursAsync(cntx, groupId, hubId, AppId, peers[i].UserID, null, null);
             jsonPeers.Add(GetJsonPeer(peers[i]));
         }
     }
     return jsonPeers.ToArray();
 }
 public static async Task<ConnectionStatus> UserConnected(string noticeHubId, string hubId, string peerId, string userId, string connectId, string languages)
 {
     var mbsvc = new UserAppMemberServiceProxy();
     var cntx = Cntx;
     cntx.AcceptLanguages = languages;
     var memb = await mbsvc.LoadEntityGraphRecursAsync(cntx, AppId, userId, null, null);
     if (memb != null)
     {
         memb.StartAutoUpdating = true;
         memb.LastActivityDate = DateTime.UtcNow;
         memb.AcceptLanguages = languages;
         List<MemberCallback> callbacks;
         if (memb.ChangedMemberCallbacks == null)
             callbacks = new List<MemberCallback>();
         else
             callbacks = new List<MemberCallback>(memb.ChangedMemberCallbacks);
         var cbk = (from d in callbacks where d.HubID == hubId && d.ChannelID == peerId select d).SingleOrDefault();
         if (cbk == null)
         {
             cbk = new MemberCallback
             {
                 ApplicationID = AppId,
                 UserID = userId,
                 HubID = hubId,
                 ChannelID = peerId,
                 ConnectionID = connectId,
                 IsDisconnected = false,
                 LastActiveDate = DateTime.UtcNow
             };
         }
         else
         {
             // it is very important to turn this on, otherwise the property will not be marked as modified.
             // and the service will not save the change!
             cbk.StartAutoUpdating = true;
             cbk.ConnectionID = connectId;
             cbk.IsDisconnected = false;
             cbk.LastActiveDate = DateTime.UtcNow;
         }
         memb.ChangedMemberCallbacks = new MemberCallback[] { cbk };
         await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { memb });
         UserServiceProxy usvc = new UserServiceProxy();
         var u = await usvc.LoadEntityByKeyAsync(cntx, userId);
         memb.UserRef = u;
         var peerMb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, peerId);
         ConnectionStatus status = new ConnectionStatus();
         status.me = cbk;
         MemberCallbackServiceProxy mbcsvc = new MemberCallbackServiceProxy();
         UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
         var peerCb = await mbcsvc.LoadEntityByKeyAsync(cntx, userId, hubId, AppId, peerId);
         if (peerCb == null || peerCb.ConnectionID == null || peerCb.IsDisconnected)
         {
             UserAssociation utop = await uasvc.LoadEntityByKeyAsync(cntx, userId, peerId, ApplicationContext.ChatAssocTypeId);
             MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy();
             var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.PrivateChatNoticeTypeId);
             var notifier = await mbcsvc.LoadEntityByKeyAsync(cntx, "System", noticeHubId, AppId, peerId);
             if (notifier != null && notifier.ConnectionID != null && !notifier.IsDisconnected)
             {
                 if (utop != null && utop.NoMessages != null && utop.NoMessages == true)
                 {
                     status.status = PeerStatus.InBlackList;
                 }
                 else if (utop != null && utop.DoNotNotify != null && utop.DoNotNotify == true)
                 {
                     status.status = PeerStatus.DoNotDisturb;
                 }
                 else if (utop != null && utop.NotifyButBlock != null && utop.NotifyButBlock == true)
                 {
                     status.peerNotifier = notifier;
                     status.status = PeerStatus.NotifyButBlock;
                 }
                 else
                 {
                     status.peerNotifier = notifier;
                     status.status = PeerStatus.Notifiable;
                 }
             }
             else
             {
                 if (utop == null || utop.NoMessages == null || utop.NoMessages == false)
                     status.status = PeerStatus.LeaveMessage;
             }
             MemberNotification n = new MemberNotification 
             {
                 ID = Guid.NewGuid().ToString(),
                 Title = string.Format(ResourceUtils.GetString("20dc5913998d0e9ed01360475e46a0f9", "{0} invites you to chat, is waiting ...", peerMb.AcceptLanguages), ""),
                 CreatedDate = DateTime.UtcNow,
                 PriorityLevel = 0,
                 ReadCount = 0,
                 ApplicationID = AppId,
                 TypeID = ApplicationContext.PrivateChatNoticeTypeId,
                 UserID = peerId
             };
             bool hasIcon = !string.IsNullOrEmpty(memb.IconMime);
             n.NoticeMsg = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"hasIcon\": " + (hasIcon ? "true" : "false") + ", \"msg\": \"" + n.Title + "\", \"isCancel\": false, ";
             if (utop != null && utop.NoMessages != null && utop.NoMessages == true)
                 n.NoticeMsg += "\"noMessages\": true, ";
             else
                 n.NoticeMsg += "\"noMessages\": false, ";
             if (utop != null && utop.DoNotNotify != null && utop.DoNotNotify == true)
                 n.NoticeMsg += "\"notDisturb\": true, ";
             else
                 n.NoticeMsg += "\"notDisturb\": false, ";
             if (utop != null && utop.NotifyButBlock != null && utop.NotifyButBlock == true)
                 n.NoticeMsg += "\"keepNotified\": true }";
             else
                 n.NoticeMsg += "\"keepNotified\": false }";
             n.IsNoticeDataLoaded = true;
             MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
             var r = await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), new MemberNotification[] { n });
             status.noticeType = ntype.TypeName;
             status.noticeMsg = n.NoticeMsg;
             status.noticeRecId = r.ChangedEntities[0].UpdatedItem.ID;
         }
         else
         {
             DateTime dt = DateTime.UtcNow;
             UserAssociation utop = await uasvc.LoadEntityByKeyAsync(cntx, userId, peerId, ApplicationContext.ChatAssocTypeId);
             if (utop == null)
             {
                 utop = new UserAssociation
                 {
                     TypeID = ApplicationContext.ChatAssocTypeId,
                     FromUserID = userId,
                     ToUserID = peerId,
                     CreateDate = dt,
                     AssocCount = 1,
                     LastAssoc = dt,
                     InteractCount = 0,
                     Votes = 0
                 };
             }
             else
                 utop.AssocCount++;
             UserAssociation ptou = await uasvc.LoadEntityByKeyAsync(cntx, peerId, userId, ApplicationContext.ChatAssocTypeId);
             if (ptou == null)
             {
                 ptou = new UserAssociation
                 {
                     TypeID = ApplicationContext.ChatAssocTypeId,
                     FromUserID = peerId,
                     ToUserID = userId,
                     CreateDate = dt,
                     AssocCount = 1,
                     LastAssoc = dt,
                     InteractCount = 0,
                     Votes = 0
                 };
             }
             else
                 ptou.AssocCount++;
             await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), new UserAssociation[] { utop, ptou });
             status.status = PeerStatus.Connected;
         }
         if (peerCb != null)
             peerCb.UserAppMemberRef = peerMb;
         status.peer = peerCb;
         return status;
     }
     return null;
 }
 private static async Task _groupMembersRecurs(string hubId, CallContext cntx, EntityAbs<UserGroup> g, List<MemberCallback> callbacks, bool drillDown = false)
 {
     MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
     var qexpr = getConnectedGroupMemberFilter(hubId, g.DataBehind.ID);
     var list = await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr);
     if (list.Count() > 0)
     {
         callbacks.AddRange(list);
     }
     if (drillDown && g.ChildEntities != null)
     {
         foreach (var c in g.ChildEntities)
             await _groupMembersRecurs(hubId, cntx, c, callbacks);
     }
 }
 public static async Task<ShotMessageNotice> UpdateUserMessage(string noticeHubId, string chatHubId, string userId, string groupId, string msgId, string message)
 {
     var cntx = Cntx;
     UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
     var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);
     ShortMessageServiceProxy msvc = new ShortMessageServiceProxy();
     var msg = await msvc.LoadEntityByKeyAsync(cntx, msgId);
     if (msg == null || msg.FromID != userId)
         return null;
     if (msg.MsgText == message)
         return null;
     var now = DateTime.UtcNow;
     msg.MsgTitle = GetLeadText(message);
     msg.MsgText = message;
     msg.LastModified = now;
     await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });
     UserServiceProxy usvc = new UserServiceProxy();
     var u = await usvc.LoadEntityByKeyAsync(cntx, userId);
     msg.User_FromID = u;
     UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy();
     var cond = new UserGroupMemberSetConstraints
     {
         UserGroupIDWrap = new ForeignKeyData<string> { KeyValue = groupId }
     };
     var qexpr = new QueryExpresion();
     qexpr.OrderTks = new List<QToken>(new QToken[] { new QToken { TkName = "UserID" } });
     qexpr.FilterTks = new List<QToken>(new QToken[] {
         new QToken 
         {
             TkName = "SubscribedTo is not null && SubscribedTo == true"
         }
     });
     var gmbs = await gmsvc.ConstraintQueryAsync(cntx, new UserGroupMemberSet(), cond, qexpr);
     List<MemberNotification> notices = new List<MemberNotification>();
     List<MemberCallback> noteCbks = new List<MemberCallback>();
     MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
     string noticeMsg = "Group message by " + u.Username + " updated in " + g.DistinctString;
     MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy();
     var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.NewMessageNoticeTypeId);
     foreach (var m in gmbs)
     {
         if (m.ActivityNotification.HasValue && m.ActivityNotification.Value)
         {
             var cb = await mcbsvc.LoadEntityByKeyAsync(cntx, groupId, noticeHubId, AppId, m.UserID);
             if (cb.ConnectionID != null && !cb.IsDisconnected)
             {
                 cb.UserAppMemberRef = await mcbsvc.MaterializeUserAppMemberRefAsync(cntx, cb);
                 noteCbks.Add(cb);
             }
         }
         notices.Add(new MemberNotification
         {
             ID = Guid.NewGuid().ToString(),
             Title = noticeMsg,
             CreatedDate = now,
             PriorityLevel = 0,
             ReadCount = 0,
             ApplicationID = AppId,
             TypeID = ApplicationContext.NewMessageNoticeTypeId,
             UserID = userId
         });
     }
     var peers = await ListConnectIds(chatHubId, groupId);
     List<ShortMessageAudience> laud = new List<ShortMessageAudience>();
     foreach (var peer in peers)
     {
         if (peer.UserID != userId)
         {
             var a = new ShortMessageAudience
             {
                 MsgID = msg.ID,
                 UserID = peer.UserID,
                 VoteCount = 0
             };
             laud.Add(a);
         }
     }
     if (laud.Count > 0)
     {
         ShortMessageAudienceServiceProxy audsvc = new ShortMessageAudienceServiceProxy();
         await audsvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageAudienceSet(), laud.ToArray());
     }
     if (notices.Count > 0)
     {
         MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
         await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), notices.ToArray());
     }
     return new ShotMessageNotice { msg = GetJsonMessage(msg, userId, g, false), brief = noticeMsg, categ = ntype, peers = peers, callbacks = noteCbks };
 }
 private static async Task _listSupervisors(string hubId, string groupId, List<MemberCallback> list)
 {
     var cntx = Cntx;
     UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
     MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
     var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);
     while (g.ParentID != null)
     {
         g = await gsvc.MaterializeUpperRefAsync(cntx, g);
         var qexpr = getConnectedGroupMemberFilter(hubId, g.ID, true);
         var peers = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
         if (peers.Length > 0)
             list.AddRange(peers);
     }
 }
 public static async Task<MemberCallback[]> ListConnectIds(string hubId, string groupId, bool direct = false)
 {
     MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
     var cntx = Cntx;
     cntx.DirectDataAccess = direct;
     var qexpr = getConnectedGroupMemberFilter(hubId, groupId);
     var peers = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToList();
     await _listSupervisors(hubId, groupId, peers);
     return peers.ToArray();
 }
 public static async Task<string> GetMembers(string nhubId, string userId, string set, string qexpr, string prevlast, bool outgoing)
 {
     JavaScriptSerializer jser = new JavaScriptSerializer();
     dynamic sobj = jser.DeserializeObject(set) as dynamic;
     DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion));
     DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(User));
     var ser3 = new JavaScriptSerializer();
     System.IO.MemoryStream strm = new System.IO.MemoryStream();
     byte[] sbf = System.Text.Encoding.UTF8.GetBytes(qexpr);
     strm.Write(sbf, 0, sbf.Length);
     strm.Position = 0;
     var _qexpr = ser1.ReadObject(strm) as QueryExpresion;
     UserServiceProxy svc = new UserServiceProxy();
     UserSet _set = new UserSet();
     _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]);
     _set.PageSize_ = int.Parse(sobj["pageSize"]);
     if (sobj.ContainsKey("setFilter"))
         _set.SetFilter = sobj["setFilter"];
     User _prevlast = null;
     if (!string.IsNullOrEmpty(prevlast))
     {
         strm = new System.IO.MemoryStream();
         sbf = System.Text.Encoding.UTF8.GetBytes(prevlast);
         strm.Write(sbf, 0, sbf.Length);
         strm.Position = 0;
         _prevlast = ser2.ReadObject(strm) as User;
     }
     var cntx = Cntx;
     var result = await svc.GetPageItemsAsync(cntx, _set, _qexpr, _prevlast);
     var ar = new List<dynamic>();
     string appId = ApplicationContext.App.ID;
     UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
     MemberCallbackServiceProxy cbsvc = new MemberCallbackServiceProxy();
     UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
     DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);
     foreach (var e in result)
     {
         var cond = new UserAppMemberSetConstraints
         {
             ApplicationIDWrap = new ForeignKeyData<string> { KeyValue = appId },
             UserIDWrap = new ForeignKeyData<string> { KeyValue = e.ID }
         };
         var memb = (await mbsvc.ConstraintQueryAsync(cntx, new UserAppMemberSet(), cond, null)).SingleOrDefault();
         bool notify;
         if (outgoing)
         {
             var notifier = await cbsvc.LoadEntityByKeyAsync(cntx, "System", nhubId, appId, e.ID);
             notify = memb.LastActivityDate > dt && notifier != null && notifier.ConnectionID != null && !notifier.IsDisconnected;
         }
         else
             notify = false;
         var cond2 = new UserAssociationSetConstraints();
         if (!outgoing)
         {
            cond2.FromUserIDWrap = new ForeignKeyData<string> { KeyValue = userId };
            cond2.ToUserIDWrap = new ForeignKeyData<string> { KeyValue = e.ID };
            cond2.TypeIDWrap = null;
         }
         else
         {
             cond2.FromUserIDWrap = new ForeignKeyData<string> { KeyValue = e.ID };
             cond2.ToUserIDWrap = new ForeignKeyData<string> { KeyValue = userId };
             cond2.TypeIDWrap = null;
         }
         var assocs = await uasvc.ConstraintQueryAsync(cntx, new UserAssociationSet(), cond2, null);
         var a = new
         {
             data = e,
             member = memb,
             hasIcon = memb != null && !string.IsNullOrEmpty(memb.IconMime),
             notify = notify,
             types = new List<int>()
         };
         foreach (var assoc in assocs)
             a.types.Add(assoc.TypeID);
         ar.Add(a);
     }
     string json = ser3.Serialize(ar);
     return json;
 }
        public static async Task <dynamic> LoadRoomSummary(string hubId, string id)
        {
            UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
            var    cntx  = Cntx;
            string descr = await gsvc.LoadEntityGroupDescriptionAsync(cntx, id);

            MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
            var  qexpr = getConnectedGroupMemberFilter(hubId, id);
            long cnt   = await mcbsvc.QueryEntityCountAsync(cntx, new MemberCallbackSet(), qexpr);

            UserGroupMemberServiceProxy uigsvc = new UserGroupMemberServiceProxy();

            qexpr          = new QueryExpresion();
            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UserID"
                }
            });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UserGroupID == \"" + id + "\" && SubscribedTo is not null && SubscribedTo == true"
                }
            });
            long scnt = await uigsvc.QueryEntityCountAsync(cntx, new UserGroupMemberSet(), qexpr);

            qexpr          = new QueryExpresion();
            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "Username"
                }
            });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UsersInRole_UserID.RoleRef.UserGroupAdminRole.GroupID == \"" + id + "\""
                }
            });
            UserServiceProxy usvc = new UserServiceProxy();
            var admins            = await usvc.QueryDatabaseAsync(cntx, new UserSet(), qexpr);

            List <dynamic> ladms = new List <dynamic>();

            if (admins.Count() > 0)
            {
                RoleServiceProxy rsvc = new RoleServiceProxy();
                foreach (var u in admins)
                {
                    qexpr          = new QueryExpresion();
                    qexpr.OrderTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "ID"
                        }
                    });
                    qexpr.FilterTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "UserGroupAdminRole.GroupID == \"" + id + "\" && UsersInRole.UserID == \"" + u.ID + "\""
                        }
                    });
                    var role = (await rsvc.QueryDatabaseAsync(cntx, new RoleSet(), qexpr)).First();
                    ladms.Add(new { id = u.ID, name = u.Username, role = role.DisplayName });
                }
            }
            dynamic r = new { descr = descr, active = cnt, subscribers = scnt, admins = ladms };

            return(r);
        }
        public static async Task <PeerShotMessage> AddUserMessage(string chatHubId, string userId, string peerId, string replyId, string message, bool record)
        {
            var cntx = Cntx;
            UserServiceProxy usvc = new UserServiceProxy();
            var u = await usvc.LoadEntityByKeyAsync(cntx, userId);

            var peer = await usvc.LoadEntityByKeyAsync(cntx, peerId);

            ShortMessageServiceProxy msvc = new ShortMessageServiceProxy();
            PeerShotMessage          m    = new PeerShotMessage();
            var          now = DateTime.UtcNow;
            ShortMessage msg = new ShortMessage
            {
                ID            = Guid.NewGuid().ToString(),
                ApplicationID = AppId,
                TypeID        = 1,
                GroupID       = null,
                FromID        = userId,
                ToID          = peerId,
                ReplyToID     = string.IsNullOrEmpty(replyId) ? null : replyId,
                CreatedDate   = now,
                LastModified  = now,
                MsgText       = message
            };

            if (record)
            {
                var r = await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });

                var _msg = r.ChangedEntities[0].UpdatedItem;
                _msg.User_FromID = u;
                m.msg            = GetJsonMessage(_msg, userId, peer, false);
            }
            else
            {
                msg.User_FromID = u;
                m.msg           = GetJsonMessage(msg, userId, peer, false);
            }
            UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
            var utop = await uasvc.LoadEntityByKeyAsync(cntx, userId, peerId, ApplicationContext.ChatAssocTypeId);

            if (utop != null)
            {
                utop.InteractCount = utop.InteractCount == null ? 1 : utop.InteractCount + 1;
                utop.LastInteract  = DateTime.UtcNow;
                await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), new UserAssociation[] { utop });
            }
            MembershipPlusServiceProxy svc = new MembershipPlusServiceProxy();
            DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);
            MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
            var qexpr = new QueryExpresion();

            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UserID"
                },
                new QToken {
                    TkName = "asc"
                }
            });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "HubID == \"" + chatHubId + "\" && ChannelID == \"" + userId + "\" && ConnectionID is not null && IsDisconnected == false"
                },
                new QToken {
                    TkName = "&&"
                },
                new QToken {
                    TkName = "ApplicationID == \"" + AppId + "\" && UserID == \"" + peerId + "\""
                },
                new QToken {
                    TkName = "&&"
                },
                new QToken {
                    TkName = "UserAppMemberRef.LastActivityDate > " + svc.FormatRepoDateTime(dt)
                }
            });
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();

            m.peer = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).SingleOrDefault();
            return(m);
        }
        public static async Task <ChatRoomVM> LoadChatRoom(string hubId, string groupId, string userId, int maxMessages, bool dialog = false)
        {
            UserGroupServiceProxy gsvc = new UserGroupServiceProxy();
            var        cntx            = Cntx;
            ChatRoomVM m = new ChatRoomVM()
            {
                RoomExists = false, DialogMode = dialog
            };

            if (!string.IsNullOrEmpty(groupId))
            {
                var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId);

                if (g != null)
                {
                    m.RoomExists = true;
                    m.ID         = groupId;
                    m.RoomPath   = g.DistinctString.Split('/');
                    m.RoomInfo   = await gsvc.LoadEntityGroupDescriptionAsync(cntx, g.ID);

                    UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy();
                    UserGroupMember             uig   = await gmsvc.LoadEntityByKeyAsync(cntx, groupId, userId);

                    if (uig == null)
                    {
                        uig = new UserGroupMember
                        {
                            UserID               = userId,
                            UserGroupID          = groupId,
                            SubscribedTo         = false,
                            ActivityNotification = false
                        };
                        await gmsvc.AddOrUpdateEntitiesAsync(cntx, new UserGroupMemberSet(), new UserGroupMember[] { uig });
                    }
                    cntx.DirectDataAccess = true;
                    MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();
                    var           qexpr             = getConnectedGroupMemberFilter(hubId, g.ID);
                    var           peers             = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).ToArray();
                    List <string> jsonPeers         = new List <string>();
                    if (peers.Length > 0)
                    {
                        for (int i = 0; i < peers.Length; i++)
                        {
                            // retrieve the related entity graph
                            peers[i] = await cbsv.LoadEntityGraphRecursAsync(cntx, groupId, hubId, AppId, peers[i].UserID, null, null);

                            jsonPeers.Add(GetJsonPeer(peers[i]));
                        }
                    }
                    m.ActivePeers         = jsonPeers.ToArray();
                    cntx.DirectDataAccess = false;
                    ShortMessageServiceProxy msgsvc = new ShortMessageServiceProxy();
                    var cond = new ShortMessageSetConstraints
                    {
                        ApplicationIDWrap = new ForeignKeyData <string> {
                            KeyValue = AppId
                        },
                        TypeIDWrap = new ForeignKeyData <int> {
                            KeyValue = ApplicationContext.ChatShortMsgTypeId
                        },
                        GroupIDWrap = new ForeignKeyData <string> {
                            KeyValue = groupId
                        }
                    };
                    UserGroupMemberServiceProxy uigsvc = new UserGroupMemberServiceProxy();
                    qexpr          = new QueryExpresion();
                    qexpr.OrderTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "UserID"
                        }
                    });
                    qexpr.FilterTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "UserGroupID == \"" + g.ID + "\" && SubscribedTo is not null && SubscribedTo == true"
                        }
                    });
                    m.Subscribers = (int)(await uigsvc.QueryEntityCountAsync(cntx, new UserGroupMemberSet(), qexpr));
                    var      svc = new MembershipPlusServiceProxy();
                    DateTime dt  = DateTime.UtcNow.AddMinutes(-InitMsgTimeWindow);
                    qexpr          = new QueryExpresion();
                    qexpr.OrderTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "CreatedDate"
                        },
                        new QToken {
                            TkName = "desc"
                        }
                    });
                    qexpr.FilterTks = new List <QToken>(new QToken[] {
                        new QToken {
                            TkName = "ToID is null && CreatedDate > " + svc.FormatRepoDateTime(dt)
                        }
                    });
                    if (dialog)
                    {
                        qexpr.FilterTks.Add(new QToken {
                            TkName = " && ReplyToID is null"
                        });
                    }
                    var           msgs     = (await msgsvc.ConstraintQueryLimitedAsync(cntx, new ShortMessageSet(), cond, qexpr, maxMessages)).ToArray();
                    List <string> jsonMsgs = new List <string>();
                    if (msgs.Length > 0)
                    {
                        for (int i = msgs.Length - 1; i >= 0; i--)
                        {
                            EntitySetType[] excludes;
                            if (dialog)
                            {
                                excludes = new EntitySetType[]
                                {
                                    EntitySetType.UserGroup,
                                    //EntitySetType.ShortMessageAudience,
                                    EntitySetType.ShortMessageAttachment
                                };
                            }
                            else
                            {
                                excludes = new EntitySetType[]
                                {
                                    EntitySetType.UserGroup,
                                    //EntitySetType.ShortMessageAudience,
                                    EntitySetType.ShortMessageAttachment,
                                    EntitySetType.ShortMessage
                                };
                            }
                            msgs[i] = await msgsvc.LoadEntityGraphRecursAsync(cntx, msgs[i].ID, excludes, null);

                            jsonMsgs.Add(GetJsonMessage(msgs[i], userId, g, dialog));
                        }
                    }
                    m.RecentMsgs = jsonMsgs.ToArray();
                }
            }
            return(m);
        }
        public static async Task <ConnectionStatus> UserConnected(string noticeHubId, string hubId, string peerId, string userId, string connectId, string languages)
        {
            var mbsvc = new UserAppMemberServiceProxy();
            var cntx  = Cntx;

            cntx.AcceptLanguages = languages;
            var memb = await mbsvc.LoadEntityGraphRecursAsync(cntx, AppId, userId, null, null);

            if (memb != null)
            {
                memb.StartAutoUpdating = true;
                memb.LastActivityDate  = DateTime.UtcNow;
                memb.AcceptLanguages   = languages;
                List <MemberCallback> callbacks;
                if (memb.ChangedMemberCallbacks == null)
                {
                    callbacks = new List <MemberCallback>();
                }
                else
                {
                    callbacks = new List <MemberCallback>(memb.ChangedMemberCallbacks);
                }
                var cbk = (from d in callbacks where d.HubID == hubId && d.ChannelID == peerId select d).SingleOrDefault();
                if (cbk == null)
                {
                    cbk = new MemberCallback
                    {
                        ApplicationID  = AppId,
                        UserID         = userId,
                        HubID          = hubId,
                        ChannelID      = peerId,
                        ConnectionID   = connectId,
                        IsDisconnected = false,
                        LastActiveDate = DateTime.UtcNow
                    };
                }
                else
                {
                    // it is very important to turn this on, otherwise the property will not be marked as modified.
                    // and the service will not save the change!
                    cbk.StartAutoUpdating = true;
                    cbk.ConnectionID      = connectId;
                    cbk.IsDisconnected    = false;
                    cbk.LastActiveDate    = DateTime.UtcNow;
                }
                memb.ChangedMemberCallbacks = new MemberCallback[] { cbk };
                await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { memb });

                UserServiceProxy usvc = new UserServiceProxy();
                var u = await usvc.LoadEntityByKeyAsync(cntx, userId);

                memb.UserRef = u;

                var peerMb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, peerId);

                ConnectionStatus status = new ConnectionStatus();
                status.me = cbk;
                MemberCallbackServiceProxy mbcsvc = new MemberCallbackServiceProxy();
                var peerCb = await mbcsvc.LoadEntityByKeyAsync(cntx, userId, hubId, AppId, peerId);

                if (peerCb == null || peerCb.ConnectionID == null || peerCb.IsDisconnected)
                {
                    MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy();
                    var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, 3);

                    var notifier = await mbcsvc.LoadEntityByKeyAsync(cntx, "System", noticeHubId, AppId, peerId);

                    if (notifier != null && notifier.ConnectionID != null && !notifier.IsDisconnected)
                    {
                        status.peerNotifier = notifier;
                        status.status       = PeerStatus.Notifiable;
                    }
                    MemberNotification n = new MemberNotification
                    {
                        ID            = Guid.NewGuid().ToString(),
                        Title         = string.Format(ResourceUtils.GetString("20dc5913998d0e9ed01360475e46a0f9", "{0} invites you to chat, is waiting ...", peerMb.AcceptLanguages), u.Username),
                        CreatedDate   = DateTime.UtcNow,
                        PriorityLevel = 0,
                        ReadCount     = 0,
                        ApplicationID = AppId,
                        TypeID        = 3,
                        UserID        = peerId
                    };
                    n.NoticeMsg          = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + n.Title + "\", \"isCancel\": false }";
                    n.IsNoticeDataLoaded = true;
                    MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
                    var r = await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), new MemberNotification[] { n });

                    status.noticeType  = ntype.TypeName;
                    status.noticeMsg   = "{ \"peerId\": \"" + userId + "\", \"peer\": \"" + u.Username + "\", \"connectId\": \"" + connectId + "\", \"msg\": \"" + n.Title + "\", \"isCancel\": false }";
                    status.noticeRecId = r.ChangedEntities[0].UpdatedItem.ID;
                }
                else
                {
                    UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
                    UserAssociation             utop  = await uasvc.LoadEntityByKeyAsync(cntx, userId, peerId, ApplicationContext.ChatAssocTypeId);

                    DateTime dt = DateTime.UtcNow;
                    if (utop == null)
                    {
                        utop = new UserAssociation
                        {
                            TypeID        = ApplicationContext.ChatAssocTypeId,
                            FromUserID    = userId,
                            ToUserID      = peerId,
                            CreateDate    = dt,
                            AssocCount    = 1,
                            LastAssoc     = dt,
                            InteractCount = 0,
                            Votes         = 0
                        };
                    }
                    else
                    {
                        utop.AssocCount++;
                    }
                    UserAssociation ptou = await uasvc.LoadEntityByKeyAsync(cntx, peerId, userId, ApplicationContext.ChatAssocTypeId);

                    if (ptou == null)
                    {
                        ptou = new UserAssociation
                        {
                            TypeID        = ApplicationContext.ChatAssocTypeId,
                            FromUserID    = peerId,
                            ToUserID      = userId,
                            CreateDate    = dt,
                            AssocCount    = 1,
                            LastAssoc     = dt,
                            InteractCount = 0,
                            Votes         = 0
                        };
                    }
                    else
                    {
                        ptou.AssocCount++;
                    }
                    await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), new UserAssociation[] { utop, ptou });

                    status.status = PeerStatus.Connected;
                }
                if (peerCb != null)
                {
                    peerCb.UserAppMemberRef = peerMb;
                }
                status.peer = peerCb;
                return(status);
            }
            return(null);
        }
 public static async Task<MemberCallback> OnUserDisconnected(string hubId, string connectId)
 {
     if (string.IsNullOrEmpty(connectId))
         return null;
     var cntx = Cntx;
     MemberCallbackServiceProxy cbksvc = new MemberCallbackServiceProxy();
     QueryExpresion qexpr = new QueryExpresion();
     qexpr.OrderTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "UserID" },
         new QToken { TkName = "asc" }
     });
     qexpr.FilterTks = new List<QToken>(new QToken[] { 
         new QToken { TkName = "ApplicationID == \"" + AppId + "\" && HubID == \"" + hubId + "\" && ConnectionID == \"" + connectId + "\"" }
     });
     var cbk = (await cbksvc.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).FirstOrDefault();
     if (cbk != null)
     {
         // top level entity does not need to set 'StartAutoUpdating' since it is done by the proxy:
         // cbk.StartAutoUpdating = true; 
         cbk.ConnectionID = null;
         cbk.LastActiveDate = DateTime.UtcNow;
         cbk.IsDisconnected = true;
         await cbksvc.AddOrUpdateEntitiesAsync(cntx, new MemberCallbackSet(), new MemberCallback[] { cbk });
     }
     return cbk;
 }