public async Task<IHttpActionResult> PutUser(long id, UpdateUserCommand command) { if (id != command.Id) { return BadRequest(); } await _mediator.SendAsync(command); return StatusCode(HttpStatusCode.NoContent); }
public UserModule(IMediate mediator) { Get["/"] = _ => "Hi Earth People!"; //404 if not found!!!! Get["/{id:int}"] = parameters => { var userQuery = new UserQuery((int)parameters.id); try { var person = mediator.Request(userQuery); return person; } catch (InvalidOperationException ex) { return HttpStatusCode.NotFound; } }; Put["/{id:int}"] = parameters => { var user = this.Bind<User>(); var updateUserCmd = new UpdateUserCommand(user); try { var id = mediator.Send(updateUserCmd); return Negotiate.WithStatusCode(HttpStatusCode.NoContent); } catch (ValidationException ex) { return Negotiate.WithModel(ex.Errors.Select(x => new{x.PropertyName, x.ErrorMessage})).WithStatusCode(HttpStatusCode.UnprocessableEntity); } catch (InvalidOperationException ex) { return HttpStatusCode.NotFound; } }; Post["/"] = parameters => { var user = this.Bind<User>(); var insertUserCmd = new InsertUserCommand(user); try { var id = mediator.Send(insertUserCmd); return Negotiate.WithStatusCode(HttpStatusCode.Created).WithHeader("Location", Context.Request.Url + "/" + id); } catch (ValidationException ex) { return Negotiate.WithModel(ex.Errors.Select(x => new{x.PropertyName, x.ErrorMessage})).WithStatusCode(HttpStatusCode.UnprocessableEntity); } }; }
public CommandResult Update(Guid id, [FromBody] UpdateUserCommand command) { command.setUserId(id); command.setRequestHost(HttpContext.Request.Host.ToString()); _loggingService.Log(this.GetType(), ELogType.Input, ELogLevel.Info, new { User = this.User.Identity.Name, Path = this.Request.Path, Method = this.Request.Method }); CommandResult result = (CommandResult)_userHandler.Handle(command); _loggingService.Log(this.GetType(), ELogType.Output, ELogLevel.Info, new { User = this.User.Identity.Name, Path = this.Request.Path, Method = this.Request.Method, Code = this.Response.StatusCode }); HttpContext.Response.StatusCode = result.Code; return(result); }
public async Task <Unit> Handle(UpdateUserCommand request, CancellationToken cancellationToken) { var id = new UserId(request.Id); var userToUpdated = await _repository.GetById(id); if (userToUpdated == null) { throw new UserNotFoundForUpdateException(); } var role = await _roleRepository.GetRole(request.Role.Name); if (role == null) { throw new RoleNotFoundForUpdateUserException(); } var email = new Email(request.Email); var existEmail = await _repository.CheckMailExist(id, email); if (existEmail) { throw new EmailAlreadyAffectedException(); } if (userToUpdated.Role.Name.Value == "rfa" && userToUpdated.Role.Name.Value != request.Role.Name) { // cas du changement de role quand l'ancien role est rfa var rfaToRemove = await _rfaRepository.GetRfaByEmail(userToUpdated.Email); if (rfaToRemove != null) { await _rfaRepository.Delete(rfaToRemove); } } userToUpdated.UpdateFirstName(request.FirstName); userToUpdated.UpdateLastName(request.LastName); userToUpdated.UpdateEmail(request.Email); userToUpdated.UpdateRole(role); await _repository.Update(userToUpdated); return(new Unit()); }
public Task UpdateAsync(ApplicationUser user) { var command = new UpdateUserCommand { Id = user.Id, Title = user?.Details.Title, GivenName = user?.Details.GivenName, Surname = user?.Details.Surname, }; if (command.IsIndividual) { _commandDispatcher.Send(command); } return(Task.FromResult(0)); }
public async Task Post_actualizar_usuario_no_autenticado_Unauthorized() { // Arrange var user = await _userManager.FindByNameAsync("Bob"); var userId = user.Id; var data = new UpdateUserCommand(userId, "Bob112", "Bob112", "Bob212", "*****@*****.**", false); var requestContent = SerializerUtils.GetRequestContent(data); var url = Utilities.ComposeUri($"admin/accounts/update"); // Act var response = await Client.PutAsync(url, requestContent); // Assert response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); }
public async void ChangeAdminNameAndLastName() { var update = new UpdateUserCommand() { Name = "NotAdmin", LastName = "NotAdmin" }; HttpResponseMessage response = await _client.PutObjectAsync(UsersUrl + "/1", update); response.EnsureSuccessStatusCode(); UserModel user = await response.DeserializeObject <UserModel>(); Assert.Equal(update.Name, user.Name); Assert.Equal(update.LastName, user.LastName); }
public bool Update(UpdateUserCommand userToUpdate, int id) { using (var connection = new SqlConnection(_connectionString)) { connection.Open(); var sql = @"UPDATE [dbo].[User] SET [AllyCode] = @allyCode ,[Username] = @username WHERE [Id] = @id"; userToUpdate.Id = id; return(connection.Execute(sql, userToUpdate) == 1); } }
public void TestValidationUpdate() { var userService = new UserService(new UserRepository()); var command = new UpdateUserCommand() { UserId = 4, Name = "teste", Email = "*****@*****.**", Password = "******" }; var result = userService.ValidaUpdate(command); Assert.IsTrue(result.Count() == 0); }
public async Task <UserDto> HandleAsync(UpdateUserCommand command) { var user = await _userRepository.GetById(command.Id); user.FirstName = command.FirstName; user.LastName = command.LastName; var result = await _userRepository.SaveAsync(); return(new UserDto { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName }); }
public async Task <IActionResult> UpdateAsync(string id, [FromBody] UpdateUserCommand command) { if (command.Role == Roles.Admin) { return(BadRequest(new[] { "Nieprawidłowa rola." })); } var user = await _userService.UpdateAsync(id, command); if (user == null) { return(NotFound()); } return(Ok()); }
void AndGivenCommandPrepared() { _command = new UpdateUserCommand() { UserId = _updatedUserId, RequestedUser = new LoggedUserModel(_requestedUserId, _requestedUserEmail, _requestedUserRole), Email = "Updated email", FirstName = "Updated first name", LastName = "Updated last name", Street = "Updated street", City = "Updated city", Country = "Updated country", ZipCode = "Updated zip code", BtcWalletAddress = "Updated btc wallet address", Role = UserRolesHelper.Admin }; }
public async Task <IActionResult> Put([FromBody] UpdateUserCommand command) { try { await _mediator.Send(command); return(Ok()); } catch (KeyNotFoundException ex) { return(NotFound()); } catch (ArgumentException argumentException) { return(BadRequest(argumentException.Message)); } }
public void UpdateUser(Guid aggregateRootId, string displayName, string email, string contactPhone, string address_Country, string address_State, string address_City, string address_Street, string address_Zip) { UpdateUserCommand command = new UpdateUserCommand { AggregateRootId = aggregateRootId, DisplayName = displayName, Email = email, ContactPhone = contactPhone, Address_Country = address_Country, Address_State = address_State, Address_City = address_City, Address_Street = address_Street, Address_Zip = address_Zip }; CommitCommand(command); }
public IActionResult UpdateUser(UpdateUserCommand updatedUserCommand, int id) { var repo = new UserRepository(); var updatedUser = new User { Username = updatedUserCommand.Username, Email = updatedUserCommand.Email, City = updatedUserCommand.City, State = updatedUserCommand.State, Bio = updatedUserCommand.Bio }; var yourUpdatedUser = repo.Update(updatedUser, id); return(Ok(yourUpdatedUser)); }
public override async Task <Empty> UpdateUser(UpdateUserRequest request, ServerCallContext context) { var command = new UpdateUserCommand { Id = request.Id, Password = request.Password, Name = request.Name, DisplayName = request.DisplayName, IsEnabled = request.IsEnabled, RoleIds = request.RoleIds .Select(x => (Guid)x) .ToList(), }; await _authorizationApp.UpdateUserAsync(command); return(new Empty()); }
public async void UpdateOnlyNameTest() { var command = new UpdateUserCommand() { Id = 1, Name = "name" }; var handler = new UpdateUserCommandHandler(Context); await handler.Handle(command, CancellationToken.None); User user = Users.Single(u => u.Id == 1); Assert.Equal(command.Name, user.Name); Assert.NotNull(user.LastName); Assert.NotNull(user.Mail); }
public IActionResult Put([FromBody] UpdateUserCommand command) { try { var result = _userService.UpdateUser(command); if (result.Success) { return(Ok(result)); } return(BadRequest(result)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <IActionResult> UpdateUser([FromBody] UpdateUserCommand command) { //TODO Validation Messages if (!ModelState.IsValid) { return(BadRequest("Invalid information submitted")); } var result = await Mediator.Send(command.AttachUserId(UserId)); if (result == null) { return(BadRequest()); } return(Ok(result)); }
public async Task <IActionResult> Put([FromBody] UpdateUserCommand command) { if (!ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } User user = await this._mediator.Send(command); if (user is null) { return(this.BadRequest($"User doesn't exist in the system. {JsonConvert.SerializeObject(command)}")); } // return this.NoContent(); return(this.Accepted(user)); }
public IActionResult updateUserAsync([FromBody] UpdateUserModel model) { try { int id = 17; var userMap = _mapper.Map <UpdateUserDto>(model); var command = new UpdateUserCommand(id, userMap); _commandDispatcher.DispatchCommand(command); return(new OkObjectResult("ОК")); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <bool> Handle(UpdateUserCommand request, CancellationToken cancellationToken) { var user = await _userRepository.GetByIdAsync(request.Id); if (user == null) { await _bus.RaiseEvent( new DomainNotification(request.Id.ToString(), "未找到对应的数据", StatusCodes.Status404NotFound), cancellationToken); return(false); } if (user.UserType is UserType.AdminUser or UserType.TenantAdminUser) { await _bus.RaiseEvent( new DomainNotification(request.Id.ToString(), "当前用户禁止修改", 568), cancellationToken); return(false); } user.ContactNumber = request.ContactNumber; user.State = request.State; user.UserName = request.UserName; user.UserType = request.UserType; if (user.UserPassword != request.UserPassword) { user.UserPassword = request.UserPassword; } await _userRepository.UpdateAsync(user); if (await Commit()) { var key = GirvsEntityCacheDefaults <User> .ByIdCacheKey.Create(user.Id.ToString()); await _bus.RaiseEvent(new RemoveCacheEvent(key), cancellationToken); await _bus.RaiseEvent(new RemoveCacheListEvent(GirvsEntityCacheDefaults <User> .ListCacheKey.Create()), cancellationToken); } return(true); }
public ActionResult EditUserPost(UpdateUserCommand command) { if (!ModelState.IsValid) { return(View(command)); } try { commandPipeline.HandleCommand(command); } catch (DomainException ex) { ModelState.AddModelError(string.Empty, ex); return(View(command)); } return(RedirectToAction("Index")); }
public async Task <ResponseApi> Handle(UpdateUserCommand request, CancellationToken cancellationToken) { try { User user = _mapper.Map <User>(await _userRepository.Get(request.Id)); request.Validate(); if (request.Invalid) { return(new ResponseApi(false, "Ops, something is wrong...", request.Notifications)); } user.UpdateFields(_mapper.Map <User>(request)); await _userRepository.Update(user); var response = new UserViewModel { Id = user.Id, Name = user.Name, LastName = user.LastName, FiscalNr = user.FiscalNr, Email = user.Email, BirthDay = user.BirthDay, Gender = user.Gender, Phone = user.Phone, Street = user.Street, StateProvince = user.StateProvince, City = user.City, Country = user.Country, CityOfBirth = user.CityOfBirth, ExperienceTime = user.ExperienceTime, Summary = user.Summary, Active = user.Active, Excluded = user.Excluded, CreationDate = user.CreationDate, LastUpdate = user.LastUpdate }; return(new ResponseApi(true, "User updated sucessfuly", response)); } catch (Exception e) { return(new ResponseApi(false, "Error...", e)); } }
public async Task WhenValidValuesPosted_ThenUserShouldBeUpdated() { using (var testServer = await CreateWithUserAsync()) { var client = testServer.CreateClient(); var city = await GetRandomCityAsync(client); var updateCommand = new UpdateUserCommand( Guid.NewGuid(), "BlackSchool", "5324258289", city.Id, city.Districts.Random().Id); var response = await client.PutAsync(ApiPath, updateCommand.ToJsonContent()); response.EnsureSuccessStatusCode(); } }
public async Task <Response <bool> > Handle(UpdateUserCommand request, CancellationToken cancellationToken) { var user = await userRepo.GetUserByIdAsync(request.Userid); if (user != null) { user.UserName = request.Username ?? request.Username; user.FirstName = request.Firstname ?? request.Firstname; user.FirstName = request.Lastname ?? request.Lastname; await userRepo.UpdateAsync(user); return(Response.Ok()); } else { return(Response.Fail <bool>("چنین کاربری یافت نشد", StatusCodeEnum.NOTFUOUND, false)); } }
public async Task UserUpdate_ExceptedBehaviour() { //Arrange var authClient = await GetAuthorizedClientAsync(); var updateUserCommand = new UpdateUserCommand() { Role = Roles.User, Name = "Andrzej", Lastname = "Duda" }; //Act var result = await authClient.PutAsJsonAsync($"/user/{WebAppFactory<Startup>.UserForUpdate.Id}", updateUserCommand); //Assert Assert.Equal(HttpStatusCode.OK, result.StatusCode); }
public async Task <IActionResult> Put(long id, [FromBody] UpdateUserCommand command) { if (await authService.CheckIfBanned(User).ConfigureAwait(false)) { return(Forbid()); } if (IsUserAStranger(id)) { return(Unauthorized()); } command.Id = id; await mediator.Send(command).ConfigureAwait(false); return(NoContent()); }
public ICommandResult Handle(UpdateUserCommand command) { //Fail Fast Validation command.Validate(); if (command.Invalid) { return(new GenericCommandResult(false, Messages.Ex_ExceptionGeneric, command.Notifications)); } var user = _repository.GetById(command.Id); user.UpdateUser(command.Email, command.Name, command.Picture, command.NickName, command.Avatar, command.Country); _repository.Update(user); return(new GenericCommandResult(true, Messages.Act_Update, user)); }
public async Task <ActionResult> UpdateLibraryUser(int libraryId, int id, UpdateRequest model, CancellationToken cancellationToken) { if (!Account.IsSuperAdmin && !_userHelper.IsLibraryAdmin(libraryId) && id != Account.Id) { return(Unauthorized(new { message = "Unauthorized" })); } var command = new UpdateUserCommand { Email = model.Email, LibraryId = libraryId, Name = model.Name, Role = model.Role, }; await _commandProcessor.SendAsync(command, cancellationToken : cancellationToken); return(Ok(model)); }
public async Task GivenValidRequest_ShouldUpdateUser() { var client = _factory.GetAnonymousClient(); var command = new UpdateUserCommand { UserId = Utilities.KnownUserID1, FirstName = "User 1", LastName = "Test", EmailAddress = "*****@*****.**", DOB = DateTime.Today.AddYears(-25) }; HttpContent content = Utilities.GetRequestContent(command); var response = await client.PutAsync($"/api/users/{Utilities.KnownUserID1}", content); response.EnsureSuccessStatusCode(); }
public async Task <IActionResult> Put(int id, [FromBody] UserCreateDto userDto) { UserReadDto result; try { var query = new UpdateUserCommand(id, userDto); result = await _mediator.Send(query); } catch (Exception ex) { _logger.LogWarning($"User with id {id} not updated!"); return(StatusCode(StatusCodes.Status400BadRequest, ex.Message)); } _logger.LogInformation($"User with id {id} updated!"); return(StatusCode(StatusCodes.Status200OK, result)); }
public User Update(UpdateUserCommand commandUser) { var user = _repository.GetOne(commandUser.Id); user.IdPerson = commandUser.IdPerson; user.Validate(); if (!string.IsNullOrEmpty(commandUser.Password)) _repository.Update(user, commandUser.Password); else _repository.Update(user); if (Commit()) return user; return null; }
public Task<HttpResponseMessage> Put([FromBody]dynamic body) { var listAddress = _serviceAddress.AddToPerson(body.person.address); var listPhone = _servicePhone.AddToPerson(body.person.phone); var commandPerson = new UpdatePersonCommand( id: Guid.Parse((string)body.person.id), name: (string)body.person.name, birthDate: (DateTime)body.person.birthDate, genre: (EGenre)body.person.genre, address: listAddress, phone: listPhone, phototgraph: (string)body.person.photograph ); var person = _servicePerson.Update(commandPerson); _serviceAddress.CheckAddressRemoved(listAddress, person.Id); _servicePhone.CheckPhoneRemoved(listPhone, person.Id); var commandUser = new UpdateUserCommand( id: (string)body.id, password: (string)body.password, userName: (string)body.email, idPerson: person.Id ); var user = _service.Update(commandUser); return CreateResponse(HttpStatusCode.Created, user); }
public async Task<HttpResponseMessage> PutAsync(UpdateUserCommand command) { await _userService.UpdateUserAsync(command); return Request.CreateResponse(HttpStatusCode.OK); }