Example #1
0
        public async Task <OperationResult <string> > Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            var role = await unitOfWork.RoleRepository.GetRoleByIdAsync(request.Id, cancellationToken);

            if (role.Result != null)
            {
                role.Result.Delete();
                role.Result.UpdateSecurityStamp();
                var update = unitOfWork.RoleRepository.Update(role.Result, cancellationToken);
                if (update.Success)
                {
                    try
                    {
                        await unitOfWork.CommitSaveChangeAsync();

                        return(OperationResult <string> .BuildSuccessResult("Success Delete"));
                    }
                    catch (Exception ex)
                    {
                        return(OperationResult <string> .BuildFailure(ex));
                    }
                }
            }
            return(OperationResult <string> .BuildFailure(role.ErrorMessage));
        }
Example #2
0
        public async Task <IActionResult> DeleteRoleAsync([FromRoute] Guid id, [FromHeader(Name = "If-Match")] byte[] rowVersion)
        {
            var deleteRoleCommand = new DeleteRoleCommand(id, rowVersion);
            await _communicationBus.SendCommandAsync(deleteRoleCommand);

            return(NoContent());
        }
Example #3
0
        public async Task <bool> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            var role = await _roleRepository.GetByIdAsync(request.Id);

            if (role == null)
            {
                await _bus.RaiseEvent(new DomainNotification(request.Id.ToString(), "未找到对应的数据"));

                return(false);
            }

            if (role.IsInitData)
            {
                await _bus.RaiseEvent(new DomainNotification(request.Id.ToString(), "系统初始化数据,无法进行操作"));

                return(false);
            }

            await _roleRepository.DeleteAsync(role);

            if (await Commit())
            {
                var key = GirvsEntityCacheDefaults <Role> .ByIdCacheKey.Create(role.Id.ToString());

                _bus.RaiseEvent(new RemoveCacheEvent(key), cancellationToken);
                _bus.RaiseEvent(new RemoveCacheListEvent(GirvsEntityCacheDefaults <Role> .ListCacheKey.Create()),
                                cancellationToken);
                _bus.RaiseEvent(new RemoveServiceCacheEvent(), cancellationToken);
            }

            return(true);
        }
Example #4
0
        public Task <JsonResult> Delete(int roleId)
        {
            var command = new DeleteRoleCommand();

            command.RoleId = roleId;

            return(_apiResponseHelper.RunCommandAsync(command));
        }
Example #5
0
        public void Validate_GivenAllPropertiesAreValid_ExpectValidationSuccess()
        {
            var cmd       = new DeleteRoleCommand(TestVariables.RoleId);
            var validator = new DeleteRoleCommandValidator();
            var result    = validator.Validate(cmd);

            Assert.True(result.IsValid);
        }
Example #6
0
        public async Task <ActionResult> Delete([FromRoute] Guid id, DeleteRoleCommand command, CancellationToken cancellationToken)
        {
            command.SetRoleId(id);

            await Mediator.Send(command, cancellationToken);

            return(Ok());
        }
Example #7
0
        public async Task <IActionResult> Delete(int roleId)
        {
            var command = new DeleteRoleCommand();

            command.RoleId = roleId;

            return(await _apiResponseHelper.RunCommandAsync(this, command));
        }
Example #8
0
        public Task <RoleCommandResponse> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            UserRole role     = _repo.DeleteRole(request.RoleId);
            var      response = new RoleCommandResponse(role);

            response.Status = GetResponseStatus(role);
            return(Task.FromResult(response));
        }
        public async Task HandleAsync(DeleteRoleCommand message, CancellationToken token = default(CancellationToken))
        {
            var role = await this.GetRoleAsync(message.RoleId);

            role.Delete();
            _roles.Delete(role);
            await _roles.SaveChangesAsync();
        }
        public async Task <IActionResult> Delete([FromRoute] Guid id)
        {
            var command = new DeleteRoleCommand {
                Id = id
            };
            await _mediator.Send(command);

            return(Ok());
        }
Example #11
0
        public async Task <APIResult> Delete([FromBody] DeleteRoleCommand command)
        {
            var rs = await mediator.Send(command);

            return(new APIResult()
            {
                Result = rs
            });
        }
        public async Task <IActionResult> DELETE_ROLE([FromBody] DeleteRoleCommand command)
        {
            var response = await _mediator.Send(command);

            if (response.Status.IsSuccessful)
            {
                return(Ok(response));
            }
            return(BadRequest(response));
        }
Example #13
0
 public ResultDto DeleteRole(long id)
 {
     return(Result(() => {
         var command = new DeleteRoleCommand
         {
             Id = id
         };
         CommandDispatcher.Send(command);
     }));
 }
Example #14
0
        public async Task DeleteAsync(DeleteRoleCommand command)
        {
            var role = await _repository.GetAsync(command.Id);

            if (role is null)
            {
                throw new RoleException($"Role id: {command.Id} not exist.");
            }

            await _repository.DeleteAsync(role);
        }
Example #15
0
        public async Task DeleteAsync(Guid id)
        {
            DeleteRoleCommand command = new DeleteRoleCommand(id);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = _notifications.GetNotificationMessage();
                throw new GirvsException(StatusCodes.Status400BadRequest, errorMessage);
            }
        }
Example #16
0
        public async Task HandleAsync_Should_Throw_PreconditionFailedException_When_RowVersion_Does_Not_Match()
        {
            var deleteRoleCommand = new DeleteRoleCommand(Guid.NewGuid(), new byte[] { 1, 2, 4, 8, 16, 64 });
            var role          = new Role(deleteRoleCommand.RoleId, new byte[] { 1, 2, 4, 8, 16, 32 }, "Name");
            var getRoleResult = GetResult <Role> .Ok(role);

            _roleGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getRoleResult);

            Func <Task> result = async() => await _commandHandler.HandleAsync(deleteRoleCommand);

            await result.Should().ThrowAsync <PreconditionFailedException>();
        }
Example #17
0
        public void Validate_GivenRoleIdIsEmpty_ExpectValidationFailure()
        {
            var cmd       = new DeleteRoleCommand(Guid.Empty);
            var validator = new DeleteRoleCommandValidator();
            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 <ActionResult> Delete(DeleteRoleCommand deleteRoleCommand)
        {
            try
            {
                bool success = await this.mediator.Send(deleteRoleCommand);

                return(Ok(success));
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex));
            }
        }
        public async Task <bool> Handle(DeleteRoleCommand message, CancellationToken cancellationToken)
        {
            var role = await _roleManager.FindByIdAsync(message.Id.ToString());

            var result = await _roleManager.DeleteAsync(role);

            if (!result.Succeeded)
            {
                throw new ArgumentException(result.Errors.First().Description, nameof(role));
            }

            return(true);
        }
Example #20
0
        public async Task HandleAsync_Should_Delete_Role()
        {
            var deleteRoleCommand = new DeleteRoleCommand(Guid.NewGuid(), Array.Empty <byte>());
            var role          = new Role(deleteRoleCommand.RoleId, deleteRoleCommand.RowVersion, "Name");
            var getRoleResult = GetResult <Role> .Ok(role);

            _roleGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getRoleResult);
            _roleRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny <Role>())).Returns(Task.CompletedTask);

            Func <Task> result = async() => await _commandHandler.HandleAsync(deleteRoleCommand);

            await result.Should().NotThrowAsync <Exception>();
        }
        public async Task <ResultWithError <ErrorData> > Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            var result = await this.Process(request, cancellationToken);

            var dbResult = await this._roleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            if (!dbResult)
            {
                return(ResultWithError.Fail(new ErrorData(
                                                ErrorCodes.SavingChanges, "Failed To Save Database")));
            }

            return(result);
        }
        public async Task DeleteRoleHandler_FluentValidationHandler_ThrowsValidationException()
        {
            //Setup
            var command = new DeleteRoleCommand(new DeleteRoleDto {
                ApplicationId = Guid.NewGuid()
            });
            var validator = new DeleteRoleCommandValidator();

            //Action
            var result = await validator.ValidateAsync(command);

            //Assert
            Assert.Contains(result.Errors, o => o.ErrorMessage == "RoleId cannot be empty");
        }
Example #23
0
        public async Task <ActionResult> DeleteRoleAysnc([FromQuery] DeleteRoleCommand request)
        {
            try
            {
                request.SetUser(User.GetUserId());
                var response = await _mediator.Send(request);

                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Operation failed into controller {Routes.Create_Role} with message: {ex.Message}");
                return(BadRequest(ex.Message));
            }
        }
Example #24
0
        public async Task HandleAsync_Should_Throw_ResourceNotFoundException_When_Role_Is_Not_Found()
        {
            var deleteRoleCommand = new DeleteRoleCommand(Guid.NewGuid(), Array.Empty <byte>());
            var errors            = new Collection <IError>
            {
                new Error(RoleErrorCodeEnumeration.NotFound, RoleErrorMessage.NotFound)
            };
            var getRoleResult = GetResult <Role> .Fail(errors);

            _roleGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getRoleResult);

            Func <Task> result = async() => await _commandHandler.HandleAsync(deleteRoleCommand);

            var exceptionResult = await result.Should().ThrowAsync <ResourceNotFoundException>();

            exceptionResult.And.Errors.Should().BeEquivalentTo(errors);
        }
Example #25
0
        public async Task <IActionResult> Delete(DeleteRoleCommand command)
        {
            try
            {
                await _mediator.Send(command);

                return(Ok());
            }
            catch (KeyNotFoundException ex)
            {
                return(NotFound());
            }
            catch (ArgumentException argumentException)
            {
                return(BadRequest(argumentException.Message));
            }
        }
        public async Task <RequestResponse> DeleteRoleAsync(DeleteRoleCommand role)
        {
            var existRole = await _roleManager.FindByIdAsync(role.Id.ToString());

            if (existRole == null)
            {
                throw new Exception("The role doesn't exist");
            }
            var users = await _userManager.GetUsersInRoleAsync(existRole.Name);

            if (users.Count > 0)
            {
                throw new Exception("The role has users assigned");
            }

            await _roleManager.DeleteAsync(existRole);

            return(RequestResponse.Success());
        }
Example #27
0
        public async Task ShouldDeleteExisting()
        {
            // Arrange
            Role entity     = Role.Create(Guid.NewGuid(), "Name", "Code");
            var  repository = new Mock <IRoleRepository>();

            repository.Setup(e =>
                             e.GetByIdAsync(It.IsAny <Guid>(), It.IsAny <CancellationToken>())).ReturnsAsync(entity);
            DeleteRoleCommand cmd = new DeleteRoleCommand(entity.Id);

            RoleCommandHandler actual = new RoleCommandHandler(repository.Object);

            // Act
            await actual.HandleAsync(cmd);

            // Assert
            repository.Verify(e =>
                              e.Delete(It.Is <Role>(a => a.Equals(entity))),
                              Times.Once
                              );
        }
        public async Task Handle_GivenSavingSucceeds_ExpectSuccessfulResult()
        {
            var role        = new Mock <IRole>();
            var roleQueries = new Mock <IRoleQueries>();

            roleQueries.Setup(x => x.CheckForRoleUsageById(It.IsAny <Guid>()))
            .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 DeleteRoleCommandHandler(roleRepository.Object, roleQueries.Object);
            var cmd     = new DeleteRoleCommand(TestVariables.RoleId);

            var result = await handler.Handle(cmd, CancellationToken.None);

            Assert.True(result.IsSuccess);
        }
        public async Task Handle_GivenRoleDoesNotExist_ExpectFailedResult()
        {
            var roleQueries = new Mock <IRoleQueries>();

            roleQueries.Setup(x => x.CheckForRoleUsageById(It.IsAny <Guid>()))
            .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 <IRole> .Nothing);
            var handler = new DeleteRoleCommandHandler(roleRepository.Object, roleQueries.Object);
            var cmd     = new DeleteRoleCommand(TestVariables.RoleId);

            var result = await handler.Handle(cmd, CancellationToken.None);

            Assert.True(result.IsFailure);
            Assert.Equal(ErrorCodes.RoleNotFound, result.Error.Code);
        }
Example #30
0
        public async Task <ResultWithError <ErrorData> > Process(
            DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            var roleMaybe = await this._roleRepository.Find(request.RoleId, cancellationToken);

            if (roleMaybe.HasNoValue)
            {
                return(ResultWithError.Fail(new ErrorData(ErrorCodes.RoleNotFound)));
            }

            var presenceResult = await this._roleQueries.CheckForRoleUsageById(request.RoleId);

            if (presenceResult.IsPresent)
            {
                return(ResultWithError.Fail(new ErrorData(ErrorCodes.RoleInUse)));
            }

            var role = roleMaybe.Value;

            this._roleRepository.Delete(role);

            return(ResultWithError.Ok <ErrorData>());
        }