public static async Task<string> GetSetInfo(string adminId, string set) { EntitySetType type; JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) filter = sobj["setFilter"]; switch (type) { case EntitySetType.User: { var p = await GetMaxPriority(adminId); UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(Cntx, filter); RoleServiceProxy rsvc = new RoleServiceProxy(); var roles = await rsvc.QueryDatabaseAsync(Cntx, new RoleSet(), null); List<dynamic> rlist = new List<dynamic>(); foreach (var r in roles) { if (r.RolePriority <= p.Major) rlist.Add(new { id = r.ID, name = r.RoleName, path = r.DistinctString, op = true }); } JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters, roles = rlist.ToArray() }); return json; } } } return null; }
public async Task<string> GetSetInfo(string sourceId, string set) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) filter = sobj["setFilter"]; switch (type) { case EntitySetType.User: { UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } case EntitySetType.Role: { RoleServiceProxy svc = new RoleServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } } } return null; }
public async Task<string> GetNextSorterOps(string sourceId, string set, string sorters) { EntitySetType type; if (Enum.TryParse<EntitySetType>(set, out type)) { switch (type) { case EntitySetType.User: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<QToken>)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); System.IO.MemoryStream strm = new System.IO.MemoryStream(); byte[] sbf = System.Text.Encoding.UTF8.GetBytes(sorters); strm.Write(sbf, 0, sbf.Length); strm.Position = 0; var _sorters = ser1.ReadObject(strm) as List<QToken>; UserServiceProxy svc = new UserServiceProxy(); var result = await svc.GetNextSorterOpsAsync(ApplicationContext.ClientContext, _sorters); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } case EntitySetType.Role: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<QToken>)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); System.IO.MemoryStream strm = new System.IO.MemoryStream(); byte[] sbf = System.Text.Encoding.UTF8.GetBytes(sorters); strm.Write(sbf, 0, sbf.Length); strm.Position = 0; var _sorters = ser1.ReadObject(strm) as List<QToken>; RoleServiceProxy svc = new RoleServiceProxy(); var result = await svc.GetNextSorterOpsAsync(ApplicationContext.ClientContext, _sorters); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } case EntitySetType.MemberNotification: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<QToken>)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); System.IO.MemoryStream strm = new System.IO.MemoryStream(); byte[] sbf = System.Text.Encoding.UTF8.GetBytes(sorters); strm.Write(sbf, 0, sbf.Length); strm.Position = 0; var _sorters = ser1.ReadObject(strm) as List<QToken>; MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); var result = await svc.GetNextSorterOpsAsync(ApplicationContext.ClientContext, _sorters); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } } } return null; }
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); }
private void MainWindow_OnWindowClosing(object sender, CancelEventArgs e) { //sending logout request: UserServiceProxy.Logout(new LogoutRequest { UserName = AuthenticatedUser.Instance.UserName }); //shut down the application: App.Current.Shutdown(); }
private static void Main(string[] args) { var appSettings = ConfigurationManager.AppSettings; string hostUrl = appSettings["hostUrl"]; string userName = appSettings["userName"]; string password = appSettings["password"]; string acctId = appSettings["dataCenterId"]; UserServiceProxy proxy = new UserServiceProxy(); LoginInfo loginInfo = new LoginInfo { Username = userName, Password = password, Lcid = 2052, AcctID = acctId, LoginType = LoginType.NormalERPLogin }; proxy.HostURL = hostUrl; proxy.ValidateUser( hostUrl, loginInfo, result => { Console.WriteLine(result.IsSuccessByAPI ? "登录成功" : throw new Exception("登录失败" + result.Message)); }); Thread.Sleep(2000); MetadataServiceProxy metadataService = new MetadataServiceProxy { HostURL = hostUrl }; string objectId; bool isExist; do { Console.WriteLine("输入业务对象标识并回车"); objectId = Console.ReadLine(); isExist = metadataService.IsExistMetaObjectType(objectId); if (!isExist) { Console.WriteLine($"标识为{objectId}的业务对象不存在,请重新输入"); } }while (!isExist); FormMetadata formMetadata = metadataService.GetFormMetadata(objectId); string outputPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, formMetadata.SubSystemId + Path.DirectorySeparatorChar); Console.WriteLine($"开始生成业务对象{formMetadata.Name}的实体类"); ClassFileGenerator.GenerateClassFiles(formMetadata, outputPath); Console.WriteLine($"生成结束,文件路径:{outputPath}"); Console.ReadKey(); }
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 void UpdateUser() { Logger.LogNewMessage("Updating user data..", LogType.INFO); try { UserServiceProxy.UpdateUser(User.ID, User.Name, User.LastName); } catch (Exception e) { Logger.LogNewMessage($"Error occured updating user info. Error message {e.Message}", LogType.ERROR); } }
public static async Task<RolePriority> GetMaxPriority(User u) { UserServiceProxy usrv = new UserServiceProxy(); var l = await usrv.MaterializeAllUsersInRole_UserIDsAsync(Cntx, u); if (l == null || l.Count() == 0) return new RolePriority { Major = -1, Minor = -1 }; UsersInRoleServiceProxy uisvc = new UsersInRoleServiceProxy(); foreach (var ir in l) ir.RoleRef = uisvc.MaterializeRoleRef(Cntx, ir); var uir = (from d in l orderby d.RoleRef.RolePriority descending, d.SubPriority descending select d).First(); var roleids = (from d in l orderby d.RoleRef.RolePriority select d.RoleID).ToArray(); return new RolePriority { Major = uir.RoleRef.RolePriority, Minor = uir.SubPriority, RoleIds = roleids, MaxRole = uir.RoleRef }; }
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 <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 void RefreshUsersList() { Logger.LogNewMessage("Getting all users from server..", LogType.INFO); try { Users = new BindingList <User>(UserServiceProxy.GetAllUsers()); if (Users == null) { Users = new BindingList <User>(); } }catch (Exception e) { Logger.LogNewMessage($"Error occured getting all users. Error message {e.Message}", LogType.ERROR); } }
static void Main(string[] args) { var userServiceProxy = new UserServiceProxy(); var response = userServiceProxy.Login(new LoginRequest { UserName = "******", Password = "******" }); Console.WriteLine(response.IsSuccess + response.Message); foreach (var user in response.AllOtherUsers) { Console.WriteLine(user.UserName); } Console.ReadLine(); }
public void TestMethod1() { UserServiceProxy proxy = new UserServiceProxy(); // 引用Kingdee.BOS.ServiceFacade.KDServiceClient.dll proxy.HostURL = @"http://127.0.0.1/K3cloud/"; //k/3cloud地址 LoginInfo loginInfo = new LoginInfo(); loginInfo.Username = "******"; loginInfo.Password = "******"; loginInfo.Lcid = 2052; loginInfo.AcctID = "5c42b8435b2962"; //Context ctx = proxy.ValidateUser("", "5c42b8435b2962", "scy", "666666", 2052).Context; Context ctx = proxy.ValidateUser("http://127.0.0.1/K3cloud/", loginInfo).Context; //List<long> salerIds = CRMServiceHelper.getSalerPersonids(ctx, 101789); }
public async Task <string> GetSetInfo(string sourceId, string set) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse <EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) { filter = sobj["setFilter"]; } switch (type) { case EntitySetType.User: { UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } case EntitySetType.Role: { RoleServiceProxy svc = new RoleServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } case EntitySetType.MemberNotification: { MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } } } return(null); }
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; }
public static Context getContext(string UserName, string PassWord, int ICID, string DBID, string ServerUrl) { UserServiceProxy proxy = new UserServiceProxy(); // 引用Kingdee.BOS.ServiceFacade.KDServiceClient.dll proxy.HostURL = @"http://localhost/K3Cloud/"; //k/3cloud地址 LoginInfo logininfo = new LoginInfo(); logininfo.Username = UserName; logininfo.Password = PassWord; logininfo.Lcid = ICID; logininfo.AcctID = DBID; Context ctx = proxy.ValidateUser("http://localhost/K3Cloud/", logininfo).Context;//guid为业务数据中心dbid,可以去管理中心数据库查询一下t_bas_datacenter_l表查找,后面需要用户名和密码 return(ctx); }
public void SaveUserData(User user) { var userService = new UserServiceProxy(); var response = userService.SaveUser(user); if (!response.Contains("error", StringComparison.OrdinalIgnoreCase)) { return; } if (response.Contains("database", StringComparison.OrdinalIgnoreCase)) { throw new DatabaseException("Can't save user"); } else { throw new ApplicationException("Fialed to save user, unknown reason"); } }
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 <string> GetSetInfo(string adminId, string set) { EntitySetType type; JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; if (Enum.TryParse <EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) { filter = sobj["setFilter"]; } switch (type) { case EntitySetType.User: { var p = await GetMaxPriority(adminId); UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(Cntx, filter); RoleServiceProxy rsvc = new RoleServiceProxy(); var roles = await rsvc.QueryDatabaseAsync(Cntx, new RoleSet(), null); List <dynamic> rlist = new List <dynamic>(); foreach (var r in roles) { if (r.RolePriority <= p.Major) { rlist.Add(new { id = r.ID, name = r.RoleName, path = r.DistinctString, op = true }); } } JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters, roles = rlist.ToArray() }); return(json); } } } return(null); }
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 }); } } }
private async Task _getUserInRoleAsync(CallContext cctx, EntityAbs <Role> ra, List <string> usersinrole) { UserServiceProxy usvc = new UserServiceProxy(); QueryExpresion qexpr = new QueryExpresion(); qexpr.OrderTks = new List <QToken>(new QToken[] { new QToken { TkName = "Username" } }); qexpr.FilterTks = new List <QToken>(new QToken[] { new QToken { TkName = "UsersInRole." }, new QToken { TkName = "RoleID" }, new QToken { TkName = "==" }, new QToken { TkName = "" + ra.DataBehind.ID + "" } }); var users = await usvc.QueryDatabaseAsync(cctx, new UserSet(), qexpr); foreach (User u in users) { usersinrole.Add(u.Username); } if (ra.ChildEntities != null) { foreach (var c in ra.ChildEntities) { await _getUserInRoleAsync(cctx, c, usersinrole); } } }
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 <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<ShotMessageNotice> UpdateUserMessage(string noticeHubId, string chatHubId, string userId, string groupId, string msgId, string message) { var cntx = Cntx; UserGroupServiceProxy gsvc = new UserGroupServiceProxy(); var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId); ShortMessageServiceProxy msvc = new ShortMessageServiceProxy(); var msg = await msvc.LoadEntityByKeyAsync(cntx, msgId); if (msg == null || msg.FromID != userId) return null; if (msg.MsgText == message) return null; var now = DateTime.UtcNow; msg.MsgTitle = GetLeadText(message); msg.MsgText = message; msg.LastModified = now; await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg }); UserServiceProxy usvc = new UserServiceProxy(); var u = await usvc.LoadEntityByKeyAsync(cntx, userId); msg.User_FromID = u; UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy(); var cond = new UserGroupMemberSetConstraints { UserGroupIDWrap = new ForeignKeyData<string> { KeyValue = groupId } }; var qexpr = new QueryExpresion(); qexpr.OrderTks = new List<QToken>(new QToken[] { new QToken { TkName = "UserID" } }); qexpr.FilterTks = new List<QToken>(new QToken[] { new QToken { TkName = "SubscribedTo is not null && SubscribedTo == true" } }); var gmbs = await gmsvc.ConstraintQueryAsync(cntx, new UserGroupMemberSet(), cond, qexpr); List<MemberNotification> notices = new List<MemberNotification>(); List<MemberCallback> noteCbks = new List<MemberCallback>(); MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy(); string noticeMsg = "Group message by " + u.Username + " updated in " + g.DistinctString; MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy(); var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.NewMessageNoticeTypeId); foreach (var m in gmbs) { if (m.ActivityNotification.HasValue && m.ActivityNotification.Value) { var cb = await mcbsvc.LoadEntityByKeyAsync(cntx, groupId, noticeHubId, AppId, m.UserID); if (cb.ConnectionID != null && !cb.IsDisconnected) { cb.UserAppMemberRef = await mcbsvc.MaterializeUserAppMemberRefAsync(cntx, cb); noteCbks.Add(cb); } } notices.Add(new MemberNotification { ID = Guid.NewGuid().ToString(), Title = noticeMsg, CreatedDate = now, PriorityLevel = 0, ReadCount = 0, ApplicationID = AppId, TypeID = ApplicationContext.NewMessageNoticeTypeId, UserID = userId }); } var peers = await ListConnectIds(chatHubId, groupId); List<ShortMessageAudience> laud = new List<ShortMessageAudience>(); foreach (var peer in peers) { if (peer.UserID != userId) { var a = new ShortMessageAudience { MsgID = msg.ID, UserID = peer.UserID, VoteCount = 0 }; laud.Add(a); } } if (laud.Count > 0) { ShortMessageAudienceServiceProxy audsvc = new ShortMessageAudienceServiceProxy(); await audsvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageAudienceSet(), laud.ToArray()); } if (notices.Count > 0) { MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy(); await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), notices.ToArray()); } return new ShotMessageNotice { msg = GetJsonMessage(msg, userId, g, false), brief = noticeMsg, categ = ntype, peers = peers, callbacks = noteCbks }; }
public async Task <string> GetPageItems(string sourceId, string set, string qexpr, string prevlast) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse <EntitySetType>(sobj["set"], out type)) { switch (type) { case EntitySetType.User: { 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(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); var ar = new List <dynamic>(); foreach (var e in result) { ar.Add(new { Id = e.ID.ToString(), DistinctString = e.DistinctString }); } string json = ser3.Serialize(ar); return(json); } case EntitySetType.Role: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(Role)); 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; RoleServiceProxy svc = new RoleServiceProxy(); RoleSet _set = new RoleSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) { _set.SetFilter = sobj["setFilter"]; } Role _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 Role; } var result = await svc.GetPageItemsAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); var ar = new List <dynamic>(); foreach (var e in result) { ar.Add(new { Id = e.ID.ToString(), DistinctString = e.DistinctString }); } string json = ser3.Serialize(ar); return(json); } case EntitySetType.MemberNotification: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(MemberNotification)); 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; MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); MemberNotificationSet _set = new MemberNotificationSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) { _set.SetFilter = sobj["setFilter"]; } MemberNotification _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 MemberNotification; } var result = await svc.GetPageItemsAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); var ar = new List <dynamic>(); foreach (var e in result) { ar.Add(new { Id = e.ID.ToString(), DistinctString = e.DistinctString }); } string json = ser3.Serialize(ar); return(json); } } } return(null); }
public async Task <string> GetSetInfo(string sourceId, string set) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse <EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) { filter = sobj["setFilter"]; } switch (type) { case EntitySetType.User: { UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } case EntitySetType.Role: { RoleServiceProxy svc = new RoleServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } case EntitySetType.MemberNotification: { MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } case EntitySetType.ShortMessage: { if (filter == null) { throw new Exception("The page is not properly parameterized!"); } else { Func <string, string, int> count = (s, p) => { int _cnt = 0; int i = 0; while ((i = s.IndexOf(p, i)) != -1) { _cnt++; i += p.Length; } return(_cnt); }; if (filter.Contains("ToID is null") && filter.Contains("___usergroups___") && count(filter, "||") == 0) { string[] mbgrpIds = await GroupChatViewContext.UserGroupChatMembers(System.Web.HttpContext.Current.User.Identity.GetUserId()); if (mbgrpIds == null || mbgrpIds.Length == 0) { throw new Exception(ResourceUtils.GetString("234038e6185f013e25d0213c06f5a0e9", "You are not a member of any chat group.")); } string groupexpr = ""; foreach (var gid in mbgrpIds) { groupexpr += (groupexpr != "" ? " || " : "") + "GroupID == \"" + gid + "\""; } filter = filter.Replace("___usergroups___", groupexpr); } else if (filter.EndsWith("&& ToID is not null && GroupID is null && ( ToID == \"{0}\" || FromID == \"{0}\" )") && count(filter, "||") == 1) { filter = string.Format(filter, System.Web.HttpContext.Current.User.Identity.GetUserId()); } else { throw new Exception("The page is not properly parameterized!"); } } ShortMessageServiceProxy svc = new ShortMessageServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return(json); } } } return(null); }
public static async Task <dynamic> GetBriefMemberDetails(string id) { UserServiceProxy usvc = new UserServiceProxy(); // exclude all EntitySetType[] excludes = new EntitySetType[] { EntitySetType.Announcement, EntitySetType.EventCalendar, EntitySetType.MemberNotification, //EntitySetType.UserAppMember, EntitySetType.UserAssociation, EntitySetType.UserAssocInvitation, EntitySetType.UserGroupMember, EntitySetType.UserProfile, EntitySetType.UsersInRole, EntitySetType.UsersRoleHistory }; var cctx = Cntx; var graph = await usvc.LoadEntityGraphRecursAsync(cctx, id, excludes, null); var member = (from d in graph.ChangedUserAppMembers where d.ApplicationID == ApplicationContext.App.ID select d).Single(); var Details = (from d in graph.ChangedUserDetails where d.ApplicationID == ApplicationContext.App.ID select d).FirstOrDefault(); var Communications = (from d in graph.ChangedCommunications where d.ApplicationID == ApplicationContext.App.ID select d).ToArray(); dynamic obj = null; if (Details != null) { switch (Details.Gender) { case "M": Details.Gender = ResourceUtils.GetString("63889cfb9d3cbe05d1bd2be5cc9953fe", "Male"); break; case "F": Details.Gender = ResourceUtils.GetString("b719ce180ec7bd9641fece2f920f4818", "Female"); break; default: break; } obj = new { hasDetails = true, details = new { gender = Details.Gender, birthdate = Details.BirthDate, description = Details.Description, website = Details.WebsiteUrl, lastModified = Details.LastModified, hasPhoto = !string.IsNullOrEmpty(Details.PhotoMime) }, channels = new List <dynamic>() }; } else { obj = new { hasDetails = false, details = new {}, channels = new List <dynamic>() }; } SortedDictionary <int, List <Communication> > dic = new SortedDictionary <int, List <Communication> >(); foreach (var c in Communications) { List <Communication> l; if (!dic.TryGetValue(c.TypeID, out l)) { l = new List <Communication>(); dic.Add(c.TypeID, l); } l.Add(c); } if (!string.IsNullOrEmpty(member.Email)) { List <Communication> leml; if (!dic.TryGetValue(6, out leml) || leml.Count == 0) { leml = new List <Communication>(); leml.Add(new Communication { AddressInfo = member.Email }); dic.Add(6, leml); } else { if (!(from d in leml where d.AddressInfo.ToLower().Trim() == member.Email.ToLower().Trim() select d).Any()) { leml.Insert(0, new Communication { AddressInfo = member.Email }); } } } if (Details != null && !string.IsNullOrEmpty(Details.WebsiteUrl)) { List <Communication> leml; if (!dic.TryGetValue(9, out leml) || leml.Count == 0) { leml = new List <Communication>(); leml.Add(new Communication { AddressInfo = Details.WebsiteUrl }); dic.Add(9, leml); } else { if (!(from d in leml where d.AddressInfo.ToLower().Trim() == Details.WebsiteUrl.ToLower().Trim() select d).Any()) { leml.Insert(0, new Communication { AddressInfo = Details.WebsiteUrl }); } } } foreach (var kvp in dic) { string label = ""; switch (kvp.Key) { case 1: label = ResourceUtils.GetString("9c9d1674420681239f48d5fa8e181534", "Home Addresses"); break; case 2: label = ResourceUtils.GetString("a35ce85c83d755ca36c922000e529b42", "Work Addresses"); break; case 3: label = ResourceUtils.GetString("926206a444a6304c5989c7ac50696003", "Daytime Phone Numbers"); break; case 4: label = ResourceUtils.GetString("106f87b4378b7aa297f4790c212705cd", "Nighttime Phone Numbers"); break; case 5: label = ResourceUtils.GetString("701be5946aa3309654adceb89fef73e1", "Mobile Phone Numbers"); break; case 6: label = ResourceUtils.GetString("32948fb18d1ae027b936e2ed205f05b8", "E-Mail Addresses"); break; case 7: label = ResourceUtils.GetString("5cf3560c135befe2651d67f4b8d787e6", "Instant Message Addresses"); break; case 8: label = ResourceUtils.GetString("b3d34dcab5c7808cbfbf07208c680a87", "Voice Mail Addresses"); break; case 9: label = ResourceUtils.GetString("ed3ce4ec38212812ef687c8e69870530", "Website Addresses"); break; } dynamic ch = new { name = label, addresses = new List <dynamic>() }; foreach (var c in kvp.Value) { ch.addresses.Add(new { address = c.AddressInfo, comment = c.Comment }); } obj.channels.Add(ch); } return(obj); }
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<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<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 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 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> GetManagedUsers(string adminId, string set, string qexpr, string prevlast) { var maxp = await GetMaxPriority(adminId); JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse <EntitySetType>(sobj["set"], out type)) { switch (type) { case EntitySetType.User: { 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; } RoleServiceProxy rsvc = new RoleServiceProxy(); var roles = await rsvc.QueryDatabaseAsync(Cntx, new RoleSet(), null); 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) { List <Role> rlist = new List <Role>(); foreach (var r in roles) { if (r.RolePriority <= maxp.Major) { rlist.Add(r); } } var p = await GetMaxPriority(e); List <dynamic> rolelist = new List <dynamic>(); var _roles = await svc.MaterializeAllUsersInRole_UserIDsAsync(Cntx, e); dynamic _max = null; if (_roles != null) { List <UsersInRole> _rlist = new List <UsersInRole>(); foreach (var ir in _roles) { ir.RoleRef = uirsvc.MaterializeRoleRef(Cntx, ir); _rlist.Add(ir); } foreach (var ir in from d in _rlist orderby d.RoleRef.RolePriority descending, d.SubPriority descending select d) { bool op = adminId != e.ID && (ir.RoleRef.RolePriority < maxp.Major || ir.RoleRef.RolePriority == maxp.Major && ir.SubPriority <= maxp.Minor); var _r = new { id = ir.RoleRef.ID, uid = ir.UserID, name = ir.RoleRef.RoleName, path = Utils.GetHtmlRolePath(ir.RoleRef.DistinctString), level = ir.SubPriority, op = op }; if (ir.RoleRef.ID == p.MaxRole.ID) { _max = _r; } rolelist.Add(_r); int ptr = -1; for (int i = 0; i < rlist.Count; i++) { if (rlist[i].ID == ir.RoleRef.ID) { ptr = i; break; } } if (ptr != -1) { rlist.RemoveAt(ptr); } } } List <dynamic> availablers = new List <dynamic>(); //if (adminId != e.ID) { foreach (var r in rlist) { availablers.Add(new { id = r.ID, name = r.RoleName, path = Utils.GetHtmlRolePath(r.DistinctString), op = true }); } } var membs = svc.MaterializeAllUserAppMembers(Cntx, e); ar.Add(new { data = e, member = (from d in membs where d.ApplicationID == appId select d).SingleOrDefault(), roles = rolelist.ToArray(), maxrole = _max, availableRoles = availablers.ToArray(), CanEdit = p.IsLowerOrEqual(maxp) }); } string json = ser3.Serialize(ar); return(json); } } } return(null); }
public static async Task<dynamic> GetBriefMemberDetails(string id) { UserServiceProxy usvc = new UserServiceProxy(); // exclude all EntitySetType[] excludes = new EntitySetType[] { EntitySetType.Announcement, EntitySetType.EventCalendar, EntitySetType.MemberNotification, //EntitySetType.UserAppMember, EntitySetType.UserAssociation, EntitySetType.UserAssocInvitation, EntitySetType.UserGroupMember, EntitySetType.UserProfile, EntitySetType.UsersInRole, EntitySetType.UsersRoleHistory }; var cctx = Cntx; var graph = await usvc.LoadEntityGraphRecursAsync(cctx, id, excludes, null); var member = (from d in graph.ChangedUserAppMembers where d.ApplicationID == ApplicationContext.App.ID select d).Single(); var Details = (from d in graph.ChangedUserDetails where d.ApplicationID == ApplicationContext.App.ID select d).FirstOrDefault(); var Communications = (from d in graph.ChangedCommunications where d.ApplicationID == ApplicationContext.App.ID select d).ToArray(); dynamic obj = null; if (Details != null) { switch (Details.Gender) { case "M": Details.Gender = ResourceUtils.GetString("63889cfb9d3cbe05d1bd2be5cc9953fe", "Male"); break; case "F": Details.Gender = ResourceUtils.GetString("b719ce180ec7bd9641fece2f920f4818", "Female"); break; default : break; } obj = new { hasDetails = true, details = new { gender = Details.Gender, birthdate = Details.BirthDate, description = Details.Description, website = Details.WebsiteUrl, lastModified = Details.LastModified, hasPhoto = !string.IsNullOrEmpty(Details.PhotoMime) }, channels = new List<dynamic>() }; } else { obj = new { hasDetails = false, details = new {}, channels = new List<dynamic>() }; } SortedDictionary<int, List<Communication>> dic = new SortedDictionary<int, List<Communication>>(); foreach (var c in Communications) { List<Communication> l; if (!dic.TryGetValue(c.TypeID, out l)) { l = new List<Communication>(); dic.Add(c.TypeID, l); } l.Add(c); } if (!string.IsNullOrEmpty(member.Email)) { List<Communication> leml; if (!dic.TryGetValue(6, out leml) || leml.Count == 0) { leml = new List<Communication>(); leml.Add(new Communication { AddressInfo = member.Email }); dic.Add(6, leml); } else { if (!(from d in leml where d.AddressInfo.ToLower().Trim() == member.Email.ToLower().Trim() select d).Any()) leml.Insert(0, new Communication { AddressInfo = member.Email }); } } if (Details != null && !string.IsNullOrEmpty(Details.WebsiteUrl)) { List<Communication> leml; if (!dic.TryGetValue(9, out leml) || leml.Count == 0) { leml = new List<Communication>(); leml.Add(new Communication { AddressInfo = Details.WebsiteUrl }); dic.Add(9, leml); } else { if (!(from d in leml where d.AddressInfo.ToLower().Trim() == Details.WebsiteUrl.ToLower().Trim() select d).Any()) leml.Insert(0, new Communication { AddressInfo = Details.WebsiteUrl }); } } foreach (var kvp in dic) { string label = ""; switch(kvp.Key) { case 1: label = ResourceUtils.GetString("9c9d1674420681239f48d5fa8e181534", "Home Addresses"); break; case 2: label = ResourceUtils.GetString("a35ce85c83d755ca36c922000e529b42", "Work Addresses"); break; case 3: label = ResourceUtils.GetString("926206a444a6304c5989c7ac50696003", "Daytime Phone Numbers"); break; case 4: label = ResourceUtils.GetString("106f87b4378b7aa297f4790c212705cd", "Nighttime Phone Numbers"); break; case 5: label = ResourceUtils.GetString("701be5946aa3309654adceb89fef73e1", "Mobile Phone Numbers"); break; case 6: label = ResourceUtils.GetString("32948fb18d1ae027b936e2ed205f05b8", "E-Mail Addresses"); break; case 7: label = ResourceUtils.GetString("5cf3560c135befe2651d67f4b8d787e6", "Instant Message Addresses"); break; case 8: label = ResourceUtils.GetString("b3d34dcab5c7808cbfbf07208c680a87", "Voice Mail Addresses"); break; case 9: label = ResourceUtils.GetString("ed3ce4ec38212812ef687c8e69870530", "Website Addresses"); break; } dynamic ch = new { name = label, addresses = new List<dynamic>() }; foreach (var c in kvp.Value) { ch.addresses.Add(new { address = c.AddressInfo, comment = c.Comment }); } obj.channels.Add(ch); } return obj; }
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> AdjustUserRoleLevel(string adminId, string uid, int rid, int del) { var maxp = await MemberAdminContext.GetMaxPriority(adminId); UserServiceProxy usvc = new UserServiceProxy(); var u = usvc.LoadEntityByKey(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 + del > maxp.Major) return new { ok = false, msg = ResourceUtils.GetString("5986d63fe301793ee7f5b2134a8f8787", "Modifying more priviledged role is not authorized.") }; 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); return new { ok = true, msg = "" }; }
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<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 <ShotMessageNotice> UpdateUserMessage(string noticeHubId, string chatHubId, string userId, string groupId, string msgId, string message) { var cntx = Cntx; UserGroupServiceProxy gsvc = new UserGroupServiceProxy(); var g = await gsvc.LoadEntityByKeyAsync(cntx, groupId); ShortMessageServiceProxy msvc = new ShortMessageServiceProxy(); var msg = await msvc.LoadEntityByKeyAsync(cntx, msgId); if (msg == null || msg.FromID != userId) { return(null); } if (msg.MsgText == message) { return(null); } var now = DateTime.UtcNow; msg.MsgTitle = GetLeadText(message); msg.MsgText = message; msg.LastModified = now; await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg }); UserServiceProxy usvc = new UserServiceProxy(); var u = await usvc.LoadEntityByKeyAsync(cntx, userId); msg.User_FromID = u; UserGroupMemberServiceProxy gmsvc = new UserGroupMemberServiceProxy(); var cond = new UserGroupMemberSetConstraints { UserGroupIDWrap = new ForeignKeyData <string> { KeyValue = groupId } }; var qexpr = new QueryExpresion(); qexpr.OrderTks = new List <QToken>(new QToken[] { new QToken { TkName = "UserID" } }); qexpr.FilterTks = new List <QToken>(new QToken[] { new QToken { TkName = "SubscribedTo is not null && SubscribedTo == true" } }); var gmbs = await gmsvc.ConstraintQueryAsync(cntx, new UserGroupMemberSet(), cond, qexpr); List <MemberNotification> notices = new List <MemberNotification>(); List <MemberCallback> noteCbks = new List <MemberCallback>(); MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy(); string noticeMsg = "Group message by " + u.Username + " updated in " + g.DistinctString; MemberNotificationTypeServiceProxy ntsvc = new MemberNotificationTypeServiceProxy(); var ntype = await ntsvc.LoadEntityByKeyAsync(cntx, ApplicationContext.NewMessageNoticeTypeId); foreach (var m in gmbs) { if (m.ActivityNotification.HasValue && m.ActivityNotification.Value) { var cb = await mcbsvc.LoadEntityByKeyAsync(cntx, groupId, noticeHubId, AppId, m.UserID); if (cb.ConnectionID != null && !cb.IsDisconnected) { cb.UserAppMemberRef = await mcbsvc.MaterializeUserAppMemberRefAsync(cntx, cb); noteCbks.Add(cb); } } notices.Add(new MemberNotification { ID = Guid.NewGuid().ToString(), Title = noticeMsg, CreatedDate = now, PriorityLevel = 0, ReadCount = 0, ApplicationID = AppId, TypeID = ApplicationContext.NewMessageNoticeTypeId, UserID = userId }); } var peers = await ListConnectIds(chatHubId, groupId); List <ShortMessageAudience> laud = new List <ShortMessageAudience>(); foreach (var peer in peers) { if (peer.UserID != userId) { var a = new ShortMessageAudience { MsgID = msg.ID, UserID = peer.UserID, VoteCount = 0 }; laud.Add(a); } } if (laud.Count > 0) { ShortMessageAudienceServiceProxy audsvc = new ShortMessageAudienceServiceProxy(); await audsvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageAudienceSet(), laud.ToArray()); } if (notices.Count > 0) { MemberNotificationServiceProxy nsvc = new MemberNotificationServiceProxy(); await nsvc.AddOrUpdateEntitiesAsync(cntx, new MemberNotificationSet(), notices.ToArray()); } return(new ShotMessageNotice { msg = GetJsonMessage(msg, userId, g, false), brief = noticeMsg, categ = ntype, peers = peers, callbacks = noteCbks }); }
public static async Task<dynamic> 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 async Task <string> GetNextFilterOps(string sourceId, string set, string qexpr) { EntitySetType type; if (Enum.TryParse <EntitySetType>(set, out type)) { switch (type) { case EntitySetType.User: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); 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(); var result = await svc.GetNextFilterOpsAsync(ApplicationContext.ClientContext, _qexpr, ""); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } case EntitySetType.Role: { var ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); var ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); 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; RoleServiceProxy svc = new RoleServiceProxy(); var result = await svc.GetNextFilterOpsAsync(ApplicationContext.ClientContext, _qexpr, ""); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } case EntitySetType.MemberNotification: { var ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); var ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); 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; MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); var result = await svc.GetNextFilterOpsAsync(ApplicationContext.ClientContext, _qexpr, ""); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } case EntitySetType.ShortMessage: { var ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); var ser2 = new DataContractJsonSerializer(typeof(TokenOptions)); 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; var svc = new ShortMessageServiceProxy(); var result = await svc.GetNextFilterOpsAsync(ApplicationContext.ClientContext, _qexpr, ""); strm = new System.IO.MemoryStream(); ser2.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } } } 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 async Task <string> NextPageBlock(string sourceId, string set, string qexpr, string prevlast) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse <EntitySetType>(sobj["set"], out type)) { switch (type) { case EntitySetType.User: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(User)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(UserPageBlock)); 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.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } case EntitySetType.Role: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(Role)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(RolePageBlock)); 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; RoleServiceProxy svc = new RoleServiceProxy(); RoleSet _set = new RoleSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) { _set.SetFilter = sobj["setFilter"]; } Role _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 Role; } var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } case EntitySetType.MemberNotification: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(MemberNotification)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(MemberNotificationPageBlock)); 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; MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); MemberNotificationSet _set = new MemberNotificationSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) { _set.SetFilter = sobj["setFilter"]; } MemberNotification _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 MemberNotification; } var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } case EntitySetType.ShortMessage: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(ShortMessage)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(ShortMessagePageBlock)); 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; var svc = new ShortMessageServiceProxy(); var _set = new ShortMessageSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (!sobj.ContainsKey("setFilter")) { throw new Exception("The page is not properly parameterized!"); } else { Func <string, string, int> count = (s, p) => { int _cnt = 0; int i = 0; while ((i = s.IndexOf(p, i)) != -1) { _cnt++; i += p.Length; } return(_cnt); }; string filter = sobj["setFilter"]; if (filter.Contains("ToID is null") && filter.Contains("___usergroups___") && count(filter, "||") == 0) { string[] mbgrpIds = await GroupChatViewContext.UserGroupChatMembers(System.Web.HttpContext.Current.User.Identity.GetUserId()); if (mbgrpIds == null || mbgrpIds.Length == 0) { throw new Exception(ResourceUtils.GetString("234038e6185f013e25d0213c06f5a0e9", "You are not a member of any chat group.")); } string groupexpr = ""; foreach (var gid in mbgrpIds) { groupexpr += (groupexpr != "" ? " || " : "") + "GroupID == \"" + gid + "\""; } _set.SetFilter = filter.Replace("___usergroups___", groupexpr); } else if (filter.EndsWith("&& ToID is not null && GroupID is null && ( ToID == \"{0}\" || FromID == \"{0}\" )") && count(filter, "||") == 1) { filter = string.Format(filter, System.Web.HttpContext.Current.User.Identity.GetUserId()); _set.SetFilter = filter; } else { throw new Exception("The page is not properly parameterized!"); } } ShortMessage _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 ShortMessage; } var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return(json); } } } return(null); }
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<dynamic> LoadRoomSummary(string hubId, string id) { UserGroupServiceProxy gsvc = new UserGroupServiceProxy(); var cntx = Cntx; string descr = await gsvc.LoadEntityGroupDescriptionAsync(cntx, id); MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy(); var qexpr = getConnectedGroupMemberFilter(hubId, id); long cnt = await mcbsvc.QueryEntityCountAsync(cntx, new MemberCallbackSet(), qexpr); UserGroupMemberServiceProxy uigsvc = new UserGroupMemberServiceProxy(); qexpr = new QueryExpresion(); qexpr.OrderTks = new List<QToken>(new QToken[] { new QToken { TkName = "UserID" } }); qexpr.FilterTks = new List<QToken>(new QToken[] { new QToken { TkName = "UserGroupID == \"" + id + "\" && SubscribedTo is not null && SubscribedTo == true" } }); long scnt = await uigsvc.QueryEntityCountAsync(cntx, new UserGroupMemberSet(), qexpr); qexpr = new QueryExpresion(); qexpr.OrderTks = new List<QToken>(new QToken[] { new QToken { TkName = "Username" } }); qexpr.FilterTks = new List<QToken>(new QToken[] { new QToken { TkName = "UsersInRole_UserID.RoleRef.UserGroupAdminRole.GroupID == \"" + id + "\"" } }); UserServiceProxy usvc = new UserServiceProxy(); var admins = await usvc.QueryDatabaseAsync(cntx, new UserSet(), qexpr); List<dynamic> ladms = new List<dynamic>(); if (admins.Count() > 0) { RoleServiceProxy rsvc = new RoleServiceProxy(); foreach (var u in admins) { qexpr = new QueryExpresion(); qexpr.OrderTks = new List<QToken>(new QToken[] { new QToken { TkName = "ID" } }); qexpr.FilterTks = new List<QToken>(new QToken[] { new QToken { TkName = "UserGroupAdminRole.GroupID == \"" + id + "\" && UsersInRole.UserID == \"" + u.ID + "\"" } }); var role = (await rsvc.QueryDatabaseAsync(cntx, new RoleSet(), qexpr)).First(); ladms.Add(new { id = u.ID, name = u.Username, role = role.DisplayName }); } } dynamic r = new { descr = descr, active = cnt, subscribers = scnt, admins = ladms }; return r; }
public async Task<string> GetSetInfo(string sourceId, string set) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { string filter = null; if (sobj.ContainsKey("setFilter")) filter = sobj["setFilter"]; switch (type) { case EntitySetType.User: { UserServiceProxy svc = new UserServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } case EntitySetType.Role: { RoleServiceProxy svc = new RoleServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } case EntitySetType.MemberNotification: { MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } case EntitySetType.ShortMessage: { if (filter == null) throw new Exception("The page is not properly parameterized!"); else { Func<string, string, int> count = (s, p) => { int _cnt = 0; int i = 0; while ((i = s.IndexOf(p, i)) != -1) { _cnt++; i += p.Length; } return _cnt; }; if (filter.Contains("ToID is null") && filter.Contains("___usergroups___") && count(filter, "||") == 0) { string[] mbgrpIds = await GroupChatViewContext.UserGroupChatMembers(System.Web.HttpContext.Current.User.Identity.GetUserId()); if (mbgrpIds == null || mbgrpIds.Length == 0) throw new Exception(ResourceUtils.GetString("234038e6185f013e25d0213c06f5a0e9", "You are not a member of any chat group.")); string groupexpr = ""; foreach (var gid in mbgrpIds) groupexpr += (groupexpr != "" ? " || " : "") + "GroupID == \"" + gid + "\""; filter = filter.Replace("___usergroups___", groupexpr); } else if (filter.EndsWith("&& ToID is not null && GroupID is null && ( ToID == \"{0}\" || FromID == \"{0}\" )") && count(filter, "||") == 1) { filter = string.Format(filter, System.Web.HttpContext.Current.User.Identity.GetUserId()); } else throw new Exception("The page is not properly parameterized!"); } ShortMessageServiceProxy svc = new ShortMessageServiceProxy(); var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter); JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters }); return json; } } } return null; }
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 async Task<string> GetPageItems(string sourceId, string set, string qexpr, string prevlast) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { switch (type) { case EntitySetType.User: { 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(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); var ar = new List<dynamic>(); foreach (var e in result) { ar.Add(new { Id = e.ID.ToString(), DistinctString = e.DistinctString }); } string json = ser3.Serialize(ar); return json; } case EntitySetType.Role: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(Role)); 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; RoleServiceProxy svc = new RoleServiceProxy(); RoleSet _set = new RoleSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) _set.SetFilter = sobj["setFilter"]; Role _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 Role; } var result = await svc.GetPageItemsAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); var ar = new List<dynamic>(); foreach (var e in result) { ar.Add(new { Id = e.ID.ToString(), DistinctString = e.DistinctString }); } string json = ser3.Serialize(ar); return json; } case EntitySetType.MemberNotification: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(MemberNotification)); 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; MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); MemberNotificationSet _set = new MemberNotificationSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) _set.SetFilter = sobj["setFilter"]; MemberNotification _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 MemberNotification; } var result = await svc.GetPageItemsAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); var ar = new List<dynamic>(); foreach (var e in result) { ar.Add(new { Id = e.ID.ToString(), DistinctString = e.DistinctString }); } string json = ser3.Serialize(ar); return json; } } } 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<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 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<string> GetManagedUsers(string adminId, string set, string qexpr, string prevlast) { var maxp = await GetMaxPriority(adminId); JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { switch (type) { case EntitySetType.User: { 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; } RoleServiceProxy rsvc = new RoleServiceProxy(); var roles = await rsvc.QueryDatabaseAsync(Cntx, new RoleSet(), null); 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) { List<Role> rlist = new List<Role>(); foreach (var r in roles) { if (r.RolePriority <= maxp.Major) rlist.Add(r); } var p = await GetMaxPriority(e); List<dynamic> rolelist = new List<dynamic>(); var _roles = await svc.MaterializeAllUsersInRole_UserIDsAsync(Cntx, e); dynamic _max = null; if (_roles != null) { List<UsersInRole> _rlist = new List<UsersInRole>(); foreach (var ir in _roles) { ir.RoleRef = uirsvc.MaterializeRoleRef(Cntx, ir); _rlist.Add(ir); } foreach (var ir in from d in _rlist orderby d.RoleRef.RolePriority descending, d.SubPriority descending select d) { bool op = adminId != e.ID && (ir.RoleRef.RolePriority < maxp.Major || ir.RoleRef.RolePriority == maxp.Major && ir.SubPriority <= maxp.Minor); var _r = new { id = ir.RoleRef.ID, uid = ir.UserID, name = ir.RoleRef.RoleName, path = Utils.GetHtmlRolePath(ir.RoleRef.DistinctString), level = ir.SubPriority, op = op }; if (ir.RoleRef.ID == p.MaxRole.ID) _max = _r; rolelist.Add(_r); int ptr = -1; for (int i = 0; i < rlist.Count; i++) { if (rlist[i].ID == ir.RoleRef.ID) { ptr = i; break; } } if (ptr != -1) rlist.RemoveAt(ptr); } } List<dynamic> availablers = new List<dynamic>(); //if (adminId != e.ID) { foreach (var r in rlist) availablers.Add(new { id = r.ID, name = r.RoleName, path = Utils.GetHtmlRolePath(r.DistinctString), op = true }); } var membs = svc.MaterializeAllUserAppMembers(Cntx, e); ar.Add(new { data = e, member = (from d in membs where d.ApplicationID == appId select d).SingleOrDefault(), roles = rolelist.ToArray(), maxrole = _max, availableRoles = availablers.ToArray(), CanEdit = p.IsLowerOrEqual(maxp) }); } string json = ser3.Serialize(ar); return json; } } } return null; }
public async Task<string> NextPageBlock(string sourceId, string set, string qexpr, string prevlast) { JavaScriptSerializer jser = new JavaScriptSerializer(); dynamic sobj = jser.DeserializeObject(set) as dynamic; EntitySetType type; if (Enum.TryParse<EntitySetType>(sobj["set"], out type)) { switch (type) { case EntitySetType.User: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(User)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(UserPageBlock)); 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.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } case EntitySetType.Role: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(Role)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(RolePageBlock)); 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; RoleServiceProxy svc = new RoleServiceProxy(); RoleSet _set = new RoleSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) _set.SetFilter = sobj["setFilter"]; Role _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 Role; } var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } case EntitySetType.MemberNotification: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(MemberNotification)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(MemberNotificationPageBlock)); 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; MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy(); MemberNotificationSet _set = new MemberNotificationSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (sobj.ContainsKey("setFilter")) _set.SetFilter = sobj["setFilter"]; MemberNotification _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 MemberNotification; } var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } case EntitySetType.ShortMessage: { DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion)); DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(ShortMessage)); DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(ShortMessagePageBlock)); 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; var svc = new ShortMessageServiceProxy(); var _set = new ShortMessageSet(); _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]); _set.PageSize_ = int.Parse(sobj["pageSize"]); if (!sobj.ContainsKey("setFilter")) throw new Exception("The page is not properly parameterized!"); else { Func<string, string, int> count = (s, p) => { int _cnt = 0; int i = 0; while ((i = s.IndexOf(p, i)) != -1) { _cnt++; i += p.Length; } return _cnt; }; string filter = sobj["setFilter"]; if (filter.Contains("ToID is null") && filter.Contains("___usergroups___") && count(filter, "||") == 0) { string[] mbgrpIds = await GroupChatViewContext.UserGroupChatMembers(System.Web.HttpContext.Current.User.Identity.GetUserId()); if (mbgrpIds == null || mbgrpIds.Length == 0) throw new Exception(ResourceUtils.GetString("234038e6185f013e25d0213c06f5a0e9", "You are not a member of any chat group.")); string groupexpr = ""; foreach (var gid in mbgrpIds) groupexpr += (groupexpr != "" ? " || " : "") + "GroupID == \"" + gid + "\""; _set.SetFilter = filter.Replace("___usergroups___", groupexpr); } else if (filter.EndsWith("&& ToID is not null && GroupID is null && ( ToID == \"{0}\" || FromID == \"{0}\" )") && count(filter, "||") == 1) { filter = string.Format(filter, System.Web.HttpContext.Current.User.Identity.GetUserId()); _set.SetFilter = filter; } else throw new Exception("The page is not properly parameterized!"); } ShortMessage _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 ShortMessage; } var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast); strm = new System.IO.MemoryStream(); ser3.WriteObject(strm, result); string json = System.Text.Encoding.UTF8.GetString(strm.ToArray()); return json; } } } return null; }
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<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<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(); }