public void BeAbleToReturnAllUsersInRepository() { List <User> allUsers = new List <User> { new User("Gabriel", "*****@*****.**", "Wololo1234!", CashierRole.GetInstance()), new User("Ignacio", "*****@*****.**", "#designPatternsLover123", AdminRole.GetInstance()) }; var mockUserService = new Mock <IUserService>(); mockUserService.Setup(x => x.GetAllUsers(It.IsAny <string>())).Returns(allUsers); UsersController controller = new UsersController(mockUserService.Object); IHttpActionResult actionResult = controller.GetUsers(); OkNegotiatedContentResult <IEnumerable <User> > contentResult = (OkNegotiatedContentResult <IEnumerable <User> >)actionResult; Assert.IsTrue(contentResult.Content.All(x => allUsers.Contains(x)) && allUsers.All(x => contentResult.Content.Contains(x))); }
public async Task <ResponseResult <int> > Add_Save() { //获取参数 var streamReader = new StreamReader(Request.Body); var paramStr = streamReader.ReadToEnd(); RequestParamterHelper requestParamterHelper = new RequestParamterHelper(paramStr); var roleNames = requestParamterHelper.GetParamValue("roleName"); var roleName = roleNames[0]; var menus = requestParamterHelper.GetParamValue("menuId"); var role = new AdminRole(); role.Name = roleName; var serviceResult = await _roleService.AddRoleAsync(role, menus.Select(m => int.Parse(m)).ToList()); return(new ResponseResult <int>(true, serviceResult)); }
public void InsertTestsUserInfoForTest() { CONTROLLER = new UsersController(ADMIN_USER_USEREMAIL); TESTS_USERS = new[] { new User("Gabriel", "*****@*****.**", "Wololo1234!", CashierRole.GetInstance()), new User("Ignacio", "*****@*****.**", "#designPatternsLover123", AdminRole.GetInstance()) }; foreach (User aTestUser in TESTS_USERS) { CONTROLLER.PostUser(aTestUser); } ICollection <User> reservedUsers = new[] { ADMIN_USER }; ALL_USERS_IN_REPOSITORY = reservedUsers.Concat(TESTS_USERS).ToList(); }
public ActionResult ListStudent(int ClassId) { var adminRole = new AdminRole(); // var students = adminRole.GetStudents().Except(adminRole.GetStudentsOfClass(ClassId)).ToList(); var students = adminRole.GetStudents().Select(x => new StudentSubscriptionVM { StudentId = x.StudentId, Name = $"{x.StudentName}, {x.StudentFirstName}", Subscribed = false }).ToList(); var studentsSubscribed = adminRole.GetStudentsOfClass(ClassId).ToList(); students.ForEach(x => x.Subscribed = studentsSubscribed.Any(y => y.StudentId == x.StudentId)); var ViewValue = new ClassWithStudentsVM { Classe = adminRole.GetClass(ClassId), Students = students }; return(View(ViewValue));//ajouter page de selection }
public ActionResult Edit(Admin admins, FormCollection f) { // Get QuyenAdmin int quyenAdmin = int.Parse(f["AdminRole"]); AdminRole adminRole = new AdminRole(); // Admin adminRole.Id = admins.Id; adminRole.HotenAdmin = admins.HotenAdmin; adminRole.PassAdmin = admins.PassAdmin; adminRole.UserAdmin = admins.UserAdmin; adminRole.EmailAdmin = admins.EmailAdmin; adminRole.MaQuyen = quyenAdmin; HttpResponseMessage response = client.PutAsJsonAsync(url + @"adminrole/" + adminRole.Id, adminRole).Result; response.EnsureSuccessStatusCode(); return(RedirectToAction("MemberAdmin", "Admin")); }
public void BeAbleToGetAllObjectsWhileApplyingAFilterAndIncludingPropertiesPlusOrderingBy() { User user = new User("Bruno", "*****@*****.**", "Hola111!!!", AdminRole.GetInstance()); User anotherUser = new User("Alberto", "*****@*****.**", "Hola111!!!", AdminRole.GetInstance()); List <User> data = new List <User>(); data.Add(user); data.Add(anotherUser); var mockContext = new Mock <TodoPagosContext>(); var set = new Mock <DbSet <User> >().SetupData(data); mockContext.Setup(ctx => ctx.Set <User>()).Returns(set.Object); GenericRepository <User> repository = new GenericRepository <User>(mockContext.Object); IEnumerable <User> resultingUsers = repository.Get((x => x.HasThisRole(AdminRole.GetInstance())), (x => x.AsQueryable().OrderBy(u => u.Name)), "Roles"); Assert.AreEqual(2, resultingUsers.Count()); }
//给一个管理员增加一个角色 public bool AddAdminRole(AdminRole _AdminRole) { string Sql = "insert into AdminRole(AdminID,RoleID) values (@AdminID,@RoleID)"; SqlParameter[] Paras = new SqlParameter[] { new SqlParameter("@AdminID", _AdminRole.AdminID), new SqlParameter("@RoleID", _AdminRole.RoleID) }; if (SqlHelper.ExecuteNonQuery(Sql, Paras, CommandType.Text) > 0) { return(true); } else { return(false); } }
/// <summary> /// 获取用户权限菜单 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public List <MenuViewModel> GetMenuListByAccountId(long accountId, long menuType) { AdminRole role = new AdminRole(); OQL qRole = OQL.From(role) .Select() .OrderBy(role.ID, "asc") .END; StringBuilder sbMenuIds = new StringBuilder(); foreach (AdminRole item in qRole.ToList <AdminRole>()) { sbMenuIds.Append(item.MenuIds); } JsonRsp <MenuViewModel> rsp = new JsonRsp <MenuViewModel>(); AdminMenu model = new AdminMenu(); OQL q = new OQL(model); q.Select() .Where(q.Condition.AND(model.MenuType, "=", menuType)) .OrderBy(model.ID, "asc"); List <AdminMenu> list = q.ToList <AdminMenu>();//使用OQL扩展 return(list.ConvertAll <MenuViewModel>(o => { return new MenuViewModel() { ID = o.ID, ParentID = o.ParentID, MenuKey = o.MenuKey, MenuName = o.MenuName, MenuUrl = o.MenuUrl, MenuType = o.MenuType, IDPath = o.IDPath, Remark = o.Remark, Sort = o.Sort, Status = o.Status, CreateTIme = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), }; } )); }
public async Task <int> Create(string roleName) { if (string.IsNullOrEmpty(roleName)) { throw new HopexException(_localizer["角色名称不能为空"]); } if ((await _roleRepository.CountAsync(x => x.Name == roleName)) > 0) { throw new HopexException(_localizer["名称已存在"]); } var role = new AdminRole() { Name = roleName }; int id = await _roleRepository.InsertAsync(role); return(id); }
public ActionResult AssignToFloor(int id, AdminRole collection) { try { AdminRole Admin = _context.Admins.Find(id); Admin.BuildingId = collection.BuildingId; Admin.PostId = collection.PostId; string BuildingName = _context.Building.FirstOrDefault(x => x.Id == collection.BuildingId).BuildingName; int FloorNumber = _context.Floors.FirstOrDefault(x => x.Id == collection.PostId).FloorNumber; Admin.IsAssigned = BuildingName + "( " + FloorNumber.ToString() + " )"; Admin.Updated = DateTime.Today; Admin.UpdatedBy = User.Identity.Name; _context.Entry(Admin).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); return(RedirectToAction("List")); } catch { return(View()); } }
public IHttpActionResult GetAdminRole(int id) { Admin admin = db.Admins.Find(id); QuyenAdmin quyenAdmin = db.QuyenAdmins.Where(n => n.MaAdmin == admin.Id).SingleOrDefault(); if (admin == null || quyenAdmin == null) { return(NotFound()); } AdminRole adminRole = new AdminRole(); // Admin adminRole.Id = admin.Id; adminRole.HotenAdmin = admin.HotenAdmin; adminRole.PassAdmin = admin.PassAdmin; adminRole.UserAdmin = admin.UserAdmin; adminRole.EmailAdmin = admin.EmailAdmin; adminRole.MaQuyen = quyenAdmin.MaQuyen; return(Ok(adminRole)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); //Assign Role to user Here await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles); //................ AdminRole Admin = new AdminRole(); Admin.Name = model.UserName; Admin.Role = model.UserRoles; Admin.IsBlocked = "Active"; Admin.IsAssigned = "Not"; Admin.BuildingId = 0; Admin.PostId = 0; Admin.Updated = DateTime.Today; Admin.UpdatedBy = User.Identity.Name; _context.Admins.Add(Admin); _context.SaveChanges(); //Ends Here return(RedirectToAction("Index", "SuperAdmin")); } ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Boom")) .ToList(), "Name", "Name"); AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Create(AdminRole model, FormCollection form) { if (ModelState.IsValid) { try { model.UpdatePermissions(GetPermissions(form)); DataContext.AdminRoles.Add(model); SaveChanges(); ShowSuccess(MessageResource.CreateSuccess); return(RedirectToIndex()); } catch { ShowError(MessageResource.CreateFailed); } } return(View(model)); }
protected void btAdd_Click(object sender, EventArgs e) { //管理员表与管理员角色表都需要更新 AdminInfo _AdminInfo = new AdminInfo(); AdminRole _AdminRole = new AdminRole(); AdminRoleBLL _AdminRoleBLL = new AdminRoleBLL(); RoleBLL _RoleBLL = new RoleBLL(); AdminInfoBLL _AdminInfoBLL = new AdminInfoBLL(); int Num = _AdminInfoBLL.AdminExist(this.txtAccount.Text.Trim()); if (Num > 0) { Response.Write("<script language='javascript'>"); Response.Write("alert('该账号已存在');"); Response.Write("</script>"); return; } _AdminInfo.AdminAccount = this.txtAccount.Text.Trim(); _AdminInfo.PassWord = this.txtPass.Text.Trim(); _AdminInfo.IsSYS = false; bool StepOne = _AdminInfoBLL.AddAdminInfo(_AdminInfo); _AdminRole.AdminID = _AdminInfoBLL.GetAdminID(txtAccount.Text.Trim()); _AdminRole.RoleID = int.Parse(this.DropDownRole.SelectedValue.ToString()); bool StepTwo = _AdminRoleBLL.AddAdminRole(_AdminRole); if (StepOne && StepTwo) { Response.Write("<script language='javascript'>"); Response.Write("alert('添加成功');"); Response.Write("document.location.href='AdminList.aspx';"); Response.Write("</script>"); } }
public ActionResult ListStudentSav(ClassWithStudentsVM maClasseStudent) { var adminRole = new AdminRole(); adminRole.UpdateClassAttendence(maClasseStudent.Classe.ClassId, maClasseStudent.Students.Where(x => x.Subscribed == true).Select(x => adminRole.GetStudent(x.StudentId)).ToList()); //var existingStudent = adminRole.GetStudentsOfClass(maClasseStudent.Classe.ClassId).Select(x=>x.StudentId); //var deletedStudent = Queryable.Except<Student>(existingStudent.AsQueryable(), maClasseStudent.Students.Where(x=>x.Subscribed == true).Select(x => x.StudentId)).ToList(); ////var addedStudent = maClasseStudent.Students.Where(a => a.Subscribed == true); //for (var i = 0; i < maClasseStudent.Students.Count(); i++) //{ // if (maClasseStudent.Students[i].Subscribed == false) // { // var ViewValue1 = adminRole.RemoveStudent(maClasseStudent.Classe.ClassId, maClasseStudent.Students[i].StudentId); // } // else // { // var ViewValue2 = adminRole.AddStudent2(adminRole.GetClass(maClasseStudent.Classe.ClassId), adminRole.GetStudent(maClasseStudent.Students[i].StudentId)); // } //} return(RedirectToAction("Details", new { ClassId = maClasseStudent.Classe.ClassId })); }
/// <summary> /// 获取列表(全部) /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public JsonRsp <RoleViewModel> GetAllList() { JsonRsp <RoleViewModel> rsp = new JsonRsp <RoleViewModel>(); AdminRole model = new AdminRole(); OQL q = OQL.From(model) .Select() .OrderBy(model.ID, "asc") .END; List <AdminRole> list = q.ToList <AdminRole>();//使用OQL扩展 rsp.data = list.ConvertAll <RoleViewModel>(o => { return(new RoleViewModel() { ID = o.ID, RoleName = o.RoleName, CreateTIme = o.CreateTIme.ToString("yyyy-MM-dd HH:mm:ss"), }); } ); rsp.success = true; rsp.code = 0; return(rsp); }
/// <summary> /// Creates the or update admin role. /// </summary> /// <param name="role">The role.</param> /// <returns>System.Nullable<Guid>.</returns> public Guid? CreateOrUpdateAdminRole(AdminRole role) { try { role.CheckNullObject("role"); using (var controller = new AdminRoleAccessController()) { return controller.CreateOrUpdateAdminRole(role, ContextHelper.GetCurrentOperatorKey()); } } catch (Exception ex) { throw ex.Handle( role); } }
public void BeAbleToReturnAllRolesOfASingleUserInRepository() { User singleUser = new User("Diego", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); IEnumerable <User> user = new List <User> { singleUser }; var mockUnitOfWork = new Mock <IUnitOfWork>(); IEnumerable <string> roles = new List <string>() { "Admin" }; mockUnitOfWork.Setup(un => un.UserRepository.Get(It.IsAny <Expression <Func <User, bool> > >(), null, "")).Returns(user); UserService userService = new UserService(mockUnitOfWork.Object); IEnumerable <string> returnedRoles = userService.GetRolesOfUser(singleUser.Email, singleUser.Email); mockUnitOfWork.VerifyAll(); CollectionAssert.AreEqual((ICollection)roles, (ICollection)returnedRoles); }
public void BeAbleToReturnSingleUserInRepository() { User singleUser = new User("Diego", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); var mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork.Setup(un => un.UserRepository.GetByID(singleUser.ID)).Returns(singleUser); mockUnitOfWork .Setup(un => un.CurrentSignedInUserHasRequiredPrivilege(singleUser.Email, UserManagementPrivilege.GetInstance())) .Returns(true); UserService userService = new UserService(mockUnitOfWork.Object); User returnedUser = userService.GetSingleUser(singleUser.ID, singleUser.Email); mockUnitOfWork.VerifyAll(); Assert.AreSame(singleUser, returnedUser); }
public void NotDeleteAnythingIfSignedInUserAsksToDeleteHimself() { var mockUnitOfWork = new Mock <IUnitOfWork>(); User user = new User("Bruno", "*****@*****.**", "Holaaaa12!", AdminRole.GetInstance()); SetMockDeleteRoutine3(mockUnitOfWork, user); UserService userService = new UserService(mockUnitOfWork.Object); bool deleted = userService.DeleteUser(user.ID, It.IsAny <string>()); mockUnitOfWork.Verify(un => un.UserRepository.Delete(It.IsAny <int>()), Times.Never()); mockUnitOfWork.Verify(un => un.Save(), Times.Never()); Assert.IsFalse(deleted); }
// TODO: handle better return results public static bool AddRoom(string roomName, string password = "", AdminRole permission = AdminRole.None, bool incremental = false, uint id = 0u, bool displayInList = false) { if (roomName == "Message") return true; if (password.Length > ConfigManager.Config.Room.MaxRoomPasswordLength) { LogManager.Write("Lobby Manager", "Failed to add room {0}, password length is too long!", roomName); return false; } if (permission > AdminRole.Mojang) { LogManager.Write("Lobby Manager", "Failed to add room {0}, permision id is invalid!"); return false; } if (roomStore.Count > ConfigManager.Config.Room.MaxRooms) { LogManager.Write("Lobby Manager", "Failed to add room {0}, max room limit reached!", roomName); return false; } if (!roomStore.TryAdd(roomName, new RoomInfo(roomName, password, permission, incremental, id))) { //LogManager.Write("Lobby Manager", "Failed to add room {0}, it already exists!", roomName); return false; } if (displayInList && !isInitialised) roomList.Add(roomName); return true; }
public AdminRole Add(AdminRole entity) { throw new NotImplementedException(); }
// GET: Ingredient public ActionResult Index() { var adminRole = new AdminRole(); return(View(adminRole.GetIngredients())); }
public void BeAbleToGetAllUsersFromRepository() { User singleUser = new User("Diego", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); var mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork .Setup(un => un.CurrentSignedInUserHasRequiredPrivilege(singleUser.Email, UserManagementPrivilege.GetInstance())) .Returns(true); mockUnitOfWork.Setup(un => un.UserRepository.Get(null, null, "")); UserService userService = new UserService(mockUnitOfWork.Object); IEnumerable <User> returnedUsers = userService.GetAllUsers(singleUser.Email); mockUnitOfWork.VerifyAll(); }
private void SetMockUpdateRoutine2(Mock <IUnitOfWork> mockUnitOfWork, User toBeUpdatedUser) { mockUnitOfWork .Setup(un => un.UserRepository.GetByID(It.IsAny <int>())) .Returns(() => toBeUpdatedUser); mockUnitOfWork .Setup(un => un.CurrentSignedInUserHasRequiredPrivilege(It.IsAny <string>(), UserManagementPrivilege.GetInstance())) .Returns(true); mockUnitOfWork .Setup(un => un.RoleRepository.Get(It.IsAny <System.Linq.Expressions.Expression <Func <Role, bool> > >(), null, "")).Returns(new[] { AdminRole.GetInstance() }); }
public void NotUpdateNotFilledInformation() { User toBeUpdatedUser = new User("Diego", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); User updatedUser = new User("Diego", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); updatedUser.Name = ""; var mockUnitOfWork = new Mock <IUnitOfWork>(); SetMockUpdateRoutine2(mockUnitOfWork, toBeUpdatedUser); UserService userService = new UserService(mockUnitOfWork.Object); bool updated = userService.UpdateUser(toBeUpdatedUser.ID, updatedUser, It.IsAny <string>()); mockUnitOfWork.Verify(un => un.UserRepository.Update(It.IsAny <User>()), Times.Exactly(1)); mockUnitOfWork.Verify(un => un.Save(), Times.Exactly(1)); Assert.AreEqual(toBeUpdatedUser.Name, "Diego"); }
protected void btAdd_Click(object sender, EventArgs e) { AdminInfoBLL _AdminInfoBLL = new AdminInfoBLL(); AdminInfo _AdminInfo = new AdminInfo(); _AdminInfo.AdminAccount = this.txtAccount.Text; _AdminInfo.PassWord = this.txtPass.Text; string _AdminID = Request.QueryString["AdminID"].ToString(); int AdminID = int.Parse(_AdminID); _AdminInfo.IsSYS = _AdminInfoBLL.IsSys(AdminID); if (_AdminInfo.IsSYS) { if (_AdminInfoBLL.UpdateAdminInfo(AdminID, _AdminInfo)) { Response.Write("<script language='javascript'>"); Response.Write("alert('更新成功');"); Response.Write("document.location.href='AdminList.aspx';"); Response.Write("</script>"); } } else { int RoleID = int.Parse(DropDownRole.SelectedValue.ToString()); AdminRoleBLL _AdminRoleBLL = new AdminRoleBLL(); bool StepOne = false; bool StepTwo = false; if (_AdminInfoBLL.UpdateAdminInfo(AdminID, _AdminInfo)) { StepOne = true; } int AdminRoleCount = _AdminRoleBLL.GetCountByAdminID(AdminID); if (AdminRoleCount > 0) { if (_AdminRoleBLL.UpdateAdminRole(AdminID, RoleID)) { StepTwo = true; } } else { AdminRole _AdminRole = new AdminRole(); _AdminRole.AdminID = AdminID; _AdminRole.RoleID = RoleID; if (_AdminRoleBLL.AddAdminRole(_AdminRole)) { StepTwo = true; } } if (StepOne && StepTwo) { Response.Write("<script language='javascript'>"); Response.Write("alert('更新成功');"); Response.Write("document.location.href='AdminList.aspx';"); Response.Write("</script>"); } } }
public void NotUpdateUserWithEmailOfAnotherUserInRepository() { User updatedUserInfo = new User("Diego", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); var mockUnitOfWork = new Mock <IUnitOfWork>(); SetMockUpdateRoutine6(mockUnitOfWork); UserService userService = new UserService(mockUnitOfWork.Object); bool updated = userService.UpdateUser(updatedUserInfo.ID + 1, updatedUserInfo, It.IsAny <string>()); mockUnitOfWork.Verify(un => un.UserRepository.Update(It.IsAny <User>()), Times.Never()); mockUnitOfWork.Verify(un => un.Save(), Times.Never()); Assert.IsFalse(updated); }
private void SetMockUpdateRoutine6(Mock <IUnitOfWork> mockUnitOfWork) { User userWithSameEmail = new User("Bruno", "*****@*****.**", "#ElBizagrita1996", AdminRole.GetInstance()); userWithSameEmail.ID = 5; mockUnitOfWork .Setup(un => un.UserRepository.GetByID(It.IsAny <int>())) .Returns(() => new User()); mockUnitOfWork .Setup(un => un.CurrentSignedInUserHasRequiredPrivilege(It.IsAny <string>(), UserManagementPrivilege.GetInstance())) .Returns(true); mockUnitOfWork .Setup(un => un.UserRepository.Get( It.IsAny <System.Linq.Expressions.Expression <Func <User, bool> > >(), null, "")) .Returns(new[] { userWithSameEmail }); }
public ActionResult Edit(int id) { var adminRole = new AdminRole(); return(View(adminRole.GetIngredient(id))); }
public void FailWithUnauthorizedAccessExceptionIfUserTriesToPostANewUserWithoutHavingUserManagementPrivilege() { User userToCreate = new User("Bruno", "*****@*****.**", "#ElBizagra1995", AdminRole.GetInstance()); var mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork .Setup(un => un.CurrentSignedInUserHasRequiredPrivilege(It.IsAny <string>(), UserManagementPrivilege.GetInstance())) .Returns(false); UserService userService = new UserService(mockUnitOfWork.Object); int id = userService.CreateUser(userToCreate, It.IsAny <string>()); }
public void Update(AdminRole entity) { throw new NotImplementedException(); }
public RoomInfo(string name, string password, AdminRole permission, bool incremental, uint id) { Name = name; Password = password; Permission = permission; Incremental = incremental; Id = id; playerStore = new ConcurrentDictionary<string, Player>(); }