public async Task <ActionResult> Edit(ProfileViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var authorDTO = _mapper.Map <ProfileViewModel, AuthorDTO>(model); if (model.UploadedData != null) { byte[] imageData = null; using (var binaryReader = new BinaryReader(model.UploadedData.OpenReadStream())) { imageData = binaryReader.ReadBytes((int)model.UploadedData.Length); } authorDTO.Avatar = imageData; } var authorCommand = new UpdateAuthorCommand { Model = authorDTO }; await _mediator.Send(authorCommand); return(RedirectToAction("Index", "Profile", new { id = model.Id })); }
public ICommandResult Handle(UpdateAuthorCommand command) { //FAIL FAST VALIDATION command.Validate(); if (command.Invalid) { return(new GenericCommandResult(false, "An error occurred while updating the requested record", command.Notifications)); } //Retrieve Author from Database var author = _authorRepository.GetById(command.Id).Result; var mapAuthor = _mapper.Map <UpdateAuthorCommand, Author>(command); //Update the data in the database author.UpdateAuthor(mapAuthor.Id, mapAuthor.Name, mapAuthor.DateOfBirthday, mapAuthor.Document); _authorRepository.Update(author); //Send message to queue _bus.Enqueue(command, UpdateAuthorCommand.QueueName); //Cache var key = key_author.Replace("{id}", author.Id.ToString()); _cache.Save(author, key); return(new GenericCommandResult(true, $"The author {author.Name} has been updated successfully", author)); }
public async Task UpdateAuthorCommandHandler_WithExperiences_UpdatesAuthor() { await AddAuthor(); var image = await AddImage(); var experiences = new List <ExperienceDto>(); var experienceDto = new ExperienceDto() { Color = "#000000", Name = "Testfile", ImageId = image.Id }; experiences.Add(experienceDto); var message = new UpdateAuthorCommand() { FirstName = "Test", LastName = "Test", About = "Test", Experiences = experiences }; var handler = new UpdateAuthorCommandHandler(TestContext.CreateHandlerContext <AuthorViewModel>(RequestDbContext, CreateMapper()), _authorService); var result = await handler.Handle(message, CancellationToken.None); Assert.Equal("Testfile", result.Experiences.First().Name = experienceDto.Name); }
public async Task <IActionResult> Edit(UpdateAuthorCommand command) { try { var author = _author.GetAuthor(command.AuthorId); var authResult = await _authService.AuthorizeAsync(User, author, "CanManageAuthor"); // var authResult1 = await _authService.AuthorizeAsync(User, person, "CanEditPerson"); var authResult2 = await _authService.AuthorizeAsync(User, author, "ContentEditor"); if (!authResult.Succeeded || !authResult2.Succeeded) { return(new ForbidResult()); } if (ModelState.IsValid) { _author.UpdateAuthor(command); return(RedirectToAction(nameof(View), new { id = command.AuthorId })); } } catch (Exception) { // Add a model-level error by using an empty string key ModelState.AddModelError( string.Empty, "An error occured updating author" ); _log.LogError("An error occured updating author"); } //If we got to here, something went wrong return(View(command)); }
public async Task Handler_GivenValidData_ShouldUpdateAuthor() { // Arrange var author = new AuthorDTO { Id = 2, UserId = "QWERTY1234567890_new", FirstName = "FirstName_new", LastName = "LastName_new", BirthDate = new DateTime(2000, 01, 01), Email = "*****@*****.**", }; var command = new UpdateAuthorCommand { Model = author }; // Act var handler = new UpdateAuthorCommand.UpdateAuthorCommandHandler(Context); await handler.Handle(command, CancellationToken.None); var entity = Context.Authors.Find(author.Id); // Assert entity.ShouldNotBeNull(); entity.FirstName.ShouldBe(command.Model.FirstName); entity.LastName.ShouldBe(command.Model.LastName); entity.BirthDate.ShouldBe(command.Model.BirthDate); entity.UserId.ShouldNotBe(command.Model.UserId); }
public async Task UpdateAuthor( [FromRoute] Guid authorId, [FromBody] UpdateAuthorCommand command) { command.AuthorId = authorId; await Mediator.Send(command); }
public UpdateBooksCommand(Guid id, string title, DateTime releaseDate, string iSBN, string category, UpdateAuthorCommand author) { Id = id; Title = title; ReleaseDate = releaseDate; ISBN = iSBN; Category = category; Author = author; }
public void Id_Cant_Be_Empty(Guid id, bool result) { var command = new UpdateAuthorCommand { Id = id, Name = "Uncle Bob" }; var validationResult = _updateAuthorCommandValidator.Validate(command); validationResult.IsValid.Should().Be(result); }
public async Task <ActionResult> Update([FromRoute] int id, [FromBody] UpdateAuthorCommand command) { if (id != command.AuthorId) { return(BadRequest()); } return(Ok(await Mediator.Send(command))); }
public async Task <IActionResult> Update([FromBody] UpdateAuthorCommand updateAuthorCommand) { var result = await _mediator.Send(updateAuthorCommand); if (!result.Success) { return(BadRequest(result.Message)); } return(Ok(result.Message)); }
public async Task ReturnsNotFoundGivenNonexistingAuthor() { var updatedAuthor = new UpdateAuthorCommand() { Id = 2222, // invalid author Name = "Doesn't Matter", }; await _client.PutAndEnsureNotFound(Routes.Authors.Update, new StringContent(JsonConvert.SerializeObject(updatedAuthor), Encoding.UTF8, "application/json")); }
public IActionResult Put(UpdateAuthorCommand command) { var result = _updateAuthorCommandHandler.Handle(command); if (result.Success) { return(Ok(command)); } return(BadRequest(result.Errors)); }
public async Task <IActionResult> Put([FromRoute] int id, [FromBody] UpdateAuthorCommand command) { var isSuccess = await this.Mediator.Send(command); var result = new ApiResult <bool>() { Message = "Update success", Data = isSuccess }; return(Ok(result)); }
public async Task <IActionResult> Put(int id, [FromBody] UpdateAuthorCommand request) { var data = await this._mediator.Send(request); var result = new ApiResult <bool>() { Message = ApiMessage.UpdateOk, Data = data }; return(Ok(result)); }
public async Task <IActionResult> Update(int id, UpdateAuthorCommand command) { // users can update their own author and admins can update any author if (id != Author.Id && Author.Role != Role.Admin) { return(Unauthorized(new { message = "Unauthorized" })); } await _mediator.Send(command); return(NoContent()); }
public void Should_Not_Update_When_Command_Is_Invalid() { //Arrange var author = new UpdateAuthorCommand { Name = "Robert Cecil Martin" }; //Act _updateAuthorCommandHandler.Handle(author); //Assert _authorRepository.Verify(r => r.Update(It.IsAny <Domain.Entities.Author>()), Times.Never); }
public void Must_Not_Update_Invalid_Author() { //Arrange var author = new UpdateAuthorCommand { Id = Guid.Empty, Name = "Eric Evans" }; //Act var httpResponseMessage = _httpClient.PutAsJsonAsync(url, author).Result; //Assert httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.BadRequest); }
public void Name_Cant_Be_Null_Or_Empty(string name, bool isValid) { //Arrange var author = new UpdateAuthorCommand { Id = Guid.NewGuid(), Name = name }; //Act var validationResult = _updateAuthorCommandValidator.Validate(author); //Assert validationResult.IsValid.Should().Be(isValid); }
public void TestCreateAuthorCommand_NotFound() { var mediator = new Mock <IMediator>(); var authorRepo = new Mock <IAuthorRepo>(); authorRepo.Setup(x => x.GetById(It.IsAny <Guid>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult((Author)null)); var updateCommand = new UpdateAuthorCommand() { Id = Guid.NewGuid(), FirstName = "Firstname", LastName = "Lastname" }; var handler = new UpdateAuthorCommand.Handler(authorRepo.Object, mediator.Object); Assert.ThrowsAsync <NotFoundException>(() => handler.Handle(updateCommand, new CancellationToken())); }
public void Name_Cant_Be_Repeated(string name, bool exists) { //Arrange var UpdateAuthorCommand = new UpdateAuthorCommand { Id = Guid.NewGuid(), Name = name }; _authorRepositoryMock.Setup(a => a.ExistsAsync(name)).Returns(Task.FromResult(exists)); //Act var validationResults = _updateAuthorCommandValidator.Validate(UpdateAuthorCommand); //Assert validationResults.IsValid.Should().Be(!exists); }
public async Task <IActionResult> Edit(AuthorViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var authorDTO = _mapper.Map <AuthorViewModel, AuthorDTO>(model); var authorCommand = new UpdateAuthorCommand { Model = authorDTO }; await _mediator.Send(authorCommand); return(RedirectToAction("Index")); }
/// <summary> /// Update person using id /// </summary> /// <param name="cmd"></param> public void UpdateAuthor(UpdateAuthorCommand cmd) { var person = _dbContext.Author.Find(cmd.AuthorId); if (person == null) { throw new Exception("Unable to find the person"); } if (person.IsDeleted) { throw new Exception("Unable to update a deleted person"); } cmd.UpdateAuthor(person); _dbContext.SaveChanges(); }
public async Task GivenLongRunningUpdateRequest_WhenTokenSourceCallsForCancellation_RequestIsTerminated() { // Arrange, generate a token source that times out instantly var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(0)); var authorPreUpdate = SeedData.Authors().FirstOrDefault(p => p.Id == 2); var updatedAuthor = new UpdateAuthorCommand() { Id = 2, Name = "James Eastham", }; // Act var request = _client.PutAsync(Routes.Authors.Update, new StringContent(JsonConvert.SerializeObject(updatedAuthor), Encoding.UTF8, "application/json"), tokenSource.Token); // Assert await Assert.ThrowsAsync <OperationCanceledException>(async() => await request); }
public async Task <ActionResult> Update(int id, UpdateAuthorCommand command) { if (id != command.Id) { return(BadRequest()); } try { await Mediator.Send(command); } catch (NotFoundException ex) { return(NotFound(ex.Message)); } return(NoContent()); }
public async Task UpdateAuthorCommandHandler_WithImage_ReturnsAuthor() { await AddAuthor(); var image = await AddImage(); var handler = new UpdateAuthorCommandHandler(TestContext.CreateHandlerContext <AuthorViewModel>(RequestDbContext, CreateMapper()), _authorService); var message = new UpdateAuthorCommand() { FirstName = "Tom", LastName = "Bina", About = "About me", ImageId = image.Id }; var result = await handler.Handle(message, CancellationToken.None); Assert.NotNull(result.Image); }
public void Must_Update_Valid_Author() { //Arrange const string authorName = "Eric Evans"; var addedAuthor = new Author("Martin Fowler"); base.SeedData(addedAuthor); var author = new UpdateAuthorCommand { Id = addedAuthor.Id, Name = authorName }; //Act var httpResponseMessage = _httpClient.PutAsJsonAsync(url, author).Result; //Assert httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK); var actual = (_authorRepository.GetAllAsync().Result).Single(a => a.Id == author.Id); actual.Name.Should().Be(authorName); }
public IActionResult UpdateAuthor(Guid id, [FromBody] UpdateAuthorDTO updateAuthorDTO) { if (ModelState.IsValid) { UpdateAuthorCommand updateAuthorCommand = new UpdateAuthorCommand(updateAuthorDTO.Firstname, updateAuthorDTO.Lastname, id); try { var result = _messages.Dispatch(updateAuthorCommand); return(Ok(result)); } catch (DomainException ex) { _logger.LogError(ex.Message); return(Error(ex.Message)); } catch (Exception ex) { _logger.LogCritical(ex.Message); return(StatusCode(500)); } } return(BadRequest()); }
public async Task Handle_GivenInvalidAuthorData_ThrowsException() { // Arrange var author = new AuthorDTO { Id = 99, UserId = "QWERTY1234567890_new", FirstName = "FirstName_new", LastName = "LastName_new", BirthDate = new DateTime(2000, 01, 01), Email = "*****@*****.**", }; var command = new UpdateAuthorCommand { Model = author }; // Act var handler = new UpdateAuthorCommand.UpdateAuthorCommandHandler(Context); // Assert await Should.ThrowAsync <NotFoundException>(() => handler.Handle(command, CancellationToken.None)); }
public async Task UpdateAnExistingAuthor() { var updatedAuthor = new UpdateAuthorCommand() { Id = 2, Name = "James Eastham", }; var authorPreUpdate = SeedData.Authors().FirstOrDefault(p => p.Id == 2); var response = await _client.PutAsync($"/authors", new StringContent(JsonConvert.SerializeObject(updatedAuthor), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); var stringResponse = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject <UpdatedAuthorResult>(stringResponse); Assert.NotNull(result); Assert.Equal(result.Id, updatedAuthor.Id.ToString()); Assert.NotEqual(result.Name, authorPreUpdate.Name); Assert.Equal("James Eastham", result.Name); Assert.Equal(result.PluralsightUrl, authorPreUpdate.PluralsightUrl); Assert.Equal(result.TwitterAlias, authorPreUpdate.TwitterAlias); }
public async Task <ActionResult> Update(UpdateAuthorCommand command) => Ok(await _mediator.Send(command));