コード例 #1
0
        public async Task UpdateBook_LibrarianUser_OkStatusCode()
        {
            // Arrange
            var claimsProvider = TestClaimsProvider.WithLibrarianClaims();
            var client         = Factory.CreateClientWithTestAuth(claimsProvider);
            var book           = await CreateBook(client);

            var newTitle = "NewTitle";

            // Act
            var content = new UpdateBookCommand()
            {
                BookId = book.Id,
                Title  = newTitle,
                Author = new AuthorDTO()
                {
                    FirstName = book.Author.FirstName,
                    LastName  = book.Author.LastName
                },
                Description   = book.Description,
                YearPublished = book.YearPublished
            };
            var response = await client.PutAsJsonAsync("api/books/", content);

            var responseBook = await response.Content.ReadFromJsonAsync <BookDTO>();

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.OK);
            responseBook.Title.Should().Be(newTitle);
        }
コード例 #2
0
 public Book Update(UpdateBookCommand command)
 {
     return(_repository.Update(new Book(command.Title, command.Synopsis, command.AuthorId)
     {
         Id = command.Id
     }));
 }
コード例 #3
0
        public async Task <Book> UpdateAsync(UpdateBookCommand cmd)
        {
            if (!cmd.IsValid)
            {
                throw new InvalidCommandException(nameof(UpdateBookCommand), cmd);
            }

            var book = await _unitOfWork.BookRepository.FindAsync(cmd.Id) ?? throw new NotFoundException(nameof(Book), cmd.Id);

            if (!_auth.CanWrite(book))
            {
                throw new NotAllowedException(_auth.Login, nameof(Book), cmd.Id);
            }

            book.Title = cmd.Title;
            book.Slug  = await GetUniqueSlugAsync(cmd.Slug, book.Id);

            book.Description = cmd.Description;
            book.ReadAccess  = cmd.ReadAccess;
            book.WriteAccess = cmd.WriteAccess;
            book.UpdatedAt   = DateTime.Now;

            _unitOfWork.BookRepository.Update(book);
            await _unitOfWork.SaveAsync();

            return(book);
        }
コード例 #4
0
        public async Task Handle_ValidCommand_BookUpdated()
        {
            var bookId   = 1;
            var newTitle = "NewTitle";
            var command  = new UpdateBookCommand()
            {
                BookId        = 1,
                Title         = newTitle,
                Description   = "Description",
                YearPublished = 2020,
                Author        = new AuthorDTO()
                {
                    FirstName = "FirstName",
                    LastName  = "LastName"
                }
            };
            var bookToUpdate = new Book("Title", new Author("FirstName", "LastName"), 2020, "Description");

            _bookRepositoryMock.Setup(x => x.GetAsync(bookId))
            .ReturnsAsync(bookToUpdate);

            await _sut.Handle(command, CancellationToken.None);

            _bookRepositoryMock.Verify(x => x.Update(bookToUpdate), Times.Once);
            bookToUpdate.Title.Should().Be(newTitle);
        }
コード例 #5
0
        public void HandleCommand(UpdateBookCommand command)
        {
            Book book = DomainRepository.Get <Book>(command.AggregateRootId);

            book.UpdateBook(command.Title, command.Author, command.Description, command.ISBN, command.Pages, command.Inventory);
            DomainRepository.Save(book);
            DomainRepository.Commit();
        }
コード例 #6
0
        public async Task <ActionResult> PartiallyUpdateBookForAuthor(long authorId, long bookId,
                                                                      JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            var author = await _messages.Dispatch(new GetAuthorQuery(authorId));

            if (author is null)
            {
                return(NotFound($"No author with id {authorId} was found."));
            }

            var bookForAuthorFromRepo = await _messages.Dispatch(new GetBookQuery(authorId, bookId));

            if (bookForAuthorFromRepo == null)
            {
                var bookDto = new BookForUpdateDto();
                patchDocument.ApplyTo(bookDto, ModelState);

                if (!TryValidateModel(bookDto))
                {
                    return(ValidationProblem(ModelState));
                }

                var addCommand = new CreateBookCommand(bookDto.Title, bookDto.Description, authorId);

                Result <Book> addResult = await _messages.Dispatch(addCommand);

                if (addResult.IsFailure)
                {
                    return(BadRequest(addResult.Error));
                }

                var bookToReturn = _mapper.Map <BookDto>(addResult.Value);
                return(CreatedAtRoute(nameof(GetBookForAuthor),
                                      new { authorId, bookId = bookToReturn.Id }, bookToReturn));
            }

            var bookToPatch = _mapper.Map <BookForUpdateDto>(bookForAuthorFromRepo);

            // add validation
            patchDocument.ApplyTo(bookToPatch, ModelState);

            if (!TryValidateModel(bookToPatch))
            {
                return(ValidationProblem(ModelState));
            }

            var updateCommand = new UpdateBookCommand(bookId, bookToPatch.Title, bookToPatch.Description, authorId);

            Result <Book> updateResult = await _messages.Dispatch(updateCommand);

            if (updateResult.IsFailure)
            {
                return(BadRequest(updateResult.Error));
            }

            return(NoContent());
        }
コード例 #7
0
 public bool Handle(UpdateBookCommand message)
 {
     using (IDomainRepository domainRepository = this.GetDomainRepository())
     {
         Book book = domainRepository.Get <Book>(message.AggregateRootId);
         book.UpdateBasicInformation(message.Title, message.Author, message.Description, message.ISBN, message.Pages, message.Inventory);
         domainRepository.Save <Book>(book);
         domainRepository.Commit();
         return(domainRepository.Committed);
     }
 }
コード例 #8
0
        public IActionResult Put(UpdateBookCommand command)
        {
            var result = _updateBookCommandHandler.Handle(command);

            if (result.Success)
            {
                return(Ok(command));
            }

            return(BadRequest(result.Errors));
        }
コード例 #9
0
        public void Should_Update_A_Book()
        {
            UpdateBookCommand command = new UpdateBookCommand()
            {
                BookId   = bookRepository.books[0].Id,
                UserId   = userRepository.users[0].Id,
                BookDate = DateTime.Parse("17/06/2019 16:00:00")
            };

            Assert.IsNotNull(_handler.Handler(command));
        }
コード例 #10
0
        private bool Handle(UpdateBookCommand command)
        {
            var provider = DependencyInjectorStub.Get((s, c) =>
            {
                BootStrapper.RegisterServices(s, c);
                s.AddScoped(x => MockRepository.GetContext());
            });

            var handler = provider.GetRequiredService <IRequestHandler <UpdateBookCommand, bool> >();

            return(handler.Handle(command, CancellationToken.None).GetAwaiter().GetResult());
        }
コード例 #11
0
        public static Domain.Entities.Book CommandToEntity(UpdateBookCommand command)
        {
            var config = new MapperConfiguration(configure =>
            {
                configure.CreateMap <UpdateBookCommand, Domain.Entities.Book>();
                configure.CreateMap <PublicationCommand, Publication>();
            });

            var mapper = config.CreateMapper();

            return(mapper.Map <Domain.Entities.Book>(command));
        }
コード例 #12
0
        public Task <bool> Handle(UpdateBookCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.FromResult(false));
            }

            var book = new Book(message.Id, message.Name, message.Author);

            _bookRepository.Update(book);

            return(Task.FromResult(Commit()));
        }
コード例 #13
0
        public Guid UpdateBook(Guid id, [FromBody] DTOs.BookDTO dto)
        {
            var command = new UpdateBookCommand
            {
                BookId      = dto.BookId,
                BookName    = dto.BookName,
                ISBN        = dto.ISBN,
                DateIssued  = dto.IssueDate,
                Description = dto.Description
            };

            _commandPublisher.Publish(command);
            return(command.CommandUniqueId);
        }
コード例 #14
0
        public void UpdateBook(long id, string title, string author, string description, string isbn, int pages, int inventory)
        {
            UpdateBookCommand command = new UpdateBookCommand
            {
                Title           = title,
                Author          = author,
                Description     = description,
                AggregateRootId = id,
                ISBN            = isbn,
                Pages           = pages,
                Inventory       = inventory
            };

            this.CommitCommand(command);
        }
コード例 #15
0
        public ActionResult Put(int id, [FromBody] BookReadModel model)
        {
            if (id != model.Id)
            {
                return(BadRequest());
            }

            var command = new UpdateBookCommand {
                Id = model.Id
            };

            _commandAdapter.Dispatch(command);

            return(NoContent());
        }
        public void Should_Not_Update_When_Command_Is_Invalid()
        {
            //Arrange
            var updateBookCommand = new UpdateBookCommand
            {
                Title = "Clean Code", Publication = _publication, AuthorId = Guid.NewGuid(), PublisherId = Guid.NewGuid()
            };

            //Act
            _updateBookCommandHandler.Handle(updateBookCommand);

            //Assert
            _bookRepository.Verify(r => r.Add(It.IsAny <Domain.Entities.Book>()), Times.Never);
            _eventPublisher.Verify(p => p.Publish(It.IsAny <BookEvent>()), Times.Never);
        }
コード例 #17
0
        public ICommandResult Handler(UpdateBookCommand command)
        {
            Book book = _bookRepository.GetById(command.BookId);

            if (!(book.User.Id == command.UserId))
            {
                AddNotification("User", "O usuário não tem permissão para alterar essa reserva.");
            }
            book.Update(command.BookDate);
            AddNotifications(book.Notifications);
            if (!IsValid())
            {
                return(null);
            }
            _bookRepository.Update(book);
            return(new StandardBookCommandResult(book.Id, DateTime.Now));
        }
コード例 #18
0
        public BookSearchVM(IBookManager _bookManager, IValidation _validation)
        {
            bookManager = _bookManager;
            validation  = _validation;

            SearchBooksCommand     = new SearchBookCommand(this);
            DeleteBookCommand      = new DeleteBookCommand(this);
            OpenUpdateCommand      = new OpenBookUpdateWindowCommand(this);
            UpdateBookCommand      = new UpdateBookCommand(this);
            EnableCheckOutCommand  = new EnableBookCheckOutCommand(this);
            EnableCheckInCommand   = new EnableBookCheckInCommand(this);
            CheckOutCommand        = new BookCheckOutCommand(this);
            CheckInCommand         = new BookCheckInCommand(this);
            ViewBookHistoryCommand = new ViewBookHistoryCommand(this);

            Books       = new ObservableCollection <Book>();
            BookHistory = new List <BookTransaction>();
        }
コード例 #19
0
 public BooksViewModel()
 {
     updateBookCommand = new UpdateBookCommand(this);
     addBookCommand    = new AddBookCommand(this);
     deleteBookCommand = new DeleteBookCommand(this);
     booksList         = new ObservableCollection <BookModel> {
     };
     typeBookList      = new ObservableCollection <string> {
     };
     authorsList       = new ObservableCollection <string> {
     };
     titleList         = new ObservableCollection <string> {
     };
     readAuthors();
     readTitles();
     readTypes();
     DataGrid_Loaded();
 }
コード例 #20
0
        public async Task <IActionResult> UpdateBookAsync(int bookId, [FromBody] UpdateBookCommand updateBookCommand)
        {
            if (bookId != updateBookCommand.BookId)
            {
                return(BadRequest("Ids do not match."));
            }

            var result = await mediator.Send(updateBookCommand);

            if (result)
            {
                return(NoContent());
            }
            else
            {
                return(NotFound());
            }
        }
コード例 #21
0
        public async Task <ActionResult> Update(int id, UpdateBookCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            try
            {
                await Mediator.Send(command);
            }
            catch (NotFoundException ex)
            {
                return(NotFound(ex.Message));
            }

            return(NoContent());
        }
コード例 #22
0
        public async Task OnGet(int bookId)
        {
            BookViewModel BookViewModel = await _mediatR.Send(new GetBookByIdQuery()
            {
                BookId = bookId
            });

            UpdateBookCommand = new UpdateBookCommand()
            {
                BookId        = BookViewModel.BookId,
                Title         = BookViewModel.Title,
                Author        = BookViewModel.Author,
                BookFormat    = BookViewModel.BookFormat,
                PublishedDate = BookViewModel.PublishedDate
            };

            PopulationOptions();
        }
コード例 #23
0
        public void Publisher_Cant_Be_Empty()
        {
            //Arrange
            var updateBookCommand = new UpdateBookCommand
            {
                Id          = Guid.NewGuid(),
                Title       = "Clean Code",
                Publication = _publication,
                AuthorId    = Guid.NewGuid(),
                PublisherId = Guid.Empty
            };

            //Act
            var validationResult = _updateBookCommandValidator.Validate(updateBookCommand);

            //Assert
            validationResult.IsValid.Should().BeFalse();
        }
コード例 #24
0
        public void Title_Cant_Be_Empty(string title, bool result)
        {
            //Arrange
            var updateBookCommand = new UpdateBookCommand
            {
                Id          = Guid.NewGuid(),
                Title       = title,
                Publication = _publication,
                AuthorId    = Guid.NewGuid(),
                PublisherId = Guid.NewGuid()
            };

            //Act
            var validationResult = _updateBookCommandValidator.Validate(updateBookCommand);

            //Assert
            validationResult.IsValid.Should().Be(result);
        }
コード例 #25
0
        public async Task <ActionResult <GenericCommandResult> > Update(
            [FromBody] UpdateBookCommand command,
            [FromServices] ProductHandler handler,
            [FromServices] IProductRepository repository,
            int id
            )
        {
            var book = repository.GetById(id);

            if (book == null)
            {
                return(BadRequest());
            }

            command.MergeEntity(book);

            var result = handler.Handle(command);

            return(Ok(result));
        }
コード例 #26
0
ファイル: BooksTests.cs プロジェクト: cpayen/Note.06
        public async Task UpdateAsync_CheckResult()
        {
            var title        = "Book's title";
            var slug         = "books-title";
            var description  = "Book's description";
            var readAccess   = Access.Private;
            var writreAccess = Access.Private;

            var auth  = IAuthMock.GetIOwnedWriteAllowed();
            var uow   = IUnitOfWorkMock.Get(IBookRepositoryMock.GetFindAsync(_book));
            var books = new Books(uow, auth);
            var cmd   = new UpdateBookCommand(_book.Id, title, slug, description, readAccess, writreAccess);
            var book  = await books.UpdateAsync(cmd);

            Assert.Equal(title, book.Title);
            Assert.Equal(slug, book.Slug);
            Assert.Equal(description, book.Description);
            Assert.Equal(readAccess, book.ReadAccess);
            Assert.Equal(writreAccess, book.WriteAccess);
        }
コード例 #27
0
        public void Validate_ValidCommand_NoErrors()
        {
            var command = new UpdateBookCommand()
            {
                BookId        = 1,
                Title         = "Title",
                Description   = "Description",
                YearPublished = 2020,
                Author        = new AuthorDTO()
                {
                    FirstName = "FirstName",
                    LastName  = "LastName"
                }
            };

            var result = _sut.Validate(command);

            result.IsValid.Should().BeTrue();
            result.Errors.Should().BeEmpty();
        }
コード例 #28
0
        public ResponseResult Handle(UpdateBookCommand command)
        {
            command.Validate();

            if (command.Invalid)
            {
                return(new ResponseResult("Erro ao atualizar livro", false, null, command.Notifications));
            }

            command.Validate();

            if (command.Invalid)
            {
                return(new ResponseResult("Erro ao inserir novo livro", false, null, command.Notifications));
            }

            var books = _bookRepository.GetByTitleAndCode(command.Title, command.Code);
            var code  = _bookRepository.GetByCode(command.Code);

            if (books != null && Guid.Parse(command.Id) != books.Id)
            {
                command.AddNotification("Titulo", "Título já cadastrado");
            }

            if (code != null && Guid.Parse(command.Id) != code.Id)
            {
                command.AddNotification("Código", "Código já cadastrado");
            }

            if (command.Invalid)
            {
                return(new ResponseResult("Erro ao inserir novo livro", false, null, command.Notifications));
            }

            var book = new Book(Guid.Parse(command.Id), command.Title, command.Code, command.Ativo);

            _bookRepository.Update(book);
            _unitOfWork.Commit();

            return(new ResponseResult("Livro atualizado com sucesso", true, book));
        }
コード例 #29
0
        public async Task Update_Book()
        {
            using (var context = GetContextWithData())
            {
                var handler = new UpdateBookCommandHandler(context);

                var categoryId = Guid.NewGuid();

                await AddCategory(context, categoryId, "nothing");

                var command = new UpdateBookCommand
                {
                    Id         = (await context.Books.FirstOrDefaultAsync()).Id,
                    Title      = "Title2",
                    Categories = new List <GetBookModelCategory> {
                        new GetBookModelCategory {
                            Id = categoryId, Name = "nothing"
                        }
                    }
                };

                await handler.Handle(command, CancellationToken.None);

                var book = await context.Books
                           .Include(c => c.BookCategories)
                           .ThenInclude(c => c.Category)
                           .Where(b => b.Id == command.Id)
                           .FirstOrDefaultAsync();

                var bookCategories = book.BookCategories.Select(b => new GetBookModelCategory
                {
                    Id = b.CategoryId, Name = b.Category.Name
                })
                                     .ToList();

                Assert.Equal(command.Title, book.Title);
                Assert.Equal(command.Categories.Count, book.BookCategories.Count);
                Assert.Equal(command.Categories.ToList().FirstOrDefault()?.Id, bookCategories.FirstOrDefault()?.Id);
                Assert.Equal(command.Categories.ToList().FirstOrDefault()?.Name, bookCategories.FirstOrDefault()?.Name);
            }
        }
コード例 #30
0
        public async Task <IActionResult> UpdateBookForAuthor(long authorId, long bookId, BookForUpdateDto book)
        {
            Guard.Against.Null(book, nameof(book));

            var author = await _messages.Dispatch(new GetAuthorQuery(authorId));

            if (author is null)
            {
                return(NotFound($"No author with id {authorId} was found."));
            }

            var bookForAuthorFromRepo = await _messages.Dispatch(new GetBookQuery(authorId, bookId));

            // upsert
            if (bookForAuthorFromRepo == null)
            {
                var addCommand = new CreateBookCommand(book.Title, book.Description, authorId);

                Result <Book> addResult = await _messages.Dispatch(addCommand);

                if (addResult.IsFailure)
                {
                    return(BadRequest(addResult.Error));
                }

                var bookToReturn = _mapper.Map <BookDto>(addResult.Value);
                return(CreatedAtRoute(nameof(GetBookForAuthor),
                                      new { authorId, bookId = bookToReturn.Id }, bookToReturn));
            }

            var updateCommand = new UpdateBookCommand(bookId, book.Title, book.Description, authorId);

            Result <Book> updateResult = await _messages.Dispatch(updateCommand);

            if (updateResult.IsFailure)
            {
                return(BadRequest(updateResult.Error));
            }

            return(NoContent());
        }