public async Task Handle_GivenRoleDoesExistAndNameHasNotChanged_ExpectSuccessfulResultAndRoleUpdated() { var role = new Mock <IRole>(); role.Setup(x => x.Name).Returns("name"); var roleQueries = new Mock <IRoleQueries>(); roleQueries.Setup(x => x.CheckForPresenceOfRoleByName(It.IsAny <string>())) .ReturnsAsync(() => new StatusCheckModel(false)); var roleRepository = new Mock <IRoleRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); roleRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); roleRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(role.Object)); var handler = new UpdateRoleCommandHandler(roleRepository.Object, roleQueries.Object); var cmd = new UpdateRoleCommand(TestVariables.RoleId, "name", new List <Guid>()); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsSuccess); roleRepository.Verify(x => x.Update(It.IsAny <IRole>()), Times.Once()); }
public async Task <IActionResult> UpdateRoleAsync(Guid id, RoleCreatingRequest request) { var command = new UpdateRoleCommand(id, request.Name, request.Description, request.PermissionIds); var result = await _commandBus.PublishAsync(command).ConfigureAwait(false); return(GenerateActionResult(result)); }
public async Task Handle_GivenRoleDoesExistAndNameHasChangedButIsNotUnique_ExpectFailedResult() { var role = new Mock <IRole>(); role.Setup(x => x.Name).Returns(string.Empty); var roleQueries = new Mock <IRoleQueries>(); roleQueries.Setup(x => x.CheckForPresenceOfRoleByName(It.IsAny <string>())) .ReturnsAsync(() => new StatusCheckModel(true)); var roleRepository = new Mock <IRoleRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); roleRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); roleRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(role.Object)); var handler = new UpdateRoleCommandHandler(roleRepository.Object, roleQueries.Object); var cmd = new UpdateRoleCommand(TestVariables.RoleId, "name", new List <Guid>()); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsFailure); Assert.Equal(ErrorCodes.RoleAlreadyExists, result.Error.Code); }
public async Task <IActionResult> Edit(string roleName) { if (string.IsNullOrEmpty(roleName)) { return(NotFound()); } var entity = await Mediator.Send(new GetRoleDetailQuery() { RoleName = roleName }); if (entity == null) { return(BadRequest()); } var permissions = await Mediator.Send(new GetPermissionListQuery()); var request = new UpdateRoleCommand { RoleName = entity.Name, Description = entity.Description, Permissions = entity.Permissions.ToList(), PermissionsList = permissions }; return(View(request)); }
public async Task <IActionResult> Put([FromRoute] Guid id, [FromBody] UpdateRoleCommand command) { command.Id = id; await _mediator.Send(command); return(Ok()); }
public async Task <IActionResult> Update(Guid id, [FromBody] UpdateRoleCommand command) { command.RoleId = id; await Mediator.Send(command); return(NoContent()); }
public async Task UpdateRoleAsync(UpdateRoleCommand command) { var role = await _roleRepository.GetRoleAsync(command.Id); role.UpdateName(command.Name); if (command.IsEnabled) { role.Enable(); } else { role.Disable(); } var permissionIds = role.RolePermissions.Select(x => x.PermissionId); var permissionIdsToAssign = command.PermissionIds.Except(permissionIds); var permissionsToAssign = await _permissionRepository.GetPermissionsAsync(x => permissionIdsToAssign.Contains(x.Id)); foreach (var permission in permissionsToAssign) { role.AssignPermission(permission); } var permissionIdsToUnassign = permissionIds.Except(command.PermissionIds); var permissionsToUnassign = await _permissionRepository.GetPermissionsAsync(x => permissionIdsToUnassign.Contains(x.Id)); foreach (var permission in permissionsToUnassign) { role.UnassignPermission(permission); } _roleRepository.Update(role); await _unitOfWork.CommitAsync(); }
public async Task <ActionResult> UpdateUserRole(string userName, [FromBody] UpdateRoleCommand command) { command.UserName = userName; await Mediator.Send(command); return(NoContent()); }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public async Task <dynamic> UpdateRole(DTOAPIReq_Role data) { Role role = this.accesser.Get(data.key); if (role != null) { var cmd = new UpdateRoleCommand { key = data.key, name = data.name, displayName = data.displayName, description = data.description, routes = data.routes.Select(x => new DTOIn_PageRouteId { PageRouteID = x }).ToArray() }; await this.publishEndpoint.Publish(cmd); return(1); } else { throw new NullReferenceException("角色不存在..请刷新页面重试"); } }
private async Task <ResultWithError <ErrorData> > Process(UpdateRoleCommand request, CancellationToken cancellationToken) { var presenceResult = await this._roleQueries.CheckForPresenceOfRoleByNameWithIdExclusion(request.Name, request.RoleId, cancellationToken); if (presenceResult.IsPresent) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.RoleAlreadyExists))); } var roleMaybe = await this._roleRepository.Find(request.RoleId, cancellationToken); if (roleMaybe.HasNoValue) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.RoleNotFound))); } var role = roleMaybe.Value; role.UpdateName(request.Name); role.SetResources(request.Resources); this._roleRepository.Update(role); return(ResultWithError.Ok <ErrorData>()); }
public async Task UpdateRoleAsync_Should_Return_OkObjectResult_With_GetRoleResponse() { var rowVersion = new byte[] { 1, 2, 4, 8, 16, 32 }; var roleId = Guid.NewGuid(); var updateRoleRequest = new UpdateRoleRequest { Id = roleId, Name = DefaultRoleEnumeration.Administrator.DisplayName }; var updateRoleCommand = new UpdateRoleCommand(updateRoleRequest.Id, rowVersion, updateRoleRequest.Name); var roleOutputQuery = new RoleOutputQuery(updateRoleRequest.Id, new byte[] { 1, 2, 4, 8, 16, 64 }, updateRoleRequest.Name); var getRoleResponse = new GetRoleResponse(roleOutputQuery.Id, roleOutputQuery.RowVersion, roleOutputQuery.Name); _mapperMock.Setup(x => x.Map <UpdateRoleRequest, UpdateRoleCommand>(It.IsAny <UpdateRoleRequest>())).Returns(updateRoleCommand); _communicationBusMock.Setup(x => x.SendCommandAsync(It.IsAny <UpdateRoleCommand>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); _getRoleQueryHandlerMock .Setup(x => x.HandleAsync(It.IsAny <GetRoleInputQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(roleOutputQuery); _mapperMock.Setup(x => x.Map <RoleOutputQuery, GetRoleResponse>(It.IsAny <RoleOutputQuery>())).Returns(getRoleResponse); var result = await _controller.UpdateRoleAsync(roleId, updateRoleRequest, rowVersion); var okObjectResult = result.As <OkObjectResult>(); okObjectResult.Value.Should().BeEquivalentTo(getRoleResponse); }
public async Task <IActionResult> Put([FromServices] IMediatorHandler bus, Guid idGrupo, EditarGrupoModel editarGrupoModel) { var updateRoleCommand = new UpdateRoleCommand(idGrupo, editarGrupoModel.Nome, editarGrupoModel.Permissoes); var result = await bus.SendCommand(updateRoleCommand); return(Response(result)); }
public void UpdateRole(Guid id, string name, string description, string externalGroupName) { userContext.CheckPermission(Permissions.RoleMaintenance); var command = new UpdateRoleCommand(id, name, description, externalGroupName); commandBus.Value.Send(Envelope.Create(command)); }
public async Task <ActionResult> Update([FromRoute] Guid id, UpdateRoleCommand command, CancellationToken cancellationToken) { command.SetRoleId(id); await Mediator.Send(command, cancellationToken); return(NoContent()); }
public Task <RoleCommandResponse> Handle(UpdateRoleCommand request, CancellationToken cancellationToken) { UserRole role = _repo.UpdateRole(request.Data); var response = new RoleCommandResponse(role); response.Status = GetResponseStatus(role); return(Task.FromResult(response)); }
public void Validate_GivenAllPropertiesAreValid_ExpectValidationSuccess() { var cmd = new UpdateRoleCommand(TestVariables.RoleId, "name", new List <Guid>()); var validator = new UpdateRoleCommandValidator(); var result = validator.Validate(cmd); Assert.True(result.IsValid); }
public static Domain.User.Role ToRole(this UpdateRoleCommand res) => new Domain.User.Role { Id = res.Id, Name = res.Name, ConfigSystem = res.ConfigSystem, CreateDocuments = res.CreateDocuments, DeleteDocuments = res.DeleteDocuments, };
public async Task <APIResult> Update([FromBody] UpdateRoleCommand command) { var rs = await mediator.Send(command); return(new APIResult() { Result = rs }); }
public async Task <ActionResult> Edit(UpdateRoleCommand command) { if (await Mediator.Send(command) == null) { return(BadRequest()); } return(RedirectToAction("Index")); }
public void Update_ShouldThrowDomainValidationException_WhenCommandIsInvalid(UpdateRoleCommand command, ValidationError[] erros) { var roleCmdGen = new RoleCmdGenerator(); var createCmd = roleCmdGen.CreateRoleCommand; var role = Role.Create(createCmd); var ex = Assert.Throws <DomainValidationException>(() => role.Update(command)); Assert.Equal(erros.Length, ex.ValidationErrors.Count()); Assert.Contains(erros, item => ex.ValidationErrors.Any(err => err.Code == item.Code && err.Member == item.Member)); }
public void Constructor_GiveValidArguments_PropertiesAreSet() { var command = new UpdateRoleCommand(TestVariables.RoleId, "name", new List <Guid> { TestVariables.ResourceId }); Assert.Equal(TestVariables.RoleId, command.RoleId); Assert.Equal("name", command.Name); Assert.Single(command.Resources); }
public async Task <IActionResult> UpdateRole(UpdateRoleCommand command) { if (!ModelState.IsValid) { return(View(command)); } await Mediator.Send(command); return(RedirectToAction(nameof(GetRoleList))); }
public async Task <IActionResult> PutRoleAsync([FromRoute] string id, [FromBody] UpdateRoleCommand request) { if (id != request.RoleId) { return(BadRequest()); } await Mediator.Send(request); return(NoContent()); }
public async Task <bool> Handle(UpdateRoleCommand message, CancellationToken cancellationToken) { var role = await _roleManager.FindByIdAsync(message.Id.ToString()); role.Description = message.Description; role.Permissions = message.Permissions; await _roleManager.UpdateAsync(role); return(true); }
public void Update(UpdateRoleCommand command) { command.Validate(true); this.Name = command.Name; this.AddEvent(new RoleUpdatedEvent(this) { Name = this.Name }); }
public void Validate_GivenNameIsNull_ExpectValidationFailure() { var cmd = new UpdateRoleCommand(TestVariables.RoleId, null, new List <Guid>()); var validator = new UpdateRoleCommandValidator(); var result = validator.Validate(cmd); Assert.False(result.IsValid); Assert.Contains( result.Errors, failure => failure.ErrorCode.Equals(ValidationCodes.FieldIsRequired) && failure.PropertyName == "Name"); }
public void Validate_GivenRoleIdIsEmpty_ExpectValidationFailure() { var cmd = new UpdateRoleCommand(Guid.Empty, "name", new List <Guid>()); var validator = new UpdateRoleCommandValidator(); var result = validator.Validate(cmd); Assert.False(result.IsValid); Assert.Contains( result.Errors, failure => failure.ErrorCode.Equals(ValidationCodes.FieldIsRequired) && failure.PropertyName == "RoleId"); }
public async Task HandleAsync_Should_Throw_PreconditionFailedException_When_RowVersion_Does_Not_Match() { var updateRoleCommand = new UpdateRoleCommand(Guid.NewGuid(), new byte[] { 1, 2, 4, 8, 16, 64 }, "NewName"); var role = new Role(updateRoleCommand.RoleId, new byte[] { 1, 2, 4, 8, 16, 32 }, "OldName"); var getRoleResult = GetResult <Role> .Ok(role); _roleGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getRoleResult); Func <Task> result = async() => await _commandHandler.HandleAsync(updateRoleCommand); await result.Should().ThrowAsync <PreconditionFailedException>(); }
public async Task UpdateAsync(UpdateRoleCommand command) { command.NewName = command.NewName.ToLower(); var role = await _repository.GetAsync(command.Id); if (role is null) { throw new RoleException($"Role id: {command.Id} not exist."); } await _repository.UpdateAsync(new Role { RoleId = role.RoleId, Name = command.NewName }); }
public async Task <RoleEditViewModel> UpdateAsync(Guid id, [FromForm] RoleEditViewModel model) { var command = new UpdateRoleCommand(model.Id.Value, model.Name, model.Desc, model.UserIds); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = _notifications.GetNotificationMessage(); throw new GirvsException(StatusCodes.Status400BadRequest, errorMessage); } return(model); }
public virtual ActionResult Put(RoleForm model) { if (model != null) { if (ModelState.IsValid) { var command = new UpdateRoleCommand(User) { EntityId = model.EntityId, Description = model.Description, RevokedUserEntityIds = model.Grants.Where(g => g.IsDeleted).Select(g => g.User.EntityId), GrantedUserEntityIds = model.Grants.Where(g => !g.IsDeleted).Select(g => g.User.EntityId), }; _services.UpdateHandler.Handle(command); SetFeedbackMessage(command.ChangeCount > 0 ? "Role has been successfully saved." : "No changes were made."); return Redirect(model.ReturnUrl); } return View(Views.form, model); } return HttpNotFound(); }