public async Task <IActionResult> Delete(int UserId) { var command = new DeleteUserCommand(UserId); var response = await _mediator.Send(command).ConfigureAwait(false); return(Ok(response)); }
public async Task DeleteUser_InvalidUserId_ThrowException(string userId) { // Arrange var userRepositoryMock = new Mock <IUserRepository>(); var userManagerMock = new Mock <IUserManager>(); var currentUserResolverMock = new Mock <ICurrentUserResolver>(); var deleteUserCommandValidator = new DeleteUserCommandValidator( userManagerMock.Object, userRepositoryMock.Object, currentUserResolverMock.Object); var validationService = new ValidationService(deleteUserCommandValidator); var userService = InstantiateUserService( new Tuple <Type, object>(typeof(IValidationService), validationService) ); var command = new DeleteUserCommand() { UserId = userId }; // Act // Assert await Assert.ThrowsAsync <ValidationException>( () => userService.DeleteUser(command) ); }
public async Task <Result> Delete([FromBody] DeleteUserCommand cmd) { _logger.LogInformation($"接收到请求{HttpContext.Request.Host}{HttpContext.Request.Path},参数 {JsonConvert.SerializeObject(cmd)}"); var result = await _mediator.Send(cmd, HttpContext.RequestAborted); return(result); }
public async Task <IActionResult> DeleteUser([FromRoute] string username) { var command = new DeleteUserCommand(username); await Mediator.Send(command); return(NoContent()); }
public void ReturnSuccessMessage_WhenPassedValidParameters() { // Arrange var sessionMock = new Mock <IUserSession>(); var currentUser = new User() { UserType = UserType.User }; sessionMock.Setup(s => s.CurrentUser).Returns(currentUser); Mock <IUserService> userServiceMock = new Mock <IUserService>(); var user = new User() { Id = 1 }; userServiceMock .Setup(c => c.GetUserByCredentials(It.IsAny <string>(), It.IsAny <string>())) .Returns(user); var sut = new DeleteUserCommand(sessionMock.Object, userServiceMock.Object); var parameters = new string[2] { "1", "pass" }; // Act var result = sut.Execute(parameters); // Assert StringAssert.Contains(result, "successfully deleted"); }
public void DeleteUser(Controller controller, int userId) { var command = new DeleteUserCommand(); command.UserId = userId; _controllerResponseHelper.ExecuteIfValid(controller, command); }
public string DispatchCommand(string[] commandParameters) { string command = commandParameters[0]; commandParameters = commandParameters.Skip(1).ToArray() `; switch (command) { case "RegisterUser": return(RegisterUserCommand.Execute(commandParameters)); case "AddTown": return(AddTownCommand.Execute(commandParameters)); case "ModifyUser": return(ModifyUserCommand.Execute(commandParameters)); case "DeleteUser": return(DeleteUserCommand.Execute(commandParameters)); case "AddTag": return(AddTagCommand.Execute(commandParameters)); default: throw new InvalidOperationException($"Command {command} not valid!"); } }
public async Task DeleteUser_NonExisting_DoNothing() { // Arrange const string id = "718aeae3-7ad8-4e3e-8935-705133d95a3c"; var userRepositoryMock = new Mock <IUserRepository>(); userRepositoryMock .Setup(r => r.GetUserById(It.IsAny <string>())) .ReturnsAsync((User)null); userRepositoryMock.SetReturnsDefault <Task>(Task.FromResult(0)); var userManagerMock = new Mock <IUserManager>(); userManagerMock.SetReturnsDefault <Task>(Task.FromResult(0)); var userService = InstantiateUserService( new Tuple <Type, object>(typeof(IUserRepository), userRepositoryMock.Object), new Tuple <Type, object>(typeof(IUserManager), userManagerMock.Object) ); var command = new DeleteUserCommand() { UserId = id }; // Act await userService.DeleteUser(command); // Assert userRepositoryMock.Verify(um => um.GetUserById(id)); userRepositoryMock.Verify(um => um.DeleteUser(It.IsAny <User>(), It.IsAny <bool>()), Times.Never); userManagerMock.Verify(um => um.RemoveUser(It.IsAny <string>()), Times.Never); }
public Task <CommandResult <User> > Handle(DeleteUserCommand request, CancellationToken cancellationToken) { var response = new CommandResult <User>("Excluído com sucesso", true, null); request.Validate(); if (request.Valid) { var user = _userRepository.GetById(request.Id); if (user != null && user.Id > 0) { if (_userRepository.Delete(user.Id)) { response.ObjetoResposta = user; return(Task.FromResult(response)); } else { response.Sucesso = false; response.Mensagem = "Não foi possível excluir este usuário."; return(Task.FromResult(response)); } response.Notificacoes.AddRange(user.Notifications.Select(x => x.Message).ToList()); } } response.Notificacoes.AddRange(request.Notifications.Select(x => x.Message).ToList()); response.Sucesso = false; response.Mensagem = "Não foi possível excluir o usuário."; return(Task.FromResult(response)); }
public async Task <IActionResult> DeleteUser([FromRoute] int id) { LogBeginOfRequest(); if (!ModelState.IsValid) { LogEndOfRequest("Failed Bad request", 400); return(BadRequest(ModelState)); } try { var command = new DeleteUserCommand(id); await userService.DeleteUserCommand.HandleAsync(command); LogEndOfRequest("Success", 200); return(Ok()); } catch (InvalidOperationException) { LogEndOfRequest($"Failed can't delete user if status is different than 'Suspended'", 400); return(BadRequest()); } catch (KeyNotFoundException) { LogEndOfRequest($"Failed User with id {id} not found", 404); return(NotFound()); } }
public void Execute_IntegrationTest_SQLite() { string filePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".dbtest"); using (SQLiteDbContext dbContext = new SQLiteDbContext(filePath)) { dbContext.Initialise(); dbContext.BeginTransaction(); IUserRepository userRepo = new UserRepository(dbContext); ICreateUserCommand createUserCommand = new CreateUserCommand(dbContext, new UserValidator(userRepo), new PasswordProvider()); IDeleteUserCommand deleteUserCommand = new DeleteUserCommand(dbContext); // create the user UserModel user = createUserCommand.Execute("test", Guid.NewGuid().ToString(), Roles.User); int rowCount = dbContext.ExecuteScalar <int>("SELECT COUNT(*) FROM Users"); Assert.AreEqual(1, rowCount); // run the delete command and check the end tables - should be 0 records deleteUserCommand.Execute(user.Id); rowCount = dbContext.ExecuteScalar <int>("SELECT COUNT(*) FROM Users"); Assert.AreEqual(0, rowCount); } }
public ICommandResult Handle(DeleteUserCommand command) { ICommandResult result = new CommandResult(); _loggingService.Log(this.GetType(), ELogType.Neutral, ELogLevel.Debug, new { command.User, command.RequestHost }, "UserCommandHandler.Handle(Delete)"); try { if (_userRepository.CheckExists(command.User)) { if (_userRepository.Delete(command.User)) { result = new CommandResult(200); } } else if (_userRepository.Valid) { result = new CommandResult(400, new Notification("User", "Could not be found")); } } catch (Exception e) { _loggingService.Log(this.GetType(), ELogType.Neutral, ELogLevel.Error, new { command.User, command.RequestHost }, e); } return(result); }
public async Task <Result <object> > Handle(DeleteUserCommand request, CancellationToken cancellationToken) { var cacheKey = $"User-{request.UserId}"; if (!await _cacheService.IsExistsAsync(cacheKey)) { var userInDb = await _userRepository.GetAsync(u => u.Id == request.UserId); userInDb.CheckForNull(); } var token = await _tokenRepository.GetAsync(t => t.Id == request.UserId); if (token is not null) { await _tokenRepository.DeleteAsync(t => t.Id == token.Id); await _sender.PublishAsync(token, cancellationToken); } await _userRepository.DeleteAsync(u => u.Id == request.UserId); await _cacheService.RemoveAsync(cacheKey); return(Result <object> .Success()); }
public async Task ShouldHaveErrorWhenTryingToDeleteOtherAccount() { //arrange var registerCommand = new RegisterUserCommand() { Username = "******", Email = "jane101@localhost", Password = "******" }; await SendAsync(registerCommand); var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!"); var deleteCommand = new DeleteUserCommand() { Username = "******" }; //act //assert FluentActions.Invoking(() => SendAsync(deleteCommand)).Should().ThrowAsync <RestException>(); }
public async Task <IActionResult> DeleteUserAsync([FromRoute] Guid id) { var deleteUserCommand = new DeleteUserCommand(id); await _communicationBus.SendCommandAsync(deleteUserCommand); return(NoContent()); }
public string Dispatch(string input) { string[] args = input.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); string commandName = args.Length > 0 ? args[0] : String.Empty; string[] commandArgs = args.Skip(1).ToArray(); switch (commandName) { case "Exit": ExitCommand exitCommand = new ExitCommand(); return(exitCommand.Execute(new string[0])); case "RegisterUser": RegisterUserCommand registerUserCommand = new RegisterUserCommand(authenticationManager); return(registerUserCommand.Execute(commandArgs)); case "Login": LoginCommand loginCommand = new LoginCommand(authenticationManager); return(loginCommand.Execute(commandArgs)); case "Logout": LogoutCommand logoutCommand = new LogoutCommand(authenticationManager); return(logoutCommand.Execute(commandArgs)); case "DeleteUser": DeleteUserCommand deleteUserCommand = new DeleteUserCommand(authenticationManager); return(deleteUserCommand.Execute(commandArgs)); default: throw new NotSupportedException($"Command {commandName} is not supported"); } }
public async Task <ActionResult <IEnumerable <UserDTO> > > DeleteUser(Guid id) { var command = new DeleteUserCommand(id); var result = await _mediator.Send(command); return(Ok(result)); }
public async Task <IActionResult> Delete(int id) { var command = new DeleteUserCommand(id); var result = await _mediatr.Send(command); return(Ok(result)); }
public IActionResult DeleteUser([FromBody] UserModel userModel) { var command = new DeleteUserCommand(userModel); CommandDispatcher.Handle(command); return(Ok()); }
public async Task <IActionResult> DeleteById(int id) { var notif = new DeleteUserCommand(id); var result = await _mediatr.Send(notif); return(result != null ? (IActionResult)Ok(new { Message = "success" }) : NotFound(new { Message = "Notification not found" })); }
public async Task <ICommandResult> Delete(Guid id, [FromBody] DeleteUserCommand command) { command.Id = id; var result = await _handler.Handle(command); return(result); }
public async Task ShouldDeleteUserAccountCorrectly() { //Arrange User user = new User("test", "test", "test", "test"); var dateDeleted = new DateTime(); var usersRepository = new Mock <IUsersRepository>(); usersRepository.Setup(x => x.Get(It.IsAny <Guid>())) .Returns(user); usersRepository.Setup(x => x.UpdateAsync(It.IsAny <User>())) .Callback <User>(x => { user = x; dateDeleted = user.ChangedAt; }) .Returns(Task.CompletedTask); var deleteUserHandler = new DeleteUserHandler(usersRepository.Object); var command = new DeleteUserCommand(user.Id); //Act await deleteUserHandler.HandleAsync(command); //Assert usersRepository.Verify(x => x.Get(It.IsAny <Guid>()), Times.Once); usersRepository.Verify(x => x.UpdateAsync(It.IsAny <User>()), Times.Once); Assert.That(user.IsDeleted); Assert.That(user.ChangedAt, Is.EqualTo(dateDeleted)); }
async Task IUserService.DeleteUser(DeleteUserCommand command) { Check.NotNull(command, name: "Command"); await validationService.Validate(command); var user = await userRepository.GetUserById(command.UserId); if (user == null) { return; } var currentPrincipal = await currentUserResolver.ResolveCurrentClaimsPrincipalAsync(); var operation = command.ForceDelete ? Operation.ForceDelete : Operation.Delete; await authorizationService.AuthorizeResource(currentPrincipal, operation, user); try { await userRepository.DeleteUser(user, command.ForceDelete); } catch (RelationshipException ex) { throw new DeleteUserException("There are time entries associated with this user, try force delete.", ex); } await userManager.RemoveUser(user.Id); }
public async Task <IActionResult> Delete(Guid id) { var command = new DeleteUserCommand(id); var result = await Mediator.Send(command); return(await ResponseBase(result)); }
public void ShoulDeleteNotExistUser() { var deleteCommand = new DeleteUserCommand(Guid.NewGuid()); Func <Task> comparison = async() => await _userCommandHandler.Handle(deleteCommand, default); comparison.Should().Throw <UserNotFoundForDeleteException>(); }
protected override void OnPropertyChanged(string propertyName) { base.OnPropertyChanged(propertyName); EditCommand.RaiseCanExecuteChanged(); EditPricesCommand.RaiseCanExecuteChanged(); DeleteUserCommand.RaiseCanExecuteChanged(); }
public async Task <ActionResult> Delete() { var request = new DeleteUserCommand(User.Identity?.Name); await _mediator.Send(request); return(NoContent()); }
public async Task <IActionResult> Delete(int id) { var request = new DeleteUserCommand(); request.Id = id; return(await _delete(request)); }
public UserController(AddUserCommand addUserCommand , EditUserCommand editUserCommand , DeleteUserCommand deleteUserCommand , GetAdminAppUserByIdQuery getAdminAppUserByIdQuery , EditOdsInstanceRegistrationForUserCommand editOdsInstanceRegistrationForUserCommand , EditUserRoleCommand editUserRoleCommand , GetRoleForUserQuery getRoleForUserQuery , IGetOdsInstanceRegistrationsByUserIdQuery getOdsInstanceRegistrationsByUserIdQuery , IGetOdsInstanceRegistrationsQuery getOdsInstanceRegistrationsQuery , ITabDisplayService tabDisplayService , SignInManager <AdminAppUser> signInManager , UserManager <AdminAppUser> userManager ) { _addUserCommand = addUserCommand; _editUserCommand = editUserCommand; _deleteUserCommand = deleteUserCommand; _getAdminAppUserByIdQuery = getAdminAppUserByIdQuery; _editOdsInstanceRegistrationForUserCommand = editOdsInstanceRegistrationForUserCommand; _editUserRoleCommand = editUserRoleCommand; _getRoleForUserQuery = getRoleForUserQuery; _getOdsInstanceRegistrationsByUserIdQuery = getOdsInstanceRegistrationsByUserIdQuery; _getOdsInstanceRegistrationsQuery = getOdsInstanceRegistrationsQuery; _tabDisplayService = tabDisplayService; SignInManager = signInManager; UserManager = userManager; }
public async Task <IActionResult> Delete(int id) { var command = new DeleteUserCommand(id); var result = await _mediatr.Send(command); return(command != null ? (IActionResult)Ok(new { Message = "deleted" }) : NotFound(new { Message = "not found" })); }
public void DeleteUser(DeleteUserCommand command) { var service = NcqrsEnvironment.Get<ICommandService>(); service.Execute(command); }