public static async Task <MemberCallback[]> UserConnectionClosed(string userId, 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.LastActivityDate = DateTime.UtcNow;
                List <MemberCallback> callbacks = new List <MemberCallback>();
                if (memb.ChangedMemberCallbacks != null)
                {
                    foreach (var c in memb.ChangedMemberCallbacks)
                    {
                        callbacks.Add(c.ShallowCopy());
                        c.StartAutoUpdating = true;
                        c.ConnectionID      = null;
                        c.IsDisconnected    = true;
                        c.LastActiveDate    = DateTime.UtcNow;
                    }
                }
                await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { memb });

                return((from d in callbacks where d.ConnectionID != null && !d.IsDisconnected select d).ToArray());
            }
            return(null);
        }
        public static async Task<MemberCallback> OnUserConnected(string hubId, 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;
                if (languages != null)
                    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 == "System" select d).SingleOrDefault();
                if (cbk == null)
                {
                    cbk = new MemberCallback
                    {
                        ApplicationID = AppId,
                        UserID = userId,
                        HubID = hubId,
                        ChannelID = "System",
                        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;
                    // other more explicit way of doing so is given in the following:
                    //cbk.ConnectionID = connectId;
                    //cbk.IsConnectionIDModified = true;
                    //cbk.IsDisconnected = false;
                    //cbk.IsIsDisconnectedModified = true;
                    //cbk.LastActiveDate = DateTime.UtcNow;
                    //cbk.IsLastActiveDateModified = true;
                }
                memb.ChangedMemberCallbacks = new MemberCallback[] { cbk };
                try
                {
                    await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { memb });
                }
                catch (Exception ex)
                {

                }
                return cbk;
            }
            return null;
        }
 public static async Task<UserAppMember> SetNotification(string userId, SimpleMessage[] msgs)
 {
     UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
     var cntx = Cntx;
     var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, userId);
     if (memb != null)
     {
         memb.ChangedMemberCallbacks = (await mbsvc.MaterializeAllMemberCallbacksAsync(cntx, memb)).ToArray();
         var notices = new List<MemberNotification>();
         foreach (var msg in msgs)
         {
             notices.Add(new MemberNotification
             {
                 ID = Guid.NewGuid().ToString(),
                 Title = msg.Title,
                 NoticeMsg = msg.Message,
                 NoticeData = msg.Data,
                 CreatedDate = DateTime.UtcNow,
                 PriorityLevel = (short)msg.Priority,
                 ReadCount = 0,
                 TypeID = msg.TypeId,
                 UserID = userId,
                 ApplicationID = AppId
             });
         }
         MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
         var results = await nsvc.AddOrUpdateEntitiesAsync(Cntx, new MemberNotificationSet(), notices.ToArray());
         for (int i = 0; i < msgs.Length; i++)
             msgs[i].Id = results.ChangedEntities[i].UpdatedItem.ID;
     }
     return memb;
 }
Example #4
0
        public static async Task ChangeAccountInfo(string id, ApplicationUser user)
        {
            var cntx = Cntx;
            UserServiceProxy usvc = new UserServiceProxy();
            var u = await usvc.LoadEntityByKeyAsync(cntx, id);

            if (u == null)
            {
                return;
            }
            u.FirstName = user.FirstName;
            u.LastName  = user.LastName;
            if (u.IsFirstNameModified || u.IsLastNameModified)
            {
                await usvc.AddOrUpdateEntitiesAsync(cntx, new UserSet(), new User[] { u });
            }
            if (!string.IsNullOrEmpty(user.Email))
            {
                UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
                var mb = await mbsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.App.ID, id);

                if (mb != null)
                {
                    mb.Email = user.Email;
                    if (mb.IsEmailModified)
                    {
                        await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { mb });
                    }
                }
            }
        }
        public static async Task <UserAppMember> LoadUser(string userId)
        {
            var cntx = Cntx;
            UserAppMemberServiceProxy msvc = new UserAppMemberServiceProxy();
            var m = await msvc.LoadEntityByKeyAsync(cntx, AppId, userId);

            return(m);
        }
Example #6
0
        public static async Task <dynamic> ChangeMemberStatus(string adminId, string uid, string status)
        {
            UserAppMemberSet s = new UserAppMemberSet();

            if (!(from d in s.MemberStatusValues where d == status select d).Any())
            {
                return new { ok = false, msg = string.Format(ResourceUtils.GetString("0b8472f8e1a556b4c90b516e2df1917b", "Status '{0}' is not known."), status) }
            }
            ;
            CallContext cctx = Cntx;

            try
            {
                UserServiceProxy usvc = new UserServiceProxy();

                UserSet us    = new UserSet();
                var     admin = await usvc.LoadEntityByKeyAsync(cctx, adminId);

                if (admin.ID == uid)
                {
                    return new { ok = false, msg = ResourceUtils.GetString("0bdf4ebe91cd037e986f8260069292be", "You shouldn't lock yourself out.") }
                }
                ;
                User u = await usvc.LoadEntityByKeyAsync(cctx, uid);

                if (u.Status != us.StatusValues[0])
                {
                    return new { ok = false, msg = ResourceUtils.GetString("b13fb15f7b82c3438ee9e09ae6a5ba2a", "The user is locked globally. It can not be changed in a particular application.") }
                }
                ;
                var maxadmp = await GetMaxPriority(adminId);

                var maxup = await GetMaxPriority(uid);

                if (maxadmp.Major < maxup.Major || maxadmp.Major == maxup.Major && maxadmp.Minor < maxup.Minor)
                {
                    return new { ok = false, msg = string.Format(ResourceUtils.GetString("0452f93e5e52c7eae26c4fac7aa2d5d7", "Denined! Your role level: {0} is less than the requested one."), maxadmp.Major.ToString() + "/" + maxadmp.Minor), newpwd = "" }
                }
                ;
                UserAppMemberServiceProxy umsrv = new UserAppMemberServiceProxy();
                UserAppMember             um    = await umsrv.LoadEntityByKeyAsync(cctx, ApplicationContext.App.ID, uid);

                if (um == null)
                {
                    return new { ok = false, msg = ResourceUtils.GetString("65318cf0e6b4b76ee9ec91f92405cbb8", "Member not found!") }
                }
                ;
                um.MemberStatus     = status;
                um.LastStatusChange = DateTime.UtcNow;
                await umsrv.AddOrUpdateEntitiesAsync(cctx, s, new UserAppMember[] { um });

                return(new { ok = true, msg = "" });
            }
            catch (Exception e)
            {
                return(new { ok = false, msg = string.Format(ResourceUtils.GetString("49dfe380301a10e682f1b3bc09136542", "Exception: {0}"), e.Message) });
            }
        }
        public static async Task <string> GetMembers(string set, string qexpr, string prevlast)
        {
            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 result = await svc.GetPageItemsAsync(Cntx, _set, _qexpr, _prevlast);

            var    ar    = new List <dynamic>();
            string appId = ApplicationContext.App.ID;
            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();

            foreach (var e in result)
            {
                //var membs = svc.MaterializeAllUserAppMembers(Cntx, e);
                //var memb = (from d in membs where d.ApplicationID == appId select d).SingleOrDefault();
                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();
                ar.Add(new { data = e, member = memb, hasIcon = memb != null && !string.IsNullOrEmpty(memb.IconMime) });
            }
            string json = ser3.Serialize(ar);

            return(json);
        }
Example #8
0
        public static async Task <OperationResult> AdjustUserRoleLevel(string adminId, string uid, int rid, int del)
        {
            OperationResult OpResult = new OperationResult();
            var             maxp     = await MemberAdminContext.GetMaxPriority(adminId);

            var cntx = Cntx;
            UserServiceProxy usvc = new UserServiceProxy();
            var u = usvc.LoadEntityByKey(cntx, uid);

            if (u == null)
            {
                OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
                return(OpResult);
            }
            UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
            var uir = await uirsvc.LoadEntityByKeyAsync(cntx, rid, u.ID);

            if (uir == null)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("78257cace857db766d54e6568d7f912b", "The user is not in this role.") };
                return(OpResult);
            }
            uir.RoleRef = await uirsvc.MaterializeRoleRefAsync(cntx, uir);

            if (maxp.Major < uir.RoleRef.RolePriority || maxp.Major == uir.RoleRef.RolePriority && uir.SubPriority + del > maxp.Major)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("5986d63fe301793ee7f5b2134a8f8787", "Modifying more priviledged role is not authorized.") };
                return(OpResult);
            }
            var oldPrio = uir.SubPriority;

            uir.SubPriority += del;
            uir.LastModified = DateTime.UtcNow;
            uir.AdminID      = adminId;
            await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });

            uir.UserID = u.ID;
            uir.RoleID = rid;
            await AddUserRoleHistory(uir, UserRoleOperations.Modified);

            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);

            var notice = new SimpleMessage
            {
                TypeId = 1,
                Title  = string.Format(ResourceUtils.GetString("54da39696e8014b5ded7a0eaeac1dfc4", "The relative priority of your role: [{0}] is changed from {1} to {2}.", memb.AcceptLanguages),
                                       uir.RoleRef.DistinctString, oldPrio, uir.SubPriority),
                Data = "{ id=\"" + rid + "\", type=\"role\", name=\"" + uir.RoleRef.DistinctString + "\" }"
            };

            OpResult.Result  = new { ok = true, msg = "" };
            OpResult.notices = new SimpleMessage[] { notice };
            return(OpResult);
        }
        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<ContentRecord> GetMemberIcon(string id)
 {
     UserAppMemberServiceProxy umsvc = new UserAppMemberServiceProxy();
     var um = await umsvc.LoadEntityByKeyAsync(Cntx, ApplicationContext.App.ID, id);
     if (um == null)
         return null;
     ContentRecord rec = new ContentRecord();
     rec.MimeType = um.IconMime;
     rec.LastModified = um.IconLastModified.HasValue ? um.IconLastModified.Value : DateTime.MaxValue;
     rec.Data = await umsvc.LoadEntityIconImgAsync(Cntx, ApplicationContext.App.ID, id);
     return rec;
 }
Example #11
0
        public static async Task <OperationResult> RemoveUserFromRole(string adminId, string uid, int rid)
        {
            OperationResult OpResult = new OperationResult();
            var             maxp     = await MemberAdminContext.GetMaxPriority(adminId);

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

            if (u == null)
            {
                OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
                return(OpResult);
            }
            UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
            var uir = await uirsvc.LoadEntityByKeyAsync(cntx, rid, u.ID);

            if (uir == null)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("78257cace857db766d54e6568d7f912b", "The user is not in this role.") };
                return(OpResult);
            }
            uir.RoleRef = await uirsvc.MaterializeRoleRefAsync(cntx, uir);

            if (maxp.Major < uir.RoleRef.RolePriority || maxp.Major == uir.RoleRef.RolePriority && uir.SubPriority > maxp.Major)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("0437b5660f17723dc29c3fa7e08e08a0", "Removing more priviledged role is not authorized.") };
                return(OpResult);
            }
            await uirsvc.DeleteEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });

            uir.UserID = u.ID;
            uir.RoleID = rid;
            await AddUserRoleHistory(uir, UserRoleOperations.Deleted);

            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);

            OpResult.Result  = new { ok = true, msg = "", available = new { id = rid, name = uir.RoleRef.RoleName, path = uir.RoleRef.DistinctString, op = true } };
            OpResult.notices = new SimpleMessage[]
            {
                new SimpleMessage
                {
                    TypeId = 1,
                    Title  = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), uir.RoleRef.DistinctString),
                    Data   = "{ id=\"" + rid + "\", type=\"role\", name=\"" + uir.RoleRef.DistinctString + "\" }"
                }
            };
            return(OpResult);
        }
 public static async Task<bool> UpdateMemeberIcon(string id, string mineType, DateTime lastModified, byte[] imgdata)
 {
     UserAppMemberServiceProxy umsvc = new UserAppMemberServiceProxy();
     var um = umsvc.LoadEntityByKey(Cntx, ApplicationContext.App.ID, id);
     if (um == null)
         return false;
     um.IconImg = imgdata;
     um.IsIconImgLoaded = true;
     um.IsIconImgModified = true;
     um.IconMime = mineType;
     um.IconLastModified = lastModified;
     var result = await umsvc.AddOrUpdateEntitiesAsync(Cntx, new UserAppMemberSet(), new UserAppMember[] { um });
     return (result.ChangedEntities[0].OpStatus & (int)EntityOpStatus.Updated) > 0;
 }
 public static async Task<string> GetMembers(string set, string qexpr, string prevlast)
 {
     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 result = await svc.GetPageItemsAsync(Cntx, _set, _qexpr, _prevlast);
     var ar = new List<dynamic>();
     string appId = ApplicationContext.App.ID;
     UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
     foreach (var e in result)
     {
         //var membs = svc.MaterializeAllUserAppMembers(Cntx, e);
         //var memb = (from d in membs where d.ApplicationID == appId select d).SingleOrDefault();
         UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
         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();
         ar.Add(new { data = e, member = memb, hasIcon = memb != null && !string.IsNullOrEmpty(memb.IconMime) });
     }
     string json = ser3.Serialize(ar);
     return json;
 }
Example #14
0
        public static async Task <ContentRecord> GetMemberIcon(string id)
        {
            UserAppMemberServiceProxy umsvc = new UserAppMemberServiceProxy();
            var um = await umsvc.LoadEntityByKeyAsync(Cntx, ApplicationContext.App.ID, id);

            if (um == null)
            {
                return(null);
            }
            ContentRecord rec = new ContentRecord();

            rec.MimeType     = um.IconMime;
            rec.LastModified = um.IconLastModified.HasValue ? um.IconLastModified.Value : DateTime.MaxValue;
            rec.Data         = await umsvc.LoadEntityIconImgAsync(Cntx, ApplicationContext.App.ID, id);

            return(rec);
        }
Example #15
0
        public static async Task <bool> UpdateMemeberIcon(string id, string mineType, DateTime lastModified, byte[] imgdata)
        {
            UserAppMemberServiceProxy umsvc = new UserAppMemberServiceProxy();
            var um = umsvc.LoadEntityByKey(Cntx, ApplicationContext.App.ID, id);

            if (um == null)
            {
                return(false);
            }
            um.IconImg           = imgdata;
            um.IsIconImgLoaded   = true;
            um.IsIconImgModified = true;
            um.IconMime          = mineType;
            um.IconLastModified  = lastModified;
            var result = await umsvc.AddOrUpdateEntitiesAsync(Cntx, new UserAppMemberSet(), new UserAppMember[] { um });

            return((result.ChangedEntities[0].OpStatus & (int)EntityOpStatus.Updated) > 0);
        }
        public static async Task <string> LoadUserInfo(string userId, string approot)
        {
            var cntx = Cntx;
            UserAppMemberServiceProxy msvc = new UserAppMemberServiceProxy();
            var m = await msvc.LoadEntityByKeyAsync(cntx, AppId, userId);

            string json = @"{ ""id"": """ + userId + @""", ""icon"": ";

            if (!string.IsNullOrEmpty(m.IconMime))
            {
                json += @"true, ""iconUrl"": """ + approot + @"Account/GetMemberIcon?id=" + userId + @"""";
            }
            else
            {
                json += @"false, ""iconUrl"": """"";
            }
            json += " }";
            return(json);
        }
 public static async Task ChangeAccountInfo(string id, ApplicationUser user)
 {
     var cntx = Cntx;
     UserServiceProxy usvc = new UserServiceProxy();
     var u = await usvc.LoadEntityByKeyAsync(cntx, id);
     if (u == null)
         return;
     u.FirstName = user.FirstName;
     u.LastName = user.LastName;
     if (u.IsFirstNameModified || u.IsLastNameModified)
         await usvc.AddOrUpdateEntitiesAsync(cntx, new UserSet(), new User[] { u });
     if (!string.IsNullOrEmpty(user.Email))
     {
         UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
         var mb = await mbsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.App.ID, id);
         if (mb != null)
         {
             mb.Email = user.Email;
             if (mb.IsEmailModified)
                 await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { mb });
         }
     }
 }
Example #18
0
        public static async Task <UserAppMember> SetNotification(string userId, SimpleMessage[] msgs)
        {
            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var cntx = Cntx;
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, userId);

            if (memb != null)
            {
                memb.ChangedMemberCallbacks = (await mbsvc.MaterializeAllMemberCallbacksAsync(cntx, memb)).ToArray();
                var notices = new List <MemberNotification>();
                foreach (var msg in msgs)
                {
                    notices.Add(new MemberNotification
                    {
                        ID            = Guid.NewGuid().ToString(),
                        Title         = msg.Title,
                        NoticeMsg     = msg.Message,
                        NoticeData    = msg.Data,
                        CreatedDate   = DateTime.UtcNow,
                        PriorityLevel = (short)msg.Priority,
                        ReadCount     = 0,
                        TypeID        = msg.TypeId,
                        UserID        = userId,
                        ApplicationID = AppId
                    });
                }
                MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy();
                var results = await nsvc.AddOrUpdateEntitiesAsync(Cntx, new MemberNotificationSet(), notices.ToArray());

                for (int i = 0; i < msgs.Length; i++)
                {
                    msgs[i].Id = results.ChangedEntities[i].UpdatedItem.ID;
                }
            }
            return(memb);
        }
 public static async Task<UserAppMember> LoadUser(string userId)
 {
     var cntx = Cntx;
     UserAppMemberServiceProxy msvc = new UserAppMemberServiceProxy();
     var m = await msvc.LoadEntityByKeyAsync(cntx, AppId, userId);
     return m;
 }
Example #20
0
        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<OperationResult> AddUserToRole(string adminId, string uid, int rid)
 {
     OperationResult OpResult = new OperationResult();
     var maxp = await MemberAdminContext.GetMaxPriority(adminId);
     RoleServiceProxy rsvc = new RoleServiceProxy();
     UserServiceProxy usvc = new UserServiceProxy();
     var cntx = Cntx;
     var u = await usvc.LoadEntityByKeyAsync(cntx, uid);
     if (u == null)
     {
         OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
         return OpResult;
     }
     var uroles = await usvc.MaterializeAllRolesAsync(cntx, u);
     if (DBAutoCleanupRoles)
     {
         // prevent polution
         List<Role> higherroles = new List<Role>();
         foreach (var ur in uroles)
         {
             var pr = ur;
             if (pr.ID == rid)
                 higherroles.Add(ur);
             while (pr.ParentID != null)
             {
                 pr.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, pr);
                 pr = pr.UpperRef;
                 if (pr.ID == rid)
                 {
                     higherroles.Add(ur);
                     break;
                 }
             }
         }
         if (higherroles.Count > 0)
         {
             string rolesstr = "";
             foreach (var hr in higherroles)
                 rolesstr += (rolesstr == "" ? "" : ", ") + hr.DistinctString;
             string errorfmt = ResourceUtils.GetString("43558b5deaec392b9461d28d4e753687", "Operation denied: the user already has this or more specific roles: '{0}'! Try to remove them before adding present one.");
             OpResult.Result = new { ok = false, msg = string.Format(errorfmt, rolesstr) };
             return OpResult;
         }
     }
     var r = await rsvc.LoadEntityByKeyAsync(cntx, rid);
     if (r == null)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("db2a3d7bc44d36a9ebeaa0d562c4cd21", "The role is not found.") };
         return OpResult;
     }
     else if (r.RolePriority > maxp.Major)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("67729f0f407d1ea57f28b43235b3e5f6", "Adding more priviledged role is not authorized.") };
         return OpResult;
     }
     List<SimpleMessage> notices = new List<SimpleMessage>();
     var uir = new UsersInRole();
     List<Role> removed = new List<Role>();
     if (DBAutoCleanupRoles)
     {
         // clean up: find more general roles to remove.
         var p = r;
         while (p.ParentID != null)
         {
             p.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, p);
             p = p.UpperRef;
             foreach (var ur in uroles)
             {
                 if (ur.ID == p.ID)
                 {
                     if (!(from d in removed where d.ID == p.ID select d).Any())
                         removed.Add(p);
                 }
             }
         }
     }
     uir.IsPersisted = false;
     uir.UserID = u.ID;
     uir.RoleID = rid;
     uir.SubPriority = 0;
     uir.AssignDate = DateTime.UtcNow;
     uir.LastModified = uir.AssignDate;
     uir.AdminID = adminId;
     UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
     await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });
     UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
     var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);
     notices.Add(new SimpleMessage
                 {
                     TypeId = 1,
                     Title = string.Format(ResourceUtils.GetString("38015f8af3e032dfd803758dd2bde917", "New role: [{0}] is added.", memb.AcceptLanguages), r.DistinctString),
                     Data = "{ id=\"" + r.ID + "\", type=\"role\", name=\"" + r.DistinctString + "\" }"
                 });
     var _r = new { id = rid, uid = u.ID, name = r.RoleName, path = r.DistinctString, level = uir.SubPriority, op = true };
     List<dynamic> _removed = new List<dynamic>();
     if (removed.Count > 0)
     {
         List<UsersInRole> l = new List<UsersInRole>();
         foreach (var rmv in removed)
         {
             var x = uirsvc.LoadEntityByKey(Cntx, rmv.ID, u.ID);
             l.Add(x);
             _removed.Add(new { id = rmv.ID, name = rmv.RoleName, path = rmv.DistinctString, op = maxp.Major >= rmv.RolePriority });
         }
         await uirsvc.DeleteEntitiesAsync(Cntx, new UsersInRoleSet(), l.ToArray());
         foreach (var _rrmv in removed)
             notices.Add(new SimpleMessage
             {
                 TypeId = 1,
                 Title = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), _rrmv.DistinctString),
                 Data = "{ id=\"" + _rrmv.ID + "\", type=\"role\", name=\"" + _rrmv.DistinctString + "\" }"
             });
     }
     await AddUserRoleHistory(uir, UserRoleOperations.Added);
     OpResult.Result = new { ok = true, msg = "", added = _r, removed = _removed.ToArray() };
     OpResult.notices = notices.ToArray();
     return OpResult;
 }
 public static async Task<OperationResult> RemoveUserFromRole(string adminId, string uid, int rid)
 {
     OperationResult OpResult = new OperationResult();
     var maxp = await MemberAdminContext.GetMaxPriority(adminId);
     var cntx = Cntx;
     UserServiceProxy usvc = new UserServiceProxy();
     var u = await usvc.LoadEntityByKeyAsync(cntx, uid);
     if (u == null)
     {
         OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
         return OpResult;
     }
     UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
     var uir = await uirsvc.LoadEntityByKeyAsync(cntx, rid, u.ID);
     if (uir == null)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("78257cace857db766d54e6568d7f912b", "The user is not in this role.") };
         return OpResult;
     }
     uir.RoleRef = await uirsvc.MaterializeRoleRefAsync(cntx, uir);
     if (maxp.Major < uir.RoleRef.RolePriority || maxp.Major == uir.RoleRef.RolePriority && uir.SubPriority > maxp.Major)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("0437b5660f17723dc29c3fa7e08e08a0", "Removing more priviledged role is not authorized.") };
         return OpResult;
     }
     await uirsvc.DeleteEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });
     uir.UserID = u.ID;
     uir.RoleID = rid;
     await AddUserRoleHistory(uir, UserRoleOperations.Deleted);
     UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
     var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);
     OpResult.Result = new { ok = true, msg = "", available = new { id = rid, name = uir.RoleRef.RoleName, path = uir.RoleRef.DistinctString, op = true } };
     OpResult.notices = new SimpleMessage[]
     {
         new SimpleMessage 
         {
             TypeId = 1,
             Title = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), uir.RoleRef.DistinctString), 
             Data = "{ id=\"" + rid + "\", type=\"role\", name=\"" + uir.RoleRef.DistinctString + "\" }"
         }
     };
     return OpResult;
 }
 public static async Task<OperationResult> AdjustUserRoleLevel(string adminId, string uid, int rid, int del)
 {
     OperationResult OpResult = new OperationResult();
     var maxp = await MemberAdminContext.GetMaxPriority(adminId);
     var cntx = Cntx;
     UserServiceProxy usvc = new UserServiceProxy();
     var u = usvc.LoadEntityByKey(cntx, uid);
     if (u == null)
     {
         OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
         return OpResult;
     }
     UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
     var uir = await uirsvc.LoadEntityByKeyAsync(cntx, rid, u.ID);
     if (uir == null)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("78257cace857db766d54e6568d7f912b", "The user is not in this role.") };
         return OpResult;
     }
     uir.RoleRef = await uirsvc.MaterializeRoleRefAsync(cntx, uir);
     if (maxp.Major < uir.RoleRef.RolePriority || maxp.Major == uir.RoleRef.RolePriority && uir.SubPriority + del > maxp.Major)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("5986d63fe301793ee7f5b2134a8f8787", "Modifying more priviledged role is not authorized.") };
         return OpResult;
     }
     var oldPrio = uir.SubPriority;
     uir.SubPriority += del;
     uir.LastModified = DateTime.UtcNow;
     uir.AdminID = adminId;
     await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });
     uir.UserID = u.ID;
     uir.RoleID = rid;
     await AddUserRoleHistory(uir, UserRoleOperations.Modified);
     UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
     var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);
     var notice = new SimpleMessage
     {
         TypeId = 1,
         Title = string.Format(ResourceUtils.GetString("54da39696e8014b5ded7a0eaeac1dfc4", "The relative priority of your role: [{0}] is changed from {1} to {2}.", memb.AcceptLanguages),
                               uir.RoleRef.DistinctString, oldPrio, uir.SubPriority),
         Data = "{ id=\"" + rid + "\", type=\"role\", name=\"" + uir.RoleRef.DistinctString + "\" }"
     };
     OpResult.Result = new { ok = true, msg = "" };
     OpResult.notices = new SimpleMessage[] { notice };
     return OpResult;
 }
Example #24
0
        public override async Task <TUser> FindAsync(string userName, string password)
        {
            if (HttpContext.Current != null)
            {
                string cacheKey = "userLoginState:" + userName;
                var    error    = HttpContext.Current.Cache[cacheKey] as AuthFailedEventArg;
                if (error != null)
                {
                    ErrorsHandler(userName, error);
                    return(null);
                }
            }
            CallContext      cctx = _cctx.CreateCopy();
            UserServiceProxy usvc = new UserServiceProxy();
            UserSet          us   = new UserSet();
            var lu = await usvc.LoadEntityByNatureAsync(cctx, userName);

            if (lu == null || lu.Count == 0)
            {
                var err = new AuthFailedEventArg
                {
                    FailType    = AuthFailedTypes.UnknownUser,
                    FailMessage = ResourceUtils.GetString("3488820581565e9098c46152335ebb24", "Your don't have an account in the present system, please register!")
                };
                ErrorsHandler(userName, err);
                return(null);
            }
            var u = lu[0];

            if (!u.IsApproved)
            {
                var err = new AuthFailedEventArg
                {
                    FailType    = AuthFailedTypes.ApprovalNeeded,
                    FailMessage = ResourceUtils.GetString("3bdf31486d76404d69c73b90c790f9be", "Your account is pending for approval, please wait!")
                };
                ErrorsHandler(userName, err);
                return(null);
            }
            if (u.Status != us.StatusValues[0])
            {
                var err = new AuthFailedEventArg
                {
                    FailType    = AuthFailedTypes.UserAccountBlocked,
                    FailMessage = string.Format(ResourceUtils.GetString("0bcd70b0b005df9491a0623280ee1f4d", "Your account is in the state of being [{0}], please contact an administrator!"), u.Status)
                };
                ErrorsHandler(userName, err);
                return(null);
            }
            UserAppMemberSet          membs = new UserAppMemberSet();
            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cctx, app.ID, u.ID);

            if (memb == null)
            {
                var err = new AuthFailedEventArg
                {
                    FailType    = AuthFailedTypes.MemberNotFound,
                    FailMessage = string.Format(ResourceUtils.GetString("d084974602e8940a962aad7d00bf7b3e", "You are not currently a member of \"{0}\", please register."), string.IsNullOrEmpty(app.DisplayName) ? app.Name : app.DisplayName)
                };
                ErrorsHandler(userName, err);
                return(null);
            }
            if (memb.MemberStatus != membs.MemberStatusValues[0])
            {
                if (memb.MemberStatus != membs.MemberStatusValues[3])
                {
                    var err = new AuthFailedEventArg
                    {
                        FailType    = AuthFailedTypes.MembershipBlocked,
                        FailMessage = string.Format(ResourceUtils.GetString("3508707fb8263c95b4c022dd0468235b", "Your membership in \"{0}\" is in the state of being [{1}], please contact an administrator!"), string.IsNullOrEmpty(app.DisplayName) ? app.Name : app.DisplayName, memb.MemberStatus)
                    };
                    ErrorsHandler(userName, err);
                    return(null);
                }
                else
                {
                    var      windowStart = u.FailedPasswordAttemptWindowStart.HasValue ? u.FailedPasswordAttemptWindowStart.Value : DateTime.MinValue;
                    DateTime windowEnd   = windowStart.AddSeconds((Store as UserStore <TUser>).PasswordAttemptWindow);
                    if (DateTime.UtcNow <= windowEnd)
                    {
                        var err = new AuthFailedEventArg
                        {
                            FailType    = AuthFailedTypes.MembershipFrozen,
                            FailMessage = string.Format(ResourceUtils.GetString("99529364b5dfda1d15a5859cd49c5a7c", "Maximum login attemps for \"{0}\" exceeded, please try again later!"), string.IsNullOrEmpty(app.DisplayName) ? app.Name : app.DisplayName)
                        };
                        ErrorsHandler(userName, err, false);
                        return(null);
                    }
                    else
                    {
                        memb.MemberStatus               = membs.MemberStatusValues[0];
                        memb.IsMemberStatusModified     = true;
                        memb.LastStatusChange           = DateTime.UtcNow;
                        memb.IsLastStatusChangeModified = true;
                        await mbsvc.AddOrUpdateEntitiesAsync(cctx, membs, new UserAppMember[] { memb });

                        var err = new AuthFailedEventArg
                        {
                            FailType    = AuthFailedTypes.MembershipRecovered,
                            FailMessage = ResourceUtils.GetString("8cdaed0e2a0dd2e31c4960412351d4b5", "Your membership status is restored, please try again!")
                        };
                        if (u.FailedPasswordAttemptCount != 0)
                        {
                            u.FailedPasswordAttemptCount = 0;
                            usvc.EnqueueNewOrUpdateEntities(cctx, us, new User[] { u });
                        }
                        ErrorsHandler(userName, err, false);
                        return(null);
                    }
                }
            }
            TUser user = new TUser();

            user.UpdateInstance(u);
            var found = await base.FindAsync(userName, password);

            if (found == null)
            {
                await(Store as UserStore <TUser>).UpdateFailureCountAsync(cctx, user, "password");
                var err = new AuthFailedEventArg
                {
                    FailType    = AuthFailedTypes.InvalidCredential,
                    FailMessage = ResourceUtils.GetString("3a2a06b3a1f05cde765219211bf2e9be", "Invalid username or password.")
                };
                ErrorsHandler(userName, err, false);
            }
            else
            {
                u.LastLoginDate           = DateTime.UtcNow;
                u.IsLastLoginDateModified = true;
                usvc.EnqueueNewOrUpdateEntities(cctx, new UserSet(), new User[] { u });
                memb.LastActivityDate           = u.LastLoginDate;
                memb.IsLastActivityDateModified = true;
                mbsvc.EnqueueNewOrUpdateEntities(cctx, membs, new UserAppMember[] { memb });
            }
            return(found);
        }
 public static async Task<dynamic> ChangeMemberStatus(string adminId, string uid, string status)
 {
     UserAppMemberSet s = new UserAppMemberSet();
     if (!(from d in s.MemberStatusValues where d == status select d).Any())
         return new { ok = false, msg = string.Format(ResourceUtils.GetString("0b8472f8e1a556b4c90b516e2df1917b", "Status '{0}' is not known."), status) };
     CallContext cctx = Cntx;
     try
     {
         UserServiceProxy usvc = new UserServiceProxy();
         UserSet us = new UserSet();
         var admin = await usvc.LoadEntityByKeyAsync(cctx, adminId);
         if (admin.ID == uid)
             return new { ok = false, msg = ResourceUtils.GetString("0bdf4ebe91cd037e986f8260069292be", "You shouldn't lock yourself out.") };
         User u = await usvc.LoadEntityByKeyAsync(cctx, uid);
         if (u.Status != us.StatusValues[0])
             return new { ok = false, msg = ResourceUtils.GetString("b13fb15f7b82c3438ee9e09ae6a5ba2a", "The user is locked globally. It can not be changed in a particular application.") };
         var maxadmp = await GetMaxPriority(adminId);
         var maxup = await GetMaxPriority(uid);
         if (maxadmp.Major < maxup.Major || maxadmp.Major == maxup.Major && maxadmp.Minor < maxup.Minor)
             return new { ok = false, msg = string.Format(ResourceUtils.GetString("0452f93e5e52c7eae26c4fac7aa2d5d7", "Denined! Your role level: {0} is less than the requested one."), maxadmp.Major.ToString() + "/" + maxadmp.Minor), newpwd = "" };
         UserAppMemberServiceProxy umsrv = new UserAppMemberServiceProxy();
         UserAppMember um = await umsrv.LoadEntityByKeyAsync(cctx, ApplicationContext.App.ID, uid);
         if (um == null)
             return new { ok = false, msg = ResourceUtils.GetString("65318cf0e6b4b76ee9ec91f92405cbb8", "Member not found!") };
         um.MemberStatus = status;
         um.LastStatusChange = DateTime.UtcNow;
         await umsrv.AddOrUpdateEntitiesAsync(cctx, s, new UserAppMember[] { um });
         return new { ok = true, msg = "" };
     }
     catch (Exception e)
     {
         return new { ok = false, msg = string.Format(ResourceUtils.GetString("49dfe380301a10e682f1b3bc09136542", "Exception: {0}"), e.Message) };
     }
 }
        public static async Task <MemberCallback> UserConnected(string hubId, string groupId, 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 == groupId select d).SingleOrDefault();
                if (cbk == null)
                {
                    cbk = new MemberCallback
                    {
                        ApplicationID  = AppId,
                        UserID         = userId,
                        HubID          = hubId,
                        ChannelID      = groupId,
                        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;
                    // other more explicit way of doing so is given in the following:
                    //cbk.ConnectionID = connectId;
                    //cbk.IsConnectionIDModified = true;
                    //cbk.IsDisconnected = false;
                    //cbk.IsIsDisconnectedModified = true;
                    //cbk.LastActiveDate = DateTime.UtcNow;
                    //cbk.IsLastActiveDateModified = true;
                }
                memb.ChangedMemberCallbacks = new MemberCallback[] { cbk };
                await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { memb });

                cbk.UserAppMemberRef = memb;
                if (memb.UserRef == null)
                {
                    memb.UserRef = await mbsvc.MaterializeUserRefAsync(cntx, memb);
                }
                return(cbk);
            }
            return(null);
        }
 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;
 }
Example #28
0
        public static async Task <OperationResult> AddUserToRole(string adminId, string uid, int rid)
        {
            OperationResult OpResult = new OperationResult();
            var             maxp     = await MemberAdminContext.GetMaxPriority(adminId);

            RoleServiceProxy rsvc = new RoleServiceProxy();
            UserServiceProxy usvc = new UserServiceProxy();
            var cntx = Cntx;
            var u    = await usvc.LoadEntityByKeyAsync(cntx, uid);

            if (u == null)
            {
                OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
                return(OpResult);
            }
            var uroles = await usvc.MaterializeAllRolesAsync(cntx, u);

            if (DBAutoCleanupRoles)
            {
                // prevent polution
                List <Role> higherroles = new List <Role>();
                foreach (var ur in uroles)
                {
                    var pr = ur;
                    if (pr.ID == rid)
                    {
                        higherroles.Add(ur);
                    }
                    while (pr.ParentID != null)
                    {
                        pr.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, pr);

                        pr = pr.UpperRef;
                        if (pr.ID == rid)
                        {
                            higherroles.Add(ur);
                            break;
                        }
                    }
                }
                if (higherroles.Count > 0)
                {
                    string rolesstr = "";
                    foreach (var hr in higherroles)
                    {
                        rolesstr += (rolesstr == "" ? "" : ", ") + hr.DistinctString;
                    }
                    string errorfmt = ResourceUtils.GetString("43558b5deaec392b9461d28d4e753687", "Operation denied: the user already has this or more specific roles: '{0}'! Try to remove them before adding present one.");
                    OpResult.Result = new { ok = false, msg = string.Format(errorfmt, rolesstr) };
                    return(OpResult);
                }
            }
            var r = await rsvc.LoadEntityByKeyAsync(cntx, rid);

            if (r == null)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("db2a3d7bc44d36a9ebeaa0d562c4cd21", "The role is not found.") };
                return(OpResult);
            }
            else if (r.RolePriority > maxp.Major)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("67729f0f407d1ea57f28b43235b3e5f6", "Adding more priviledged role is not authorized.") };
                return(OpResult);
            }
            List <SimpleMessage> notices = new List <SimpleMessage>();
            var         uir     = new UsersInRole();
            List <Role> removed = new List <Role>();

            if (DBAutoCleanupRoles)
            {
                // clean up: find more general roles to remove.
                var p = r;
                while (p.ParentID != null)
                {
                    p.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, p);

                    p = p.UpperRef;
                    foreach (var ur in uroles)
                    {
                        if (ur.ID == p.ID)
                        {
                            if (!(from d in removed where d.ID == p.ID select d).Any())
                            {
                                removed.Add(p);
                            }
                        }
                    }
                }
            }
            uir.IsPersisted  = false;
            uir.UserID       = u.ID;
            uir.RoleID       = rid;
            uir.SubPriority  = 0;
            uir.AssignDate   = DateTime.UtcNow;
            uir.LastModified = uir.AssignDate;
            uir.AdminID      = adminId;
            UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
            await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });

            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);

            notices.Add(new SimpleMessage
            {
                TypeId = 1,
                Title  = string.Format(ResourceUtils.GetString("38015f8af3e032dfd803758dd2bde917", "New role: [{0}] is added.", memb.AcceptLanguages), r.DistinctString),
                Data   = "{ id=\"" + r.ID + "\", type=\"role\", name=\"" + r.DistinctString + "\" }"
            });
            var            _r       = new { id = rid, uid = u.ID, name = r.RoleName, path = r.DistinctString, level = uir.SubPriority, op = true };
            List <dynamic> _removed = new List <dynamic>();

            if (removed.Count > 0)
            {
                List <UsersInRole> l = new List <UsersInRole>();
                foreach (var rmv in removed)
                {
                    var x = uirsvc.LoadEntityByKey(Cntx, rmv.ID, u.ID);
                    l.Add(x);
                    _removed.Add(new { id = rmv.ID, name = rmv.RoleName, path = rmv.DistinctString, op = maxp.Major >= rmv.RolePriority });
                }
                await uirsvc.DeleteEntitiesAsync(Cntx, new UsersInRoleSet(), l.ToArray());

                foreach (var _rrmv in removed)
                {
                    notices.Add(new SimpleMessage
                    {
                        TypeId = 1,
                        Title  = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), _rrmv.DistinctString),
                        Data   = "{ id=\"" + _rrmv.ID + "\", type=\"role\", name=\"" + _rrmv.DistinctString + "\" }"
                    });
                }
            }
            await AddUserRoleHistory(uir, UserRoleOperations.Added);

            OpResult.Result  = new { ok = true, msg = "", added = _r, removed = _removed.ToArray() };
            OpResult.notices = notices.ToArray();
            return(OpResult);
        }
 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<string> LoadUserInfo(string userId, string approot)
 {
     var cntx = Cntx;
     UserAppMemberServiceProxy msvc = new UserAppMemberServiceProxy();
     var m = await msvc.LoadEntityByKeyAsync(cntx, AppId, userId);
     string json = @"{ ""id"": """ + userId + @""", ""icon"": ";
     if (!string.IsNullOrEmpty(m.IconMime))
         json += @"true, ""iconUrl"": """ + approot + @"Account/GetMemberIcon?id=" + userId + @"""";
     else
         json += @"false, ""iconUrl"": """"";
     json += " }";
     return json;
 }
 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;
 }
        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[]> UserConnectionClosed(string userId, 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.LastActivityDate = DateTime.UtcNow;
         List<MemberCallback> callbacks = new List<MemberCallback>();
         if (memb.ChangedMemberCallbacks != null)
         {
             foreach (var c in memb.ChangedMemberCallbacks)
             {
                 callbacks.Add(c.ShallowCopy());
                 c.StartAutoUpdating = true;
                 c.ConnectionID = null;
                 c.IsDisconnected = true;
                 c.LastActiveDate = DateTime.UtcNow;
             }
         }
         await mbsvc.AddOrUpdateEntitiesAsync(cntx, new UserAppMemberSet(), new UserAppMember[] { memb });
         return (from d in callbacks where d.ConnectionID != null && !d.IsDisconnected select d).ToArray();
     }
     return null;
 }