Example #1
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) });
            }
        }
Example #2
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<RolePriority> GetMaxPriority(string uid)
 {
     UserServiceProxy usrv = new UserServiceProxy();
     var u = await usrv.LoadEntityByKeyAsync(Cntx, uid);
     if (u == null)
         return new RolePriority { Major = -1, Minor = -1 };
     return await GetMaxPriority(u);
 }
Example #4
0
        public static async Task <dynamic> ResetUserPassword(string adminId, string id)
        {
            CallContext cctx = Cntx;

            try
            {
                UserServiceProxy usvc = new UserServiceProxy();
                var u = await usvc.LoadEntityByKeyAsync(cctx, id);

                if (u == null)
                {
                    return("");
                }
                var admin = await usvc.LoadEntityByKeyAsync(cctx, adminId);

                var maxadmp = await GetMaxPriority(adminId);

                var maxup = await GetMaxPriority(id);

                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 = "" }
                }
                ;
                UserStore <ApplicationUser> store = new UserStore <ApplicationUser>();
                PasswordGenerator           pgen  = new PasswordGenerator();
                var pwd = pgen.Generate();
                while (!pgen.Validate(pwd))
                {
                    pwd = pgen.Generate();
                }
                u.Password = store.HashPassword(pwd);
                if (u.IsPasswordModified)
                {
                    u.LastPasswordChangedDate = DateTime.UtcNow;
                    await usvc.AddOrUpdateEntitiesAsync(cctx, new UserSet(), new User[] { u });
                }
                return(new { ok = true, msg = "", newpwd = pwd });
            }
            catch (Exception e)
            {
                return(new { ok = false, msg = string.Format(ResourceUtils.GetString("49dfe380301a10e682f1b3bc09136542", "Exception: {0}"), e.Message) });
            }
        }
        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);
        }
Example #6
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);
        }
Example #7
0
        public static async Task <RolePriority> GetMaxPriority(string uid)
        {
            UserServiceProxy usrv = new UserServiceProxy();
            var u = await usrv.LoadEntityByKeyAsync(Cntx, uid);

            if (u == null)
            {
                return new RolePriority {
                           Major = -1, Minor = -1
                }
            }
            ;
            return(await GetMaxPriority(u));
        }
 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 async Task <ActionResult> ChangeAccountInfo(string returnUrl, ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? ResourceUtils.GetString("9bc75a1c6d94e70e8b96d8d59115c0c0", "Your password has been changed.")
                : message == ManageMessageId.SetPasswordSuccess ? ResourceUtils.GetString("9ad4e391b8ba2faf5177dcfa6dcee143", "Your password has been set.")
                : message == ManageMessageId.RemoveLoginSuccess ? ResourceUtils.GetString("9d813b903dbe8155105d3b5c4e6a04ed", "The external login was removed.")
                : message == ManageMessageId.Error ? ResourceUtils.GetString("c69732cc923305ac0684ac8fc05a4bcb", "An error has occurred.")
                : "";
            ViewBag.HasLocalPassword = HasPassword();
            ViewBag.ReturnUrl        = string.IsNullOrEmpty(returnUrl) ? Url.Action("ChangeAccountInfo") : returnUrl;
            ChangeAccountInfoModel model = new ChangeAccountInfoModel();
            UserServiceProxy       usvc  = new UserServiceProxy();
            var cntx = Startup.ClientContext.CreateCopy();

            cntx.DirectDataAccess = true;
            var u = await usvc.LoadEntityByKeyAsync(cntx, User.Identity.GetUserId());

            model.FirstName = u.FirstName;
            model.LastName  = u.LastName;
            var ci = User.Identity as System.Security.Claims.ClaimsIdentity;

            model.Email = (from d in ci.Claims where d.Type == Microsoft.IdentityModel.Claims.ClaimTypes.Email select d.Value).SingleOrDefault();
            return(View(model));
        }
Example #10
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<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> 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> 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> 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<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<dynamic> ResetUserPassword(string adminId, string id)
 {
     CallContext cctx = Cntx;
     try
     {
         UserServiceProxy usvc = new UserServiceProxy();
         var u = await usvc.LoadEntityByKeyAsync(cctx, id);
         if (u == null)
             return "";
         var admin = await usvc.LoadEntityByKeyAsync(cctx, adminId);
         var maxadmp = await GetMaxPriority(adminId);
         var maxup = await GetMaxPriority(id);
         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 = "" };
         UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();
         PasswordGenerator pgen = new PasswordGenerator();
         var pwd = pgen.Generate();
         while (!pgen.Validate(pwd))
             pwd = pgen.Generate();
         u.Password = store.HashPassword(pwd);
         if (u.IsPasswordModified)
         {
             u.LastPasswordChangedDate = DateTime.UtcNow;
             await usvc.AddOrUpdateEntitiesAsync(cctx, new UserSet(), new User[] { u });
         }
         return new { ok = true, msg = "", newpwd = pwd };
     }
     catch (Exception e)
     {
         return new { ok = false, msg = string.Format(ResourceUtils.GetString("49dfe380301a10e682f1b3bc09136542", "Exception: {0}"), e.Message) };
     }
 }
        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 <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
            });
        }
Example #19
0
        public static async Task LeaveUserMessage(string chatHubId, string userId, string peerId, string replyId, 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();
            var          now = DateTime.UtcNow;
            ShortMessage msg = new ShortMessage
            {
                ID            = Guid.NewGuid().ToString(),
                ApplicationID = AppId,
                TypeID        = ApplicationContext.ChatShortMsgTypeId,
                GroupID       = null,
                FromID        = userId,
                ToID          = peerId,
                ReplyToID     = string.IsNullOrEmpty(replyId) ? null : replyId,
                CreatedDate   = now,
                LastModified  = now,
                MsgText       = message,
                IsNotReceived = true
            };
            await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });

            UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
            DateTime dt = DateTime.UtcNow;
            List <UserAssociation> lass = new List <UserAssociation>();
            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    = 0,
                    LastAssoc     = dt,
                    InteractCount = 1,
                    Votes         = 0
                };
            }
            else
            {
                utop.InteractCount++;
            }
            lass.Add(utop);
            if (!string.IsNullOrEmpty(replyId))
            {
                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    = 0,
                        LastAssoc     = dt,
                        InteractCount = 0,
                        Votes         = 0
                    };
                }
                else
                {
                    ptou.InteractCount++;
                }
                lass.Add(ptou);
            }
            await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), lass.ToArray());
        }
 public static async Task<dynamic> RemoveUserFromRole(string adminId, string uid, int rid)
 {
     var maxp = await MemberAdminContext.GetMaxPriority(adminId);
     UserServiceProxy usvc = new UserServiceProxy();
     var u = await usvc.LoadEntityByKeyAsync(Cntx, uid);
     if (u == null)
         return new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
     UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
     var uir = await uirsvc.LoadEntityByKeyAsync(Cntx, rid, u.ID);
     if (uir == null)
         return new { ok = false, msg = ResourceUtils.GetString("78257cace857db766d54e6568d7f912b", "The user is not in this role.") };
     uir.RoleRef = await uirsvc.MaterializeRoleRefAsync(Cntx, uir);
     if (maxp.Major < uir.RoleRef.RolePriority || maxp.Major == uir.RoleRef.RolePriority && uir.SubPriority > maxp.Major)
         return new { ok = false, msg = ResourceUtils.GetString("0437b5660f17723dc29c3fa7e08e08a0", "Removing more priviledged role is not authorized.") };
     await uirsvc.DeleteEntitiesAsync(Cntx, new UsersInRoleSet(), new UsersInRole[] { uir });
     uir.UserID = u.ID;
     uir.RoleID = rid;
     await AddUserRoleHistory(uir, UserRoleOperations.Deleted);
     return new { ok = true, msg = "", available = new { id = rid, name = uir.RoleRef.RoleName, path = uir.RoleRef.DistinctString, op = true } };
 }
        public static async Task<string[]> LoadMessages(string peerId, string userId, int maxMessages, bool dialog)
        {
            var svc = new MembershipPlusServiceProxy();
            var usvc = new UserServiceProxy();
            var msgsvc = new ShortMessageServiceProxy();
            var cntx = Cntx;
            var peer = await usvc.LoadEntityByKeyAsync(cntx, peerId);
            DateTime dt = DateTime.UtcNow.AddMinutes(-InitMsgTimeWindow);
            var cond = new ShortMessageSetConstraints
            {
                ApplicationIDWrap = new ForeignKeyData<string> { KeyValue = AppId },
                TypeIDWrap = new ForeignKeyData<int> { KeyValue = 1 },
                GroupIDWrap = new ForeignKeyData<string> { KeyValue = null }
            };
            var qexpr = new QueryExpresion();
            qexpr.OrderTks = new List<QToken>(new QToken[] { 
                new QToken { TkName = "CreatedDate" },
                new QToken { TkName = "desc" }
            });
            //                ToIDWrap = new ForeignKeyData<string> { KeyValue = peerId },

            qexpr.FilterTks = new List<QToken>(new QToken[] {
                new QToken { TkName = "( FromID ==  \"" + peerId + "\" && ToID == \"" + userId + "\" || FromID ==  \"" + userId + "\" && ToID == \"" + peerId + "\" ) && 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, peer, dialog));
                }
            }
            return jsonMsgs.ToArray();
        }
        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<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[]> LoadMessages(string peerId, string userId, int maxMessages, bool dialog)
        {
            var svc    = new MembershipPlusServiceProxy();
            var usvc   = new UserServiceProxy();
            var msgsvc = new ShortMessageServiceProxy();
            var cntx   = Cntx;
            var peer   = await usvc.LoadEntityByKeyAsync(cntx, peerId);

            DateTime dt   = DateTime.UtcNow.AddMinutes(-InitMsgTimeWindow);
            var      cond = new ShortMessageSetConstraints
            {
                ApplicationIDWrap = new ForeignKeyData <string> {
                    KeyValue = AppId
                },
                TypeIDWrap = new ForeignKeyData <int> {
                    KeyValue = 1
                },
                GroupIDWrap = new ForeignKeyData <string> {
                    KeyValue = null
                }
            };
            var qexpr = new QueryExpresion();

            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "CreatedDate"
                },
                new QToken {
                    TkName = "desc"
                }
            });
            //                ToIDWrap = new ForeignKeyData<string> { KeyValue = peerId },

            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "( FromID ==  \"" + peerId + "\" && ToID == \"" + userId + "\" || FromID ==  \"" + userId + "\" && ToID == \"" + peerId + "\" ) && 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, peer, dialog));
                }
            }
            return(jsonMsgs.ToArray());
        }
 public static async Task LeaveUserMessage(string chatHubId, string userId, string peerId, string replyId, 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();
     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,
         IsNotReceived = true
     };
     await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });
     UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
     DateTime dt = DateTime.UtcNow;
     List<UserAssociation> lass = new List<UserAssociation>();
     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 = 0,
             LastAssoc = dt,
             InteractCount = 1,
             Votes = 0
         };
     }
     else
         utop.InteractCount++;
     lass.Add(utop);
     if (!string.IsNullOrEmpty(replyId))
     {
         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 = 0,
                 LastAssoc = dt,
                 InteractCount = 0,
                 Votes = 0
             };
         }
         else
             ptou.InteractCount++;
         lass.Add(ptou);
     }
     await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), lass.ToArray());
 }
 public async Task<ActionResult> ChangeAccountInfo(string returnUrl, ManageMessageId? message)
 {
     ViewBag.StatusMessage =
         message == ManageMessageId.ChangePasswordSuccess ? ResourceUtils.GetString("9bc75a1c6d94e70e8b96d8d59115c0c0", "Your password has been changed.")
         : message == ManageMessageId.SetPasswordSuccess ? ResourceUtils.GetString("9ad4e391b8ba2faf5177dcfa6dcee143", "Your password has been set.")
         : message == ManageMessageId.RemoveLoginSuccess ? ResourceUtils.GetString("9d813b903dbe8155105d3b5c4e6a04ed", "The external login was removed.")
         : message == ManageMessageId.Error ? ResourceUtils.GetString("c69732cc923305ac0684ac8fc05a4bcb", "An error has occurred.")
         : "";
     ViewBag.HasLocalPassword = HasPassword();
     ViewBag.ReturnUrl = string.IsNullOrEmpty(returnUrl) ? Url.Action("ChangeAccountInfo") : returnUrl;
     ChangeAccountInfoModel model = new ChangeAccountInfoModel();
     UserServiceProxy usvc = new UserServiceProxy();
     var cntx = Startup.ClientContext.CreateCopy();
     cntx.DirectDataAccess = true;
     var u = await usvc.LoadEntityByKeyAsync(cntx, User.Identity.GetUserId());
     model.FirstName = u.FirstName;
     model.LastName = u.LastName;
     var ci = User.Identity as System.Security.Claims.ClaimsIdentity;
     model.Email = (from d in ci.Claims where d.Type == Microsoft.IdentityModel.Claims.ClaimTypes.Email select d.Value).SingleOrDefault();
     return View(model);
 }
 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 };
 }