public UserGroupModel(UserGroup ug) { Id = ug.Id; Name = ug.Name; Remark = ug.Remarks; Roles = ug.GetAllRoles().ToArray(); }
public void SetUp() { Logger.Info("...begin setup..."); using (var session = CreateSession()) using (var transaction = session.BeginTransaction()) { _user1 = new UserBuilder().WithUserName("u1").Build(); _user2 = new UserBuilder().WithUserName("u2").Build(); _userGroup1 = new UserGroupBuilder().WithName("g1").Build(); _userGroup2 = new UserGroupBuilder().WithName("g2").Build(); _user1.AddUserGroup(_userGroup1); _user1.AddUserGroup(_userGroup2); _user2.AddUserGroup(_userGroup1); _user2.AddUserGroup(_userGroup2); session.Save(_user1); session.Save(_user2); session.Save(_userGroup1); session.Save(_userGroup2); session.Flush(); session.Clear(); // make sure everything is present in the cache for the tests session.QueryOver<User>().List(); session.QueryOver<UserGroup>().List(); transaction.Commit(); } Logger.Info("...end setup..."); }
public vUserGroup(UserGroup group) { DB db = new DB(); this.ID = group.ID; this.GroupName = group.GroupName; this.LoginName = group.LoginName; this.LoginPassword = group.LoginPassword; this.Email = group.Email; this.Phone = group.Phone; this.Address = group.Address; this.AddTime = group.AddTime; this.Weibo = group.Weibo; this.WhatApp = group.WhatApp; this.Description = group.Description; this.LastLogin = group.LastLoginTime; this.City = group.City; this.Picture = group.Picture; this.Priority = group.Priority; this.Industry = group.Industry; this.TodayPV = group.TodayPV; this.PV = group.PV; this.Downs = group.Downs; this.Ups = group.Ups; this.Images = db.Images.Where(c => c.TID == group.ID).Where(c => c.ImageType == ImageType.UserGroup).ToList(); this.IsVerified = group.IsVerified; }
public User(int id, string code, bool blocked, UserGroup userGroup) { Id = id; Code = code; Blocked = blocked; Group = userGroup; }
///<summary>Inserts one UserGroup into the database. Returns the new priKey.</summary> internal static long Insert(UserGroup userGroup) { if(DataConnection.DBtype==DatabaseType.Oracle) { userGroup.UserGroupNum=DbHelper.GetNextOracleKey("usergroup","UserGroupNum"); int loopcount=0; while(loopcount<100){ try { return Insert(userGroup,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ userGroup.UserGroupNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(userGroup,false); } }
public vCurrentUser(UserGroup model) { this.ID = model.ID; this.CurrentName = model.GroupName; this.UserType = UserType.UserGroup; this.Show = "/UserGroup/Show/" + model.ID; }
private bool Combine(ArrayList groups, int binsize) { bool workdone=false; int i; for (i = 1; i < groups.Count; i++) { UserGroup right = (UserGroup) groups[i]; UserGroup left = (UserGroup) groups[i-1]; //Can combine if (right.Users.Count + left.Users.Count <= binsize) { workdone=true; UserGroup combine = new UserGroup(); combine.UpperBound = left.UpperBound; combine.LowerBound = right.LowerBound; combine.Users.AddRange(left.Users); combine.Users.AddRange(right.Users); groups.Remove(right); groups.Remove(left); groups.Insert(i-1, combine); i--; } } return workdone; }
/// <summary> /// Sets the default permissions for the administrators group, properly importing version 2.0 values. /// </summary> /// <param name="administrators">The administrators group.</param> /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns> public static bool SetAdministratorsGroupDefaultPermissions(UserGroup administrators) { // Administrators can do any operation return AuthWriter.SetPermissionForGlobals(AuthStatus.Grant, Actions.FullControl, administrators); // Settings.ConfigVisibleToAdmins is not imported on purpose }
// PUT api/UserGroups/5 public HttpResponseMessage PutUserGroup(int id, UserGroup usergroup) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != usergroup.Id) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(usergroup).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public static UserGroup getById(int id, String connString) { UserGroup usergroup = new UserGroup(); usergroup.Id = id; using (SqlConnection conn = new SqlConnection(connString)) { try { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "sony_sp_get_user_group_by_id"; cmd.Parameters.AddWithValue("@id", id); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { usergroup.Id = (int)reader["id"]; usergroup.GroupName = reader["groupname"].ToString(); usergroup.IsSuper = reader["issuper"].ToString().Equals("1") || reader["issuper"].ToString().Equals("True") ? true : false; usergroup.Created = (DateTime)reader["created"]; usergroup.Updated = (DateTime)reader["updated"]; } } } } catch (Exception ex) { return new UserGroup(); } } return usergroup; }
/// <summary> /// Sets the default permissions for the anonymous users group, properly importing version 2.0 values. /// </summary> /// <param name="anonymous">The anonymous users group.</param> /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns> public static bool SetAnonymousGroupDefaultPermissions(UserGroup anonymous) { bool done = true; // Properly import Private/Public Mode wiki if(Settings.PrivateAccess) { // Nothing to do, because without any explicit grant, Anonymous users cannot do anything } else if(Settings.PublicAccess) { // Public access, allow modification and propagate file management permissions if they were allowed for anonymous users done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.ModifyPages, anonymous); done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.DownloadAttachments, anonymous); if(Settings.UsersCanCreateNewPages) { done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.CreatePages, anonymous); } if(Settings.UsersCanCreateNewCategories || Settings.UsersCanManagePageCategories) { done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.ManageCategories, anonymous); } if(Settings.FileManagementInPublicAccessAllowed) { SetupFileManagementPermissions(anonymous); } } else { // Standard configuration, only allow read permissions done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.ReadPages, anonymous); done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.ReadDiscussion, anonymous); done &= AuthWriter.SetPermissionForNamespace(AuthStatus.Grant, null, Actions.ForNamespaces.DownloadAttachments, anonymous); foreach(IFilesStorageProviderV30 prov in Collectors.FilesProviderCollector.AllProviders) { done &= AuthWriter.SetPermissionForDirectory(AuthStatus.Grant, prov, "/", Actions.ForDirectories.DownloadFiles, anonymous); } } return done; }
public void MatchRepositoryLoadMatchesListByUserRequest() { UserGroup group=new UserGroup{Id = 1,Name = "Pune"}; User traveller = new User(new Email("*****@*****.**"), null, "password", group); User requestor = new User(new Email("*****@*****.**"), null, "password", group); Package package = new Package("Package", "Weight", "Dimensions"); Location origin = new Location("Origin", new TravelDate(DateTime.Today)); Location destination = new Location("Destination", new TravelDate(DateTime.Today.AddDays(1))); Journey journey = new Journey(traveller, origin, destination); Request request = new Request(requestor, package, origin, destination); UserRepository.Instance.SaveUser(traveller); UserRepository.Instance.SaveUser(requestor); RequestRepository.Instance.Save(request); JourneyRepository.Instance.Save(journey); Match match = new Match(journey, request); IMatchRepository repository = MatchRepository.Instance; IList<Match> matchList = repository.LoadMatchesByUserRequest("*****@*****.**"); try { Assert.AreEqual(1, matchList.Count); } finally { repository.Delete(match); } }
public InsertResult Insert(UserGroup userGroup, Guid userId) { try { userGroup.Id = Guid.NewGuid(); userGroup.LastUpdate = DateTime.Now; UserGroupDb.Insert ( userGroup.Id, userGroup.Description, userGroup.Currency_Code, userGroup.BackOfficeGroup ); return new InsertResult(); } catch (SqlException ex) { var entityError = new List<EntityError>(); entityError.Add(new EntityError("UserGroup", "Insert", ex.Message)); Logger.Instance.Log.ErrorException("Insert Delete", ex); return new InsertResult(entityError); } }
public static bool addUserGroup(UserGroup userGroup, String connString) { bool rs = false; using (SqlConnection conn = new SqlConnection(connString)) { try { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "sony_sp_add_user_group"; cmd.Parameters.AddWithValue("@groupname", userGroup.GroupName); cmd.Parameters.AddWithValue("@issuper", userGroup.IsSuper ? 1 : 0); cmd.Parameters.AddWithValue("@created", userGroup.Created); cmd.Parameters.AddWithValue("@updated", userGroup.Updated); SqlParameter returnVal = new SqlParameter("@indentity", SqlDbType.Int); returnVal.Direction = ParameterDirection.Output; cmd.Parameters.Add(returnVal); cmd.ExecuteNonQuery(); rs = ((int)cmd.Parameters["@indentity"].Value != 0); } } catch (Exception ex) { return false; } } return rs; }
/// <summary> /// Add a new entry to one of the dropdown tables in the database. /// </summary> /// <param name="table">Table to add a new entry to.</param> /// <param name="entry"> /// DropdownEntry containing the value and code, /// if exists. /// </param> public void addEntry(Constants.DropdownTable table, DropdownEntry entry) { switch (table) { case Constants.DropdownTable.Keyword: var kw = new Keyword { KeywordValue = entry.value }; _db.Keywords.InsertOnSubmit(kw); break; case Constants.DropdownTable.QuestionType: var qType = new QuestionType { Code = entry.code, Value = entry.value }; _db.QuestionTypes.InsertOnSubmit(qType); break; case Constants.DropdownTable.Region: var region = new Region { Code = entry.code, Value = entry.value }; _db.Regions.InsertOnSubmit(region); break; case Constants.DropdownTable.RequestorType: var rType = new RequestorType { Code = entry.code, Value = entry.value }; _db.RequestorTypes.InsertOnSubmit(rType); break; case Constants.DropdownTable.TumourGroup: var tGroup = new TumourGroup { Code = entry.code, Value = entry.value }; _db.TumourGroups.InsertOnSubmit(tGroup); break; case Constants.DropdownTable.UserGroup: var uGroup = new UserGroup { Code = entry.code, Value = entry.value }; _db.UserGroups.InsertOnSubmit(uGroup); break; } _db.SubmitChanges(); }
public vPwdEdit(UserGroup group) { this.ID = group.ID; this.GroupName = group.GroupName; this.Picture = group.Picture; this.Password = group.LoginPassword; }
public void Should_return_true_for_single_monitor() { var someGroup = new UserGroup(null,null,"ShouldFind"); var userGroup = new UserGroups(buildCollection); userGroup.Add(someGroup); Assert.That(userGroup.IsMonitoring("ShouldFind"), Is.EqualTo(true)); }
public bool IsUserGroupInReaderGroup(UserGroup userGroup, ReaderGroup readerGroup) { var query = GenerateQuery(new Guid("{F8EB1766-410A-4C38-9435-1C316956CAF3}"), userGroup.ItemId, readerGroup.ItemId); var content = ExecScalar<int>(query); var result = content == 1; return result; }
public bool CreateUserGroup(UserGroup usergroup) { var query = GenerateQuery(new Guid("{70DA19EA-1064-459E-93B0-695E68D544C5}"), usergroup.ItemId, usergroup.FriendlyName); var result = ExecChangeLineQuery(query); return result; }
public void Should_send_message_to_group_impl() { var skypeClient = new Skype_Client(new Skype()); var users = new List<SkypeClient.User>(); users.Add(new SkypeClient.User("testgogroups")); users.Add(new SkypeClient.User("jonny.plankton")); var userGroup = new UserGroup(skypeClient, users, "Trumps_trunk"); userGroup.Send(Guid.NewGuid().ToString()); }
public bool Create(UserGroup group) { if (group.ItemId.Equals(Guid.Empty)) { group.ItemId = Guid.NewGuid(); } return dataAccess.CreateUserGroup(group); }
public vSearchModel(UserGroup model) { this.ID = model.ID; this.Title = model.GroupName; this.Description = model.Description == null ? "" : model.Description; this.Phone = model.Phone; this.SearchType = SearchType.UserGroup; this.Picture = model.Picture==null?"/Images/userphoto.png":"/UserGroup/ShowPicture/" + model.ID; this.Url = "/UserGroup/UserGroupShow/" + model.ID; }
public static string GetGroupName(UserGroup group) { switch (group) { case UserGroup.Admin: return "Administrator"; default: return group.ToString(); } }
private ListViewItem CreateListViewGroupItem(UserGroup item) { ListViewItem listViewItem = new ListViewItem(); listViewItem.Text = item.ToString(); groupsListView.SmallImageList.Images.Add(item.ItemImage); listViewItem.ImageIndex = rolesListView.SmallImageList.Images.Count - 1; listViewItem.Tag = item; return listViewItem; }
public UserGroup GetUserGroupByGroupCode(Decimal GroupCode) { Hashtable lstItems = new Hashtable(); lstItems.Add("@GroupCode", GroupCode); DataTable dt = dal.GetAllUserGroupByGroupCode(lstItems); UserGroup objUserGroup = new UserGroup(); DataRow dr = dt.Rows[0]; return GetObject(dr); }
/// <summary> /// ��ӷ��� /// </summary> public void AddGroup() { string groups = Request.Params["groups"]; string userId = Request.Params["userId"]; groups = groups.Replace("��",","); string[] groupNames = groups.Split(','); UserGroup userGroup = new UserGroup(); string groupIds = ""; string changedGroupNames = ""; for(int i=0;i<groupNames.Length;i++){ string groupName = groupNames[i]; string tempGroupName = groupName; string strGroupId = null; if (groupName == "İ����") { //strGroupId = userGroup.GetStrangerGroupId(); WriteMessage("�������������Ϊ��İ���ˡ����飡"); return; } else if (groupName == "�Լ�") { WriteMessage("�������������Ϊ���Լ������飡"); return; } else { strGroupId = userGroup.ExistGroupByName(tempGroupName, userId); while (strGroupId != null && strGroupId != "") { // ������ڸ��飬���������һ�����ּ�1��û�����֣�������Ϊ1 tempGroupName += "(1)"; strGroupId = userGroup.ExistGroupByName(tempGroupName, userId); } } // �������� string createGroupId = userGroup.CreateGroup(tempGroupName, userId); if (createGroupId == "") { WriteMessage("��������ʧ�ܣ����Ժ����ԣ�"); return; } changedGroupNames += i + ":" + tempGroupName + ","; groupIds += createGroupId + ","; } WriteMessage(groupIds.TrimEnd(',') + "��" + changedGroupNames.TrimEnd(',')); }
///<summary>Converts a DataTable to a list of objects.</summary> public static List<UserGroup> TableToList(DataTable table){ List<UserGroup> retVal=new List<UserGroup>(); UserGroup userGroup; for(int i=0;i<table.Rows.Count;i++) { userGroup=new UserGroup(); userGroup.UserGroupNum= PIn.Long (table.Rows[i]["UserGroupNum"].ToString()); userGroup.Description = PIn.String(table.Rows[i]["Description"].ToString()); retVal.Add(userGroup); } return retVal; }
public ActionResult Create(UserGroup usergroup) { if (ModelState.IsValid) { db.Groups.Add(usergroup); db.SaveChanges(); LogHelper.Log(db, User.Identity.Name, AGPDefine.LogLevelType.Info, AGPDefine.LogEventType.Insert, AGPDefine.LogObjectType.Group, null); return RedirectToAction("Index"); } return View(usergroup); }
public long CreateGroup(long userId, String name, String description) { UserGroup group = new UserGroup(); UserProfile user = UserProfileDao.Find(userId); if (user == null) throw new InstanceNotFoundException(user, typeof(UserProfile).FullName); group.UserProfile.Add(user); group.groupName = name; group.description = description; UserGroupDao.Create(group); return group.groupId; }
/// <summary> /// 新增用户组别 /// </summary> /// <param name="userGroup"></param> /// <returns></returns> public UserGroup CreateUserGroup(UserGroup userGroup) { Check.Argument.IsNotNull(userGroup, "userGroup"); if (DbProvider.D<UserGroup>().Count(x => x.Name == userGroup.Name) > 0) throw new ApplicationException("会员组名称已经存在,不能出现相同的组名"); DbProvider.Add(userGroup); DbProvider.SaveChanges(); return userGroup; }
public async Task SyncGroupAsync(Guid groupId, Guid scimAppSettingsId) { ScimGroupSyncState?syncState = await _authDbContext .ScimGroupSyncStates .SingleOrDefaultAsync(s => s.SCIMAppSettings.Id == scimAppSettingsId && s.UserGroup.Id == groupId); List <ScimUserSyncState> userSyncStates = await _authDbContext .ScimUserSyncStates .Where(s => s.SCIMAppSettings.Id == scimAppSettingsId && s.User.Groups.Any(g => g.Id == groupId)) .ToListAsync(); List <Gatekeeper.SCIM.Client.Schema.Core20.Group.GroupMembership> groupMemberships = new List <Gatekeeper.SCIM.Client.Schema.Core20.Group.GroupMembership>(); foreach (ScimUserSyncState userSyncState in userSyncStates) { groupMemberships.Add(new Gatekeeper.SCIM.Client.Schema.Core20.Group.GroupMembership { Value = userSyncState.ServiceId, }); } UserGroup group = await _authDbContext .UserGroup .SingleAsync(u => u.Id == groupId); Gatekeeper.SCIM.Client.Schema.Core20.Group scimGroup = new Gatekeeper.SCIM.Client.Schema.Core20.Group { ExternalId = group.Id.ToString(), DisplayName = group.Name, Members = groupMemberships, }; Gatekeeper.SCIM.Client.Client scimClient = await GetScimClient(scimAppSettingsId); if (syncState == null) { CreateAction <Gatekeeper.SCIM.Client.Schema.Core20.Group> createGroupAction = new CreateAction <Gatekeeper.SCIM.Client.Schema.Core20.Group>(scimGroup); CreateResult <Gatekeeper.SCIM.Client.Schema.Core20.Group> createUserResult = await scimClient.PerformAction <CreateResult <Gatekeeper.SCIM.Client.Schema.Core20.Group> >(createGroupAction); if (createUserResult.ResultStatus == StateEnum.Success && createUserResult.Resource != null && createUserResult.Resource.Id != null ) { syncState = new ScimGroupSyncState { UserGroup = group, SCIMAppSettingsId = scimAppSettingsId, ServiceId = createUserResult.Resource.Id, }; _authDbContext.Add(syncState); await _authDbContext.SaveChangesAsync(); } else { throw new Exception("SCIM initial sync failed"); } } else { scimGroup.Id = syncState.ServiceId; UpdateGroupAction updateGroup = new UpdateGroupAction(scimGroup); UpdateGroupResult updateGroupResult = await scimClient.PerformAction <UpdateGroupResult>(updateGroup); if (updateGroupResult.ResultStatus != StateEnum.Success) { throw new Exception("SCIM update failed"); } } }
/// <summary> /// Determines whether a user group is contained in an array of user group names. /// </summary> /// <param name="group">The user group to check.</param> /// <param name="groups">The user group names array.</param> /// <returns><c>true</c> if <b>users</b> contains <b>user.Name</b>, <c>false</c> otherwise.</returns> private static bool IsSelected(UserGroup group, string[] groups) { StringComparer comp = StringComparer.OrdinalIgnoreCase; return(Array.Find(groups, delegate(string g) { return comp.Compare(g, group.Name) == 0; }) != null); }
/// <summary> /// Verifies the need for a data upgrade, and performs it when needed. /// </summary> private void VerifyAndPerformUpgrade() { // Load file lines // Parse first line (if any) with old (v2) algorithm // If parsing is successful, then the file must be converted // Conversion consists in removing the 'ADMIN|USER' field, creating the proper default groups and setting user membership // Structure v2: // Username|PasswordHash|Email|Active-Inactive|DateTime|Admin-User //string[] lines = File.ReadAllLines(GetFullPath(UsersFile)); // Use this method because version 2.0 file might have started with a blank line string[] lines = File.ReadAllText(GetFullPath(UsersFile)).Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length > 0) { bool upgradeIsNeeded = false; LocalUserInfo[] users = new LocalUserInfo[lines.Length]; bool[] oldStyleAdmin = new bool[lines.Length]; // Values are valid only if upgradeIsNeeded=true char[] splitter = new char[] { '|' }; for (int i = 0; i < lines.Length; i++) { string line = lines[i]; string[] fields = line.Split(splitter, StringSplitOptions.RemoveEmptyEntries); string displayName = null; if (fields.Length == 6) { if (fields[5] == "ADMIN" || fields[5] == "USER") { // Version 2.0 upgradeIsNeeded = true; oldStyleAdmin[i] = fields[5] == "ADMIN"; } else { // Version 3.0 with DisplayName specified oldStyleAdmin[i] = false; displayName = fields[5]; } } else { // Can be a version 3.0 file, with empty DisplayName oldStyleAdmin[i] = false; } users[i] = new LocalUserInfo(fields[0], displayName, fields[2], fields[3].ToLowerInvariant() == "active", DateTime.Parse(fields[4]), this, fields[1]); } if (upgradeIsNeeded) { // Dump users // Create default groups // Set membership for old users // Tell the host to set the permissions for the default groups string backupFile = GetFullPath(Path.GetFileNameWithoutExtension(UsersFile) + "_v2" + Path.GetExtension(UsersFile)); File.Copy(GetFullPath(UsersFile), backupFile); host.LogEntry("Upgrading users format from 2.0 to 3.0", LogEntryType.General, null, this); DumpUsers(users); UserGroup adminsGroup = AddUserGroup(host.GetSettingValue(SettingName.AdministratorsGroup), "Built-in Administrators"); UserGroup usersGroup = AddUserGroup(host.GetSettingValue(SettingName.UsersGroup), "Built-in Users"); for (int i = 0; i < users.Length; i++) { if (oldStyleAdmin[i]) { SetUserMembership(users[i], new string[] { adminsGroup.Name }); } else { SetUserMembership(users[i], new string[] { usersGroup.Name }); } } host.UpgradeSecurityFlagsToGroupsAcl(adminsGroup, usersGroup); } } }
/// <summary> /// Sets the rank of a <see cref="ReferenceHub"/> to a <see cref="UserGroup"/>. /// </summary> public static void SetRank(this ReferenceHub player, UserGroup userGroup) => player.serverRoles.SetGroup(userGroup, false, false, false);
public static List <UserRole> userRoles(this UserGroup userGroup) { return(UserRolesMappings.Mappings[userGroup]); }
public RegisterTests(CustomWebApplicationFactoryWithMariaDb <Startup> factory) { _client = factory.CreateClient(); _context = factory.Services.GetService <IServiceScopeFactory>().CreateScope().ServiceProvider.GetService <MainDbContext>(); Utils.RemoveAllEntities(_context); _context.Add(_org1 = Utils.CreateOrganization(code: 1, name: "org1", startDate: DateTime.Parse("2020-01-14"), endDate: DateTime.Parse("2021-01-30"))); _context.Add(_domain1 = new Domain { Id = Guid.NewGuid(), Name = "domain01", Organization = _org1 }); _context.Add(_userGroup1 = new UserGroup { Id = Guid.NewGuid(), Domain = _domain1, Name = "userGroup1" }); _context.Add(_user1 = new SuperAdmin { AccountName = "user0", Name = "user0", Password = Utils.HashPassword("user0") }); // スーパー管理者 _context.Add(_user2 = new UserAdmin { AccountName = "user1", Name = "user1", Password = Utils.HashPassword("user1"), Domain = _domain1 }); // ユーザー管理者 _context.Add(_user3 = new GeneralUser { AccountName = "user2", Name = "user2", DomainId = _domain1.Id }); _context.Add(new UserGroupEndUser() { EndUser = _user2, UserGroup = _userGroup1 }); _context.Add(new AvailablePeriod { EndUser = _user2, EndDate = DateTime.Parse("2021-03-01"), StartDate = DateTime.Parse("2020-02-10") }); _context.Add(new AvailablePeriod { EndUser = _user3, EndDate = DateTime.Parse("2021-03-01"), StartDate = DateTime.Parse("2020-02-10") }); _context.Add(_deviceGroup1 = new DeviceGroup { Id = Guid.NewGuid(), Name = "_deviceGroup1", Domain = _domain1 }); _context.Add(_lteModule1 = new LteModule { Name = "lte1", UseSoftwareRadioState = true, NwAdapterName = "abc" }); _context.Add(_device1 = new Device() { LteModule = _lteModule1, Domain = _domain1, Name = "device01", UseTpm = true, ManagedNumber = "001", WindowsSignInListCacheDays = 1, }); _context.Add(_simGroup1 = new SimGroup() { Id = Guid.NewGuid(), Name = "simGroup1", Organization = _org1, Apn = "apn", AuthenticationServerIp = "AuthServerIpAddress", IsolatedNw1IpPool = "Nw1IpAddressPool", IsolatedNw1SecondaryDns = "Nw1SecondaryDns", IsolatedNw1IpRange = "Nw1IpAddressRange", IsolatedNw1PrimaryDns = "Nw1PrimaryDns", NasIp = "NasIpAddress", UserNameSuffix = "UserNameSuffix", PrimaryDns = "PrimaryDns", SecondaryDns = "SecondaryDns" }); _context.Add(_sim1 = new Sim() // 組織 : '自組織 { Msisdn = "1001", Imsi = "1001", IccId = "1001", UserName = "******", Password = "******", SimGroup = _simGroup1 }); _context.Add(_sim2 = new Sim() // 組織 : '自組織 { Msisdn = "1002", Imsi = "1002", IccId = "1002", UserName = "******", Password = "******", SimGroup = _simGroup1 }); _context.Add(_simAndDevice1 = new SimAndDevice() { Sim = _sim1, Device = _device1, IsolatedNw2Ip = "127.0.0.1/18", AuthenticationDuration = 1, StartDate = DateTime.Parse("2020-02-01"), EndDate = DateTime.Parse("2021-02-01") }); _context.SaveChanges(); }
protected Database() { User user1 = new User("Tom", "password"); User user2 = new User("Alex", "password"); User user3 = new User("Lisa", "password"); User user4 = new User("Mario", "password"); User user5 = new User("Lucia", "password"); Users.Add(user1.UserName, user1); Users.Add(user2.UserName, user2); Users.Add(user3.UserName, user3); Users.Add(user4.UserName, user4); Users.Add(user5.UserName, user5); Location route1 = new Location("Ostpark, Munich", 48.112242, 11.630701, 5); Location route2 = new Location("Parco di Villa Borghese, Rome", 41.914614, 12.481987, 6); Location route3 = new Location("Parco degli Acquedotti, Rome", 41.853406, 12.557115, 10); Location route4 = new Location("Englischer Garten, Munich", 48.164334, 11.605598, 8); Location route5 = new Location("Parco Sempione, Milan", 45.474371, 9.171659, 4); RunningLocations.Add(route1.RouteName, route1); RunningLocations.Add(route2.RouteName, route2); RunningLocations.Add(route3.RouteName, route3); RunningLocations.Add(route4.RouteName, route4); RunningLocations.Add(route5.RouteName, route5); Event jogging1 = new InPersonEvent(new DateTime(2020, 08, 01, 08, 30, 00), 11.0, "Jogging in the park", route3); Event jogging2 = new InPersonEvent(new DateTime(2020, 08, 09, 19, 00, 00), 11.5, "After work jogging", route5); Event jogging3 = new VirtualEvent(new DateTime(2020, 8, 21, 09, 00, 00), 10.0, "Jogging as a virtual group", 7.0); Event jogging4 = new InPersonEvent(new DateTime(2020, 06, 01, 10, 00, 00), 12.0, "Morning jogging on 1st June", route1); Event jogging5 = new VirtualEvent(new DateTime(2020, 7, 28, 19, 00, 00), 11.5, "Jogging in different locations", 5.0); Event jogging6 = new InPersonEvent(new DateTime(2020, 5, 15, 11, 00, 00), 10.0, "Speed challenge", route5); Event jogging7 = new VirtualEvent(new DateTime(2020, 7, 31, 18, 30, 00), 13.0, "Evening jogging", 5.0); Events.Add(jogging1.EventTitle, jogging1); Events.Add(jogging2.EventTitle, jogging2); Events.Add(jogging3.EventTitle, jogging3); Events.Add(jogging4.EventTitle, jogging4); Events.Add(jogging5.EventTitle, jogging5); Events.Add(jogging6.EventTitle, jogging6); Events.Add(jogging7.EventTitle, jogging7); Participant part1 = new Participant(user1, jogging1); Participant part2 = new Participant(user1, jogging3); Participant part3 = new Participant(user1, jogging4); Participant part4 = new Participant(user2, jogging4); Participant part5 = new Participant(user3, jogging4); Participant part6 = new Participant(user4, jogging4); Participant part7 = new Participant(user1, jogging5); Participant part8 = new Participant(user1, jogging6); Participant part9 = new Participant(user2, jogging6); Participant part10 = new Participant(user4, jogging6); part7.SetRunningLocation(route4); part8.SetRunningLocation(route2); part3.CheckInAtEvent(); part4.CheckInAtEvent(); part5.CheckInAtEvent(); part6.CheckInAtEvent(); part8.CheckInAtEvent(); part9.CheckInAtEvent(); part10.CheckInAtEvent(); EventResults results1 = part3.UploadEventResults(TimeSpan.Parse("00:32:15", CultureInfo.InvariantCulture), 10.5, 166); EventResults results2 = part4.UploadEventResults(TimeSpan.Parse("00:31:09", CultureInfo.InvariantCulture), null, 170); EventResults results3 = part5.UploadEventResults(TimeSpan.Parse("00:34:38", CultureInfo.InvariantCulture), 9.8, null); EventResults results4 = part6.UploadEventResults(TimeSpan.Parse("00:35:00", CultureInfo.InvariantCulture), null, null); UserGroup group1 = new UserGroup(user1, "Munich Joggers"); UserGroup group2 = new UserGroup(user2, "Milan Joggers"); UserGroup group3 = new UserGroup(user3, "City joggers"); UserGroups.Add(group1.GroupName, group1); UserGroups.Add(group2.GroupName, group2); UserGroups.Add(group3.GroupName, group3); group1.AddMember(user3); group1.AddMember(user4); group2.AddMember(user4); group2.AddMember(user5); group3.AddMember(user1); }
public void AddUserGroup(UserGroup userGroup) { _context.UserGroup.Add(userGroup); }
public CustomList <UserGroup> GetAllUser() { return(UserGroup.GetAllUser()); }
public int InsertRow(DbTransaction pTran, UserGroup UserGroup) { return(InsertRow(pTran, UserGroup, false)); }
public int UpdateRow(UserGroup UserGroup) { DbTransaction Tran = null; return(UpdateRow(Tran, UserGroup, false)); }
public int InsertRow(UserGroup UserGroup) { DbTransaction Tran = null; return(InsertRow(Tran, UserGroup, false)); }
public int DeleteRow(DbTransaction pTran, UserGroup UserGroup) { return(DeleteRow(pTran, UserGroup, false)); }
static void Main(string[] args) { #region 初始化 IFreeSql var fsql = new FreeSql.FreeSqlBuilder() .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseConnectionString(FreeSql.DataType.Sqlite, "data source=test.db;max pool size=5") //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2") .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3") .UseLazyLoading(true) .Build(); BaseEntity.Initialization(fsql); #endregion var test01 = EMSServerModel.Model.User.Select.IncludeMany(a => a.Roles).ToList(); var test01tb = EMSServerModel.Model.User.Orm.CodeFirst.GetTableByEntity(typeof(EMSServerModel.Model.User)); var us = User1.Select.Limit(10).ToList(); new Products { title = "product-1" }.Save(); new Products { title = "product-2" }.Save(); new Products { title = "product-3" }.Save(); new Products { title = "product-4" }.Save(); new Products { title = "product-5" }.Save(); var items1 = Products.Select.Limit(10).OrderByDescending(a => a.CreateTime).ToList(); var items2 = fsql.Select <Products>().Limit(10).OrderByDescending(a => a.CreateTime).ToList(); BaseEntity.Orm.UseJsonMap(); new S_SysConfig <TestConfig> { Name = "testkey11", Config = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey22", Config = new TestConfig { clicks = 22, title = "testtitle22" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey33", Config = new TestConfig { clicks = 33, title = "testtitle33" } }.Save(); var testconfigs11 = S_SysConfig <TestConfig> .Select.ToList(); var repo = BaseEntity.Orm.Select <TestConfig>().Limit(10).ToList(); Task.Run(async() => { using (var uow = BaseEntity.Begin()) { var id = (await new User1().SaveAsync()).Id; uow.Commit(); } var ug1 = new UserGroup(); ug1.GroupName = "分组一"; await ug1.InsertAsync(); var ug2 = new UserGroup(); ug2.GroupName = "分组二"; await ug2.InsertAsync(); var u1 = new User1(); u1.GroupId = ug1.Id; await u1.SaveAsync(); await u1.DeleteAsync(); await u1.RestoreAsync(); u1.Nickname = "x1"; await u1.UpdateAsync(); var u11 = await User1.FindAsync(u1.Id); u11.Description = "备注"; await u11.SaveAsync(); await u11.DeleteAsync(); var slslsl = Newtonsoft.Json.JsonConvert.SerializeObject(u1); var u11null = User1.Find(u1.Id); var u11s = User1.Where(a => a.Group.Id == ug1.Id).Limit(10).ToList(); var u11s2 = User1.Select.LeftJoin <UserGroup>((a, b) => a.GroupId == b.Id).Limit(10).ToList(); var ug1s = UserGroup.Select .IncludeMany(a => a.User1s) .Limit(10).ToList(); var ug1s2 = UserGroup.Select.Where(a => a.User1s.AsSelect().Any(b => b.Nickname == "x1")).Limit(10).ToList(); var r1 = new Role(); r1.Id = "管理员"; await r1.SaveAsync(); var r2 = new Role(); r2.Id = "超级会员"; await r2.SaveAsync(); var ru1 = new RoleUser1(); ru1.User1Id = u1.Id; ru1.RoleId = r1.Id; await ru1.SaveAsync(); ru1.RoleId = r2.Id; await ru1.SaveAsync(); var u1roles = await User1.Select.IncludeMany(a => a.Roles).ToListAsync(); var u1roles2 = await User1.Select.Where(a => a.Roles.AsSelect().Any(b => b.Id == "xx")).ToListAsync(); }).Wait(); Console.WriteLine("按任意键结束。。。"); Console.ReadKey(); }
public Permission(string command, UserGroup group) { this.command = command; this.group = group; }
/// <summary> /// Sets a permission for a directory. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="provider">The provider that handles the directory.</param> /// <param name="directory">The directory.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserGroup group) { if (group == null) { throw new ArgumentNullException("group"); } return(SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareGroup(group.Name))); }
public int UpdateRow(DbTransaction pTran, UserGroup UserGroup) { return(UpdateRow(pTran, UserGroup, false)); }
public virtual OperationResult UpdateEntity(UserGroup userGroup, bool isSave = true) { return(userGroupRepository.Update(userGroup, isSave)); }
public async Task <bool> CreateUserGroupnUserRole(User user, string groupName, bool IshallBeGpAdmin) { Group grp = new Group(); //check if group already exists bool grpAlreadyExist = _dataContext.Groups.Any(kk => kk.Name == groupName); if (grpAlreadyExist) { grp = await _dataContext.Groups.FirstOrDefaultAsync(kk => kk.Name == groupName); //return grp; } else { grp.Name = groupName; } // add user to groups // create User Group and then add to group UserGroup userGroup = new UserGroup(); userGroup.User = user; userGroup.UserId = user.Id; userGroup.GroupId = grp.Id; userGroup.Group = grp; RoleGroup roleGroup = new RoleGroup(); roleGroup.UserId = user.Id; roleGroup.GroupId = grp.Id; roleGroup.Group = grp; int roleId; Role role = new Role(); // create role _Gp_Admin if (IshallBeGpAdmin) { role = await _roleManager.FindByNameAsync("_Gp_Admin"); roleId = role.Id; } else { role = await _roleManager.FindByNameAsync("_Gp_Member"); roleId = role.Id; } var currentUserRoles = await _userManager.GetRolesAsync(user); if (!currentUserRoles.Contains(role.Name)) { IList <string> newrole = new List <string>(); newrole.Add(role.Name); var result = await _userManager.AddToRolesAsync(user, newrole); } //add role to rolegroup roleGroup.Role = role; roleGroup.RoleId = roleId; _dataContext.UserGroups.AddAsync(userGroup).Wait(); _dataContext.RoleGroups.AddAsync(roleGroup).Wait(); grp.GroupRoles.Add(roleGroup); grp.GroupUsers.Add(userGroup); // if group already exist then it has to be updated if (!grpAlreadyExist) { _dataContext.Groups.AddAsync(grp).Wait(); } else { _dataContext.Groups.Update(grp); } await _dataContext.SaveChangesAsync(); user.UserGroups.Add(userGroup); //user.Groups.Add(grp); _userManager.UpdateAsync(user).Wait(); return(true); }
public void CreateUser(UserModel model) { db = new TimeAttendanceEntities(); if (this.IsExistedUser(model.Name)) { throw new BusinessException(ErrorMessage.ERR002); } using (var trans = db.Database.BeginTransaction()) { try { User modelCreate = new User() { UserId = Guid.NewGuid().ToString(), Name = model.Name, FullName = model.FullName, BirthDay = model.BirthDay, Agency = model.Agency, Email = model.Email, UnitId = model.UnitId, Role = model.Role, Type = model.Type, PhoneNumber = model.PhoneNumber, Address = model.Address, Status = Constants.UnLock, Description = model.Description, ImageLink = model.ImageLink, CreateBy = model.CreateBy, CreateDate = DateTime.Now, }; modelCreate.Password = PasswordUtil.CreatePasswordHash(); modelCreate.PasswordHash = PasswordUtil.ComputeHash(Constants.PasswordDefault + modelCreate.Password); db.User.Add(modelCreate); if (!string.IsNullOrEmpty(model.GroupId)) { UserGroup userGroup = new UserGroup() { UserGroupId = Guid.NewGuid().ToString(), GroupId = model.GroupId, UserId = modelCreate.UserId, }; db.UserGroup.Add(userGroup); } //Thêm dánh sách quyền cho tài khoản List <UserPermission> listPermission = new List <UserPermission>(); UserPermission modelPermission; if (model.ListPermission != null && model.ListPermission.Count() > 0) { foreach (var item in model.ListPermission) { modelPermission = new UserPermission() { UserPermissionId = Guid.NewGuid().ToString(), UserId = modelCreate.UserId, FunctionId = item.FunctionId, }; listPermission.Add(modelPermission); } db.UserPermission.AddRange(listPermission); } //luu Log lich su string decription = "Thêm mới có tên là: " + model.Name; LogBusiness.SaveLogEvent(db, model.LogUserId, decription, model.ViolationEventId); db.SaveChanges(); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw new ErrorException(ErrorMessage.ERR001, ex.InnerException); } } }
public CustomList <UserGroup> GetAllUserGroup(string groupCode) { return(UserGroup.GetAllUserGroup(groupCode)); }
public void UpdateUser(UserModel model) { db = new TimeAttendanceEntities(); var modelEdit = db.User.Where(r => r.UserId.Equals(model.UserId) && r.DeleteFlg == Constants.DeleteFalse).FirstOrDefault(); if (modelEdit == null) { throw new BusinessException(ErrorMessage.ERR003); } if (modelEdit.Name != model.Name) { if (this.IsExistedUser(model.Name)) { throw new BusinessException(ErrorMessage.ERR002); } } using (var trans = db.Database.BeginTransaction()) { try { var userNameOld = modelEdit.Name; modelEdit.FullName = model.FullName; modelEdit.BirthDay = model.BirthDay; modelEdit.Agency = model.Agency; modelEdit.Email = model.Email; modelEdit.UnitId = model.UnitId; modelEdit.Role = model.Role; modelEdit.Type = model.Type; modelEdit.PhoneNumber = model.PhoneNumber; modelEdit.Address = model.Address; modelEdit.Description = model.Description; modelEdit.ImageLink = model.ImageLink; modelEdit.UpdateBy = model.UpdateBy; modelEdit.UpdateDate = DateTime.Now; if (!string.IsNullOrEmpty(model.GroupId)) { var itemDelete = db.UserGroup.Where(r => r.UserId.Equals(model.UserId)); db.UserGroup.RemoveRange(itemDelete); UserGroup userGroup = new UserGroup() { UserGroupId = Guid.NewGuid().ToString(), GroupId = model.GroupId, UserId = model.UserId, }; db.UserGroup.Add(userGroup); } //Thêm dánh sách quyền cho tài khoản List <UserPermission> listPermission = new List <UserPermission>(); UserPermission modelPermission; //Xóa quyền cũ var listPermissionDelete = db.UserPermission.Where(r => r.UserId.Equals(model.UserId)); db.UserPermission.RemoveRange(listPermissionDelete); //Thêm quyền mới if (model.ListPermission != null && model.ListPermission.Count() > 0) { foreach (var item in model.ListPermission) { modelPermission = new UserPermission() { UserPermissionId = Guid.NewGuid().ToString(), UserId = model.UserId, FunctionId = item.FunctionId, }; listPermission.Add(modelPermission); } db.UserPermission.AddRange(listPermission); } //luu Log lich su string decription = String.Empty; if (userNameOld.ToLower() == modelEdit.Name.ToLower()) { decription = "Cập nhật thông tin có tên là: " + userNameOld; } else { decription = "Cập nhật thông tin có tên ban đầu là: " + userNameOld + " thành " + model.Name;; } LogBusiness.SaveLogEvent(db, model.LogUserId, decription, null); db.SaveChanges(); trans.Commit(); //xóa cache var redis = RedisService <LoginCacheModel> .GetInstance(RedisConnection); LoginCacheModel RefreshToken; RefreshToken = redis.Get <LoginCacheModel>(Constants.ATLogin + userNameOld); if (RefreshToken != null) { redis.Remove(Constants.ATLogin + userNameOld); } } catch (Exception ex) { trans.Rollback(); throw new ErrorException(ErrorMessage.ERR001, ex.InnerException); } } }
/// <summary> /// Sets a permission for a page. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="page">The page.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForPage(AuthStatus status, PageInfo page, string action, UserGroup group) { if (group == null) { throw new ArgumentNullException("group"); } return(SetPermissionForPage(status, page, action, AuthTools.PrepareGroup(group.Name))); }
public ActionResult Edit(EditProfileViewModel EProfile, IEnumerable <string> Groups) { ViewBag.Current = "Users"; string OldUserRole = db.Users.Find(EProfile.Id).RoleName; ViewBag.Role = new SelectList(db.Roles.ToList(), "Id", "Name", EProfile.Role); ViewBag.DepartmentID = new SelectList(DepartmentListDisplay.CreateDepartmentListDisplay(), "Id", "Name", EProfile.DepartmentID); ViewBag.JobTitleId = new SelectList(db.JobTitles.ToList(), "Id", "Name", EProfile.JobTitleId); List <int> SelectedGroups = new List <int>(); SelectedGroups = db.UsersGroups.Where(a => a.UserId.Equals(EProfile.Id)).Select(a => a.GroupId).ToList(); SelectListItem sl; List <SelectListItem> ListSl = new List <SelectListItem>(); foreach (var G in db.Groups.ToList()) { sl = new SelectListItem() { Text = G.Name, Value = G.Id.ToString(), Selected = SelectedGroups.DefaultIfEmpty().Contains(G.Id) ? true : false }; ListSl.Add(sl); } ViewBag.Groups = ListSl; bool x = true; ApplicationUser user = null; if (ModelState.IsValid) { user = UserManager.FindById(EProfile.Id); if (user == null) { return(RedirectToAction("HttpNotFoundError", "ErrorController")); } //Delete All Users Permissions: if (!user.RoleName.Equals(EProfile.Role)) { List <PermissionsUser> User_Permissions = db.PermissionUsers.Where(a => a.UserId.Equals(user.Id)).ToList(); foreach (PermissionsUser UP in User_Permissions) { db.PermissionUsers.Remove(UP); } db.SaveChanges(); } if (!EProfile.Role.Equals("Master")) { if (CheckJobTitleDepartment.CheckJobTitleDepartmentCreateUser(EProfile.DepartmentID, EProfile.JobTitleId, EProfile.Id) == false) { ModelState.AddModelError("JobTitleId", "عددالأعضاء للقسم بالنسبة للمسمى الوظيفي وصل للحد الأعظمي"); x = false; } } if (db.Users.Where(a => !a.Id.Equals(EProfile.Id)).Any(a => a.UserName.Equals(EProfile.UserName, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError("UserName", "لا يمكن أن يكون اسم امستخدم مكرر، يرجى إعادةالإدخال"); x = false; } if (!string.IsNullOrEmpty(EProfile.Email)) { if (db.Users.Where(a => !a.Id.Equals(EProfile.Id)).Any(a => a.Email.Equals(EProfile.Email, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError("Email", "لا يمكن أن يكون البريد الإلكتروني مكرر، يرجى إعادةالإدخال"); x = false; } } if (x == false) { return(View(EProfile)); } user.FullName = EProfile.FullName; user.Email = EProfile.Email; user.Gender = EProfile.Gender; user.RoleName = EProfile.Role; user.UserName = EProfile.UserName; var HashPassword = UserManager.PasswordHasher.HashPassword(EProfile.Password); user.PasswordHash = HashPassword; user.UpdatedAt = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"); user.UpdatedByID = this.User.Identity.GetUserId(); db.Entry(user).State = System.Data.Entity.EntityState.Modified; //Add User To Groups // string UserId = User.Identity.GetUserId(); Notification notification = null; string NotificationTime = string.Empty; string GroupName = string.Empty; NotificationTime = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"); notification = new Notification() { CreatedAt = NotificationTime, Active = false, UserId = user.Id, Message = "تم تحديث معلوماتك الشخصية", NotificationOwnerId = UserId }; db.Notifications.Add(notification); List <string> SelectedUserGroups = new List <string>(); SelectedUserGroups = db.UsersGroups.Where(a => a.UserId.Equals(EProfile.Id)).Select(a => a.GroupId.ToString()).ToList(); if (Groups != null) { UserGroup UserGroup = null; List <string> ExpectGroups = new List <string>(); ExpectGroups = SelectedUserGroups.Except(Groups).ToList(); foreach (string User_Group_Id in Groups) { NotificationTime = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"); if (SelectedUserGroups.Contains(User_Group_Id)) { continue; } UserGroup = new UserGroup() { UserId = user.Id, GroupId = Convert.ToInt32(User_Group_Id), CreatedAt = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"), CreatedById = this.User.Identity.GetUserId() }; db.UsersGroups.Add(UserGroup); GroupName = db.Groups.Find(UserGroup.GroupId).Name; notification = new Notification() { CreatedAt = NotificationTime, Active = false, UserId = user.Id, Message = "تم إضافتك إلى المجموعة :" + GroupName , NotificationOwnerId = UserId }; db.Notifications.Add(notification); } UserGroup deleteUserGroup; foreach (string s in ExpectGroups) { deleteUserGroup = db.UsersGroups.Where(a => a.UserId.Equals(EProfile.Id) && a.GroupId.ToString().Equals(s)).SingleOrDefault(); db.UsersGroups.Remove(deleteUserGroup); GroupName = db.Groups.Find(deleteUserGroup.GroupId).Name; notification = new Notification() { CreatedAt = NotificationTime, Active = false, UserId = user.Id, Message = "تم إزالتك من المجموعة :" + GroupName , NotificationOwnerId = UserId }; db.Notifications.Add(notification); } db.SaveChanges(); } else { foreach (UserGroup ug in db.UsersGroups.Where(a => a.UserId.Equals(EProfile.Id))) { db.UsersGroups.Remove(ug); GroupName = db.Groups.Find(ug.GroupId).Name; notification = new Notification() { CreatedAt = NotificationTime, Active = false, UserId = user.Id, Message = "تم إزالتك من المجموعة :" + GroupName , NotificationOwnerId = UserId }; db.Notifications.Add(notification); } db.SaveChanges(); } db.SaveChanges(); return(RedirectToAction("Index", new { @Id = "EditSuccess" })); } return(View(EProfile)); }
public JsonResult AssignGroup([FromBody] UserGroup user) { string AddedBy = Constant.GetUserID(); return(Json(UsersSQL.AssignGroup(user, AddedBy), JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> Register(RegisterViewModel model, IEnumerable <string> Groups) { bool x = true; ViewBag.Current = "Users"; ViewBag.DepartmentID = new SelectList(DepartmentListDisplay.CreateDepartmentListDisplay(), "Id", "Name"); ViewBag.JobTitleId = new SelectList(db.JobTitles.ToList(), "Id", "Name"); ViewBag.Role = new SelectList(db.Roles.Where(a => !a.Name.Equals("Master")).ToList(), "Name", "Name", model.Role); ViewBag.Groups = new SelectList(db.Groups.ToList(), "Id", "Name"); if (ModelState.IsValid) { if (db.Users.Any(a => a.UserName.Equals(model.UserName, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError("UserName", "اسم المستخدم موجود مسبقاً يرجى اعادة الإدخال"); x = false; } if (CheckJobTitleDepartment.CheckJobTitleDepartmentCreateUser(model.DepartmentID, model.JobTitleId) == false) { ModelState.AddModelError("JobTitleId", "عددالأعضاء للقسم بالنسبة للمسمى الوظيفي وصل للحد الأعظمي"); x = false; } if (!string.IsNullOrEmpty(model.Email)) { if (db.Users.Any(a => a.Email.Equals(model.Email, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError("Email", "لا يمكن أن يكون البريد الإلكتروني مكرر، يرجى إعادةالإدخال"); x = false; } } if (x == false) { return(View(model)); } var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, FullName = model.FullName, Gender = model.Gender, DepartmentId = model.DepartmentID, JobTitleId = model.JobTitleId, CreatedAt = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"), CreatedById = this.User.Identity.GetUserId(), RoleName = model.Role }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, model.Role); //Add User To Groups if (Groups != null) { string UserId = User.Identity.GetUserId(); Notification notification = null; string NotificationTime = string.Empty; string GroupName = string.Empty; foreach (string User_Group_Id in Groups) { var UserGroup = new UserGroup() { UserId = user.Id, GroupId = Convert.ToInt32(User_Group_Id), CreatedAt = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"), CreatedById = this.User.Identity.GetUserId() }; NotificationTime = DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"); db.UsersGroups.Add(UserGroup); GroupName = db.Groups.Find(UserGroup.GroupId).Name; notification = new Notification() { CreatedAt = NotificationTime, Active = false, UserId = user.Id, Message = "تم إضافتك إلى المجموعة :" + GroupName , NotificationOwnerId = UserId }; db.Notifications.Add(notification); } } db.SaveChanges(); return(RedirectToAction("Index", new { @Id = "CreateSuccess" })); } // AddErrors(result); } return(View(model)); }
public CsvImportMineTests(CustomWebApplicationFactoryWithMariaDb <JinCreek.Server.Admin.Startup> factory) { _client = factory.CreateClient(); _context = factory.Services.GetService <IServiceScopeFactory>().CreateScope().ServiceProvider.GetService <MainDbContext>(); //_context.Database.EnsureDeleted(); //_context.Database.EnsureCreated(); //_context.Database.Migrate(); Utils.RemoveAllEntities(_context); _context.Add(_org1 = Utils.CreateOrganization(code: 1, name: "org1")); _context.Add(_org2 = Utils.CreateOrganization(code: 2, name: "org2")); _context.Add(_domain1 = new Domain { Id = Guid.NewGuid(), Name = "domain01", Organization = _org1 }); _context.Add(_domain2 = new Domain { Id = Guid.NewGuid(), Name = "domain03", Organization = _org2 }); _context.Add(_userGroup1 = new UserGroup { AdObjectId = Guid.NewGuid(), Id = Guid.NewGuid(), Name = "userGroup1", Domain = _domain1 }); _context.Add(_userGroup2 = new UserGroup { AdObjectId = Guid.NewGuid(), Id = Guid.NewGuid(), Name = "userGroup2", Domain = _domain2 }); _context.Add(new SuperAdmin { Name = "", AccountName = "user0", Password = Utils.HashPassword("user0") }); // スーパー管理者 _context.Add(new UserAdmin { AdObjectId = Guid.NewGuid(), Name = "", AccountName = "user1", Password = Utils.HashPassword("user1"), Domain = _domain1 }); // ユーザー管理者 _context.Add(_simGroup1 = new SimGroup() { Id = Guid.NewGuid(), Name = "simGroup1", Organization = _org1, Apn = "apn", AuthenticationServerIp = "AuthenticationServerIp", IsolatedNw1IpPool = "IsolatedNw1IpPool1", IsolatedNw1SecondaryDns = "IsolatedNw1SecondaryDns", IsolatedNw1IpRange = "IsolatedNw1IpRange", IsolatedNw1PrimaryDns = "IsolatedNw1PrimaryDns", NasIp = "NasIp", PrimaryDns = "PrimaryDns", SecondaryDns = "SecondaryDns", UserNameSuffix = "UserNameSuffix" }); _context.Add(_simGroup1a = new SimGroup { Id = Guid.NewGuid(), Name = "simGroup1a", Organization = _org1, Apn = "apn", AuthenticationServerIp = "AuthenticationServerIp", IsolatedNw1IpPool = "IsolatedNw1IpPool1a", IsolatedNw1SecondaryDns = "IsolatedNw1SecondaryDns", IsolatedNw1IpRange = "IsolatedNw1IpRange", IsolatedNw1PrimaryDns = "IsolatedNw1PrimaryDns", NasIp = "NasIp", PrimaryDns = "PrimaryDns", SecondaryDns = "SecondaryDns", UserNameSuffix = "UserNameSuffix" }); _context.Add(_simGroup2 = new SimGroup { Id = Guid.NewGuid(), Name = "simGroup2", Organization = _org2, Apn = "apn", AuthenticationServerIp = "AuthenticationServerIp", IsolatedNw1IpPool = "IsolatedNw1IpPool2", IsolatedNw1SecondaryDns = "IsolatedNw1SecondaryDns", IsolatedNw1IpRange = "IsolatedNw1IpRange", IsolatedNw1PrimaryDns = "IsolatedNw1PrimaryDns", NasIp = "NasIp", PrimaryDns = "PrimaryDns", SecondaryDns = "SecondaryDns", UserNameSuffix = "UserNameSuffix", }); _context.Add(_device1 = new Device() { Domain = _domain1, Name = "device01", UseTpm = true, ManagedNumber = "001", ProductName = "", SerialNumber = "", WindowsSignInListCacheDays = 1, }); _context.SaveChanges(); }
static void Main(string[] args) { #region 初始化 IFreeSql var fsql = new FreeSql.FreeSqlBuilder() .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseConnectionString(FreeSql.DataType.Sqlite, "data source=test.db;max pool size=5") //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3") //.UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=2") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToLower) //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=2") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToUpper) //.UseConnectionString(FreeSql.DataType.OdbcMySql, "Driver={MySQL ODBC 8.0 Unicode Driver};Server=127.0.0.1;Persist Security Info=False;Trusted_Connection=Yes;UID=root;PWD=root;DATABASE=cccddd_odbc;Charset=utf8;SslMode=none;Max pool size=2") //.UseConnectionString(FreeSql.DataType.OdbcSqlServer, "Driver={SQL Server};Server=.;Persist Security Info=False;Trusted_Connection=Yes;Integrated Security=True;DATABASE=freesqlTest_odbc;Pooling=true;Max pool size=3") //.UseConnectionString(FreeSql.DataType.OdbcPostgreSQL, "Driver={PostgreSQL Unicode(x64)};Server=192.168.164.10;Port=5432;UID=postgres;PWD=123456;Database=tedb_odbc;Pooling=true;Maximum Pool Size=2") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToLower) //.UseConnectionString(FreeSql.DataType.OdbcOracle, "Driver={Oracle in XE};Server=//127.0.0.1:1521/XE;Persist Security Info=False;Trusted_Connection=Yes;UID=odbc1;PWD=123456") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToUpper) //.UseConnectionString(FreeSql.DataType.OdbcDameng, "Driver={DM8 ODBC DRIVER};Server=127.0.0.1:5236;Persist Security Info=False;Trusted_Connection=Yes;UID=USER1;PWD=123456789") .UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText)) .UseLazyLoading(true) .Build(); BaseEntity.Initialization(fsql, () => _asyncUow.Value); #endregion var test01 = EMSServerModel.Model.User.Select.IncludeMany(a => a.Roles).ToList(); var test02 = EMSServerModel.Model.UserRole.Select.ToList(); var test01tb = EMSServerModel.Model.User.Orm.CodeFirst.GetTableByEntity(typeof(EMSServerModel.Model.User)); var us = User1.Select.Limit(10).ToList(); new Products { title = "product-1" }.Save(); new Products { title = "product-2" }.Save(); new Products { title = "product-3" }.Save(); new Products { title = "product-4" }.Save(); new Products { title = "product-5" }.Save(); Products.Select.WhereDynamicFilter(JsonConvert.DeserializeObject <DynamicFilterInfo>(@" { ""Logic"" : ""Or"", ""Filters"" : [ { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-1"", ""Filters"" : [ { ""Field"" : ""title"", ""Operator"" : ""contains"", ""Value"" : ""product-1111"", } ] }, { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-2"" }, { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-3"" }, { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-4"" }, ] } ")).ToList(); var items1 = Products.Select.Limit(10).OrderByDescending(a => a.CreateTime).ToList(); var items2 = fsql.Select <Products>().Limit(10).OrderByDescending(a => a.CreateTime).ToList(); BaseEntity.Orm.UseJsonMap(); BaseEntity.Orm.UseJsonMap(); BaseEntity.Orm.CodeFirst.ConfigEntity <S_SysConfig <TestConfig> >(a => { a.Property(b => b.Config2).JsonMap(); }); new S_SysConfig <TestConfig> { Name = "testkey11", Config = new TestConfig { clicks = 11, title = "testtitle11" }, Config2 = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey22", Config = new TestConfig { clicks = 22, title = "testtitle22" }, Config2 = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey33", Config = new TestConfig { clicks = 33, title = "testtitle33" }, Config2 = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); var testconfigs11 = S_SysConfig <TestConfig> .Select.ToList(); var repo = BaseEntity.Orm.Select <TestConfig>().Limit(10).ToList(); Task.Run(async() => { using (var uow = BaseEntity.Orm.CreateUnitOfWork()) { _asyncUow.Value = uow; try { var id = (await new User1().SaveAsync()).Id; } finally { _asyncUow.Value = null; } uow.Commit(); } var ug1 = new UserGroup(); ug1.GroupName = "分组一"; await ug1.InsertAsync(); var ug2 = new UserGroup(); ug2.GroupName = "分组二"; await ug2.InsertAsync(); var u1 = new User1(); u1.GroupId = ug1.Id; await u1.SaveAsync(); await u1.DeleteAsync(); await u1.RestoreAsync(); u1.Nickname = "x1"; await u1.UpdateAsync(); var u11 = await User1.FindAsync(u1.Id); u11.Description = "备注"; await u11.SaveAsync(); await u11.DeleteAsync(); var slslsl = Newtonsoft.Json.JsonConvert.SerializeObject(u1); var u11null = User1.Find(u1.Id); var u11s = User1.Where(a => a.Group.Id == ug1.Id).Limit(10).ToList(); var u11s2 = User1.Select.LeftJoin <UserGroup>((a, b) => a.GroupId == b.Id).Limit(10).ToList(); var ug1s = UserGroup.Select .IncludeMany(a => a.User1s) .Limit(10).ToList(); var ug1s2 = UserGroup.Select.Where(a => a.User1s.AsSelect().Any(b => b.Nickname == "x1")).Limit(10).ToList(); var r1 = new Role(); r1.Id = "管理员"; await r1.SaveAsync(); var r2 = new Role(); r2.Id = "超级会员"; await r2.SaveAsync(); var ru1 = new RoleUser1(); ru1.User1Id = u1.Id; ru1.RoleId = r1.Id; await ru1.SaveAsync(); ru1.RoleId = r2.Id; await ru1.SaveAsync(); var u1roles = await User1.Select.IncludeMany(a => a.Roles).ToListAsync(); var u1roles2 = await User1.Select.Where(a => a.Roles.AsSelect().Any(b => b.Id == "xx")).ToListAsync(); }).Wait(); Console.WriteLine("按任意键结束。。。"); Console.ReadKey(); }
private static bool FilterGroup(UserGroup group) { return(!group.Attributes.HasFlagSet(GroupAttributes.Integrity)); }
private static UserGroup MapGroupAttributes(UserGroup group) { return(new UserGroup(group.Sid, group.Attributes & (GroupAttributes.Enabled | GroupAttributes.UseForDenyOnly))); }