Beispiel #1
0
        public IActionResult UpdateBook(int bookId, [FromBody] BookUpdateDto updatedBook)
        {
            if (updatedBook == null)
            {
                BadRequest(ModelState);
            }

            if (bookId != updatedBook.Id)
            {
                BadRequest(ModelState);
            }

            if (!_unitOfWork.BookRepository.BookExistsById(bookId))
            {
                ModelState.AddModelError("", "Book doesn't exist!");
            }

            if (!ModelState.IsValid)
            {
                StatusCode(404, ModelState);
            }

            if (!_unitOfWork.BookRepository.UpdateBook(updatedBook))
            {
                ModelState.AddModelError("", $"Something went wrong updating the book " + $"{updatedBook.BookTitle} ");
                StatusCode(500, ModelState);
            }

            _unitOfWork.Commit();

            return(NoContent());
        }
        public async Task <IActionResult> UpdateBook(Guid id, [FromBody] BookUpdateDto book)
        {
            if (id == Guid.Empty)
            {
                return(BadRequest(InvalidIdentifier));
            }

            if (!ModelState.IsValid)
            {
                return(ValidationProblem(ModelState));
            }

            try
            {
                await _bookService.UpdateBookAsync(id, book);

                return(NoContent());
            }
            catch (BookNotFoundException exception)
            {
                _logger.LogError($"Error occurred: {exception.GetMessageWithStackTrace()}");
                return(NotFound($"Book with id:{id} not found."));
            }
            catch (Exception exception)
            {
                _logger.LogError($"Error occurred: {exception.GetMessageWithStackTrace()}");
                return(InternalServerErrorResult("Error occurred updating book with id: {id}."));
            }
        }
Beispiel #3
0
        public ActionResult <BookDto> UpdateBook(int id, [FromBody] BookUpdateDto bookUpdateDto)
        {
            if (bookUpdateDto == null)
            {
                return(BadRequest());
            }

            var existingBookItem = _bookRepository.GetSingle(id);

            if (existingBookItem == null)
            {
                return(NotFound());
            }

            _mapper.Map(bookUpdateDto, existingBookItem);

            _bookRepository.Update(id, existingBookItem);

            if (!_bookRepository.Save())
            {
                throw new Exception("Updating a bookitem failed on save.");
            }

            return(Ok(_mapper.Map <BookDto>(existingBookItem)));
        }
Beispiel #4
0
        public BookDto Update(long id, BookUpdateDto update)
        {
            var existing = _dataContext.Books
                           .FirstOrDefault(p => p.Id == id);

            if (existing == null)
            {
                // TODO: don't throw that
                throw new Exception();
            }

            var history = UpdateAndGetHistory(existing, update);

            _dataContext.BookHistories.AddRange(history);

            _dataContext.SaveChanges();

            return(new BookDto
            {
                Id = id,
                Title = existing.Title,
                Description = existing.Description,
                PublishDate = existing.PublishDate
            });
        }
Beispiel #5
0
        private static IEnumerable <BookHistory> UpdateAndGetHistory(Book source, BookUpdateDto update)
        {
            if (source.Title != update.Title)
            {
                source.Title = update.Title;
                yield return(new BookHistory
                {
                    BookId = source.Id,
                    FieldName = nameof(source.Title),
                    OldValue = source.Title,
                    NewValue = update.Title,
                    TimestampUtc = DateTime.UtcNow
                });
            }

            if (source.Description != update.Description)
            {
                source.Description = update.Description;
                yield return(new BookHistory
                {
                    BookId = source.Id,
                    FieldName = nameof(source.Description),
                    OldValue = source.Description,
                    NewValue = update.Description,
                    TimestampUtc = DateTime.UtcNow
                });
            }
        }
        public ActionResult<BookDto> Update(int id, [FromBody] BookUpdateDto updateDto)
        {
            if (updateDto == null)
            {
                return BadRequest();
            }

            var item = _bookRepository.GetSingle(id);

            if (item == null)
            {
                return NotFound();
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Mapper.Map(updateDto, item);

            _bookRepository.Update(id, item);

            if (!_bookRepository.Save())
            {
                throw new Exception("Updating an item failed on save.");
            }

            return Ok(Mapper.Map<BookDto>(item));
        }
Beispiel #7
0
        [ProducesDefaultResponseType]                           //Any error that doesn't fall above
        public async Task <ActionResult> UpdateBook(BookUpdateDto bookUpdateDto)
        {
            //Get book from DB by Id
            var book = await _unitOfWork.Book.GetBookByIdAsync(bookUpdateDto.Id);

            if (book == null)
            {
                //404
                return(NotFound());
            }

            //Map the input Dto to our Book class
            _mapper.Map(bookUpdateDto, book);

            //Book object is flagged as being updated by EF
            _unitOfWork.Book.Update(book);

            //Persist changes to DB
            if (await _unitOfWork.Book.SaveAllAsync())
            {
                return(NoContent());
            }
            else
            {
                //400
                return(BadRequest("Failed to update Book."));
            }
        }
        public ActionResult<BookDto> PartiallyUpdate(int id, [FromBody] JsonPatchDocument<BookUpdateDto> patchDoc)
        {
            if (patchDoc == null)
            {
                return BadRequest();
            }

            Book existingEntity = _bookRepository.GetSingle(id);

            if (existingEntity == null)
            {
                return NotFound();
            }

            BookUpdateDto bookUpdateDto = Mapper.Map<BookUpdateDto>(existingEntity);
            patchDoc.ApplyTo(bookUpdateDto, ModelState);

            TryValidateModel(bookUpdateDto);

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Mapper.Map(bookUpdateDto, existingEntity);
            Book updated = _bookRepository.Update(id, existingEntity);

            if (!_bookRepository.Save())
            {
                throw new Exception("Updating an item failed on save.");
            }

            return Ok(Mapper.Map<BookDto>(updated));
        }
Beispiel #9
0
        public async Task UpdateBookDb(Book book, BookUpdateDto model)
        {
            try
            {
                if (!String.IsNullOrEmpty(model.Author))
                {
                    book.Author = model.Author;
                }

                if (!String.IsNullOrEmpty(model.Title))
                {
                    book.Title = model.Title;
                }

                if (model.PublishingDate != null && model.PublishingDate.HasValue)
                {
                    book.PublishingDate = model.PublishingDate;
                }
                book.IsDeleted = model.IsDeleted;
                book.IsPublic  = model.IsPublic;

                _context.Books.Update(book);
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                throw new DbException(e.Message, e.InnerException);
            }
        }
        public async Task <IActionResult> PutBook(int authorId, int id, BookUpdateDto bookDto)
        {
            if (!_context.Authors.Any(a => a.Id == authorId))
            {
                return(NotFound());
            }
            var book = await _context.Books.FindAsync(id);

            if (book.AuthorId != authorId)
            {
                return(BadRequest());
            }

            _context.Entry(book).State = EntityState.Modified;

            _mapper.Map(bookDto, book);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #11
0
        private IActionResult Upsert(Guid authorId, Guid id, JsonPatchDocument <BookUpdateDto> book)
        {
            var bookDto = new BookUpdateDto();

            book.ApplyTo(bookDto, ModelState);

            if (bookDto.Description == bookDto.Title)
            {
                ModelState.AddModelError(nameof(BookUpdateDto), "Title and Description must be different");
            }

            TryValidateModel(bookDto);

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var bookToAdd = _mapper.Map <Book>(bookDto);

            bookToAdd.Id = id;

            _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

            if (!_libraryRepository.Save())
            {
                throw new Exception("Failed to add book");
            }

            var bookToReturn = _mapper.Map <BookDto>(bookToAdd);

            return(CreatedAtRoute(ApiNames.GetBookForAuthor, new { authorId, id = bookToReturn.Id }, bookToReturn));
        }
        //public bool UpdateBook(List<int> authorsId, List<int> genresId, List<int> reviewersId, List<int> librariansId, List<int> readersId, Book book)
        //{
        //    var authors = _bookContext.Authors.Where(a => authorsId.Contains(a.Id)).ToList();
        //    var genres = _bookContext.Genres.Where(g => genresId.Contains(g.Id)).ToList();
        //    var reviewers = _bookContext.Reviewers.Where(rev => reviewersId.Contains(rev.Id)).ToList();
        //    var librarians = _bookContext.Librarians.Where(l => librariansId.Contains(l.Id)).ToList();
        //    var readers = _bookContext.Readers.Where(r => readersId.Contains(r.Id)).ToList();

        //    var bookAuthorsToDelete = _bookContext.BooksAuthors.Where(b => b.BookId == book.Id);
        //    var bookGenresToDelete = _bookContext.BooksGenres.Where(b => b.BookId == book.Id);
        //    var bookReviewersToDelete = _bookContext.BooksReviewers.Where(b => b.BookId == book.Id);
        //    var bookLibrariansToDelete = _bookContext.LibrariansBooks.Where(b => b.BookId == book.Id);
        //    var bookReadersToDelete = _bookContext.ReadersBooks.Where(b => b.BookId == book.Id);

        //    _bookContext.RemoveRange(bookAuthorsToDelete);
        //    _bookContext.RemoveRange(bookGenresToDelete);
        //    _bookContext.RemoveRange(bookReviewersToDelete);
        //    _bookContext.RemoveRange(bookLibrariansToDelete);
        //    _bookContext.RemoveRange(bookReadersToDelete);

        //    foreach (var author in authors)
        //    {
        //        var bookAuthor = new BookAuthor()
        //        {
        //            Author = author,
        //            Book = book
        //        };
        //        _bookContext.Add(bookAuthor);
        //    }

        //    foreach (var genre in genres)
        //    {
        //        var bookGenre = new BookGenre()
        //        {
        //            Genre = genre,
        //            Book = book
        //        };
        //        _bookContext.Add(bookGenre);
        //    }

        //    foreach (var reviewer in reviewers)
        //    {
        //        var bookReviewer = new BookReviewer()
        //        {
        //            Reviewer = reviewer,
        //            Book = book
        //        };
        //        _bookContext.Add(bookReviewer);
        //    }

        //    foreach (var librarian in librarians)
        //    {
        //        var librarianBook = new LibrarianBook()
        //        {
        //            Book = book,
        //            Librarian = librarian
        //        };
        //        _bookContext.Add(librarianBook);
        //    }

        //    foreach (var reader in readers)
        //    {
        //        var readerBook = new ReaderBook()
        //        {
        //            Book = book,
        //            Reader = reader
        //        };
        //        _bookContext.Add(readerBook);
        //    }

        //    _bookContext.Add(book);

        //    return Save();
        //}

        public bool UpdateBook(BookUpdateDto bookToUpdateDto)
        {
            var bookToUpdate = MapConfig.Mapper.Map <Book>(bookToUpdateDto);

            _bookContext.Update(bookToUpdate);
            return(Save());
        }
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id,
                                                 [FromBody] BookUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            //TODO : 07 - Agrego regla de Negocio al Update
            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookCreationDto),
                                         "El titulo debe de ser distinto a la descripción.");
            }

            //TODO : 08 - Valido el modelo
            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Libro {id} del autor {authorId} fallo al intentar crearse.");
                }

                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId = authorId, id = bookToReturn.Id },
                                      bookToReturn));
            }

            Mapper.Map(book, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"El libro {id} del autor {authorId} no se actualizo.");
            }


            return(NoContent());
        }
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookUpdateDto), "A book's description cannot be the same as the title!");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            // If book is not fond we'll create a new one
            if (bookForAuthorFromRepo == null)
            {
                var bookToAdd = AutoMapper.Mapper.Map <Book>(book);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed on save.");
                }

                var bookToReturn = AutoMapper.Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new
                {
                    authorId = authorId,
                    bookId = bookToReturn.Id
                },
                                      bookToReturn));
            }

            AutoMapper.Mapper.Map(book, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book {id} for author {authorId} failed on save.");
            }

            return(NoContent());
        }
Beispiel #15
0
        public BookServiceTests()
        {
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new BookProfile());
            });

            book = new Book()
            {
                Id           = 1,
                Name         = "Test Name",
                Description  = "Test Description",
                Author       = "Test Author",
                Genre        = DAL.Enumeration.BookGenre.Adventure,
                Pages        = 100,
                Condition    = DAL.Enumeration.BookCondition.New,
                IsActive     = true,
                CreationDate = new System.DateTime(),
                ModifyDate   = new System.DateTime()
            };

            bookDto = new BookDto()
            {
                Id          = 1,
                Name        = "Test Name",
                Description = "Test Description",
                Author      = "Test Author",
                Genre       = DAL.Enumeration.BookGenre.Adventure,
                Pages       = 100,
                Condition   = DAL.Enumeration.BookCondition.New,
                IsActive    = true
            };

            bookNewDto = new BookNewDto()
            {
                Name        = "Test Name",
                Description = "Test Description",
                Author      = "Test Author",
                Genre       = DAL.Enumeration.BookGenre.Adventure,
                Pages       = 100,
                Condition   = DAL.Enumeration.BookCondition.New
            };

            bookUpdateDto = new BookUpdateDto()
            {
                Id          = 1,
                Name        = "Test Name",
                Description = "Test Description",
                Author      = "Test Author",
                Genre       = DAL.Enumeration.BookGenre.Adventure,
                Pages       = 100,
                Condition   = DAL.Enumeration.BookCondition.New
            };

            _mapper                  = new Mapper(configuration);
            _bookRepository          = new Mock <GenericRepository <Book, int> >(MockBehavior.Loose, new object[] { });
            _availableBookRepository = new Mock <GenericRepository <AvailableBook, int> >(MockBehavior.Loose, new object[] { });
        }
Beispiel #16
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookUpdateDto book)
        {
            if (book == null)
            {
                return(NotFound());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookUpdateDto),
                                         "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepository = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepository == null)
            {
                // Upserting
                var bookEntity = AutoMapper.Mapper.Map <Book>(book);
                bookEntity.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookEntity);

                if (!_libraryRepository.Save())
                {
                    throw new Exception("something went wrong...");
                }

                var bookDto = AutoMapper.Mapper.Map <BookDto>(bookEntity);

                return(CreatedAtRoute("GetBookForAuthor", new { authorId, id = bookDto.Id }, bookDto));
            }

            // update all the fields in bookForAuthorFromRepository from source: bookUpdateDto
            AutoMapper.Mapper.Map(book, bookForAuthorFromRepository);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepository);

            if (_libraryRepository.Save())
            {
                throw new Exception("something went wrong");
            }

            return(NoContent());
        }
Beispiel #17
0
        public async Task <IActionResult> Update(int id, [FromBody] BookUpdateDto bookDto)
        {
            var location = GetControllerActionNames();

            try
            {
                _logger.LogInfo($"{location}: Update attempted on record with id: {id}.");
                if (id < 1 || bookDto == null || id != bookDto.Id)
                {
                    _logger.LogWarn($"{location}: Update failed with bad data - id: {id}.");
                    return(BadRequest());
                }
                var isExists = await _bookRepository.isExists(id);

                if (!isExists)
                {
                    _logger.LogWarn($"{location}: Failed to retrieve record with id: {id}.");
                    return(NotFound());
                }
                if (!ModelState.IsValid)
                {
                    _logger.LogWarn($"{location}: Data was incomplete.");
                    return(BadRequest(ModelState));
                }
                var oldImage = await _bookRepository.GetImageFileName(id);

                var book      = _mapper.Map <Book>(bookDto);
                var isSuccess = await _bookRepository.Update(book);

                if (!isSuccess)
                {
                    return(InternalError($"{location}: Update failed for record with id: {id}."));
                }
                if (!bookDto.Image.Equals(oldImage))
                {
                    if (System.IO.File.Exists(GetImagePath(oldImage)))
                    {
                        System.IO.File.Delete(GetImagePath(oldImage));
                    }
                }
                if (!string.IsNullOrEmpty(bookDto.File))
                {
                    byte[] imageBytes = Convert.FromBase64String(bookDto.File);
                    System.IO.File.WriteAllBytes(GetImagePath(bookDto.Image), imageBytes);
                }

                _logger.LogInfo($"{location}: Record with id: {id} successfully updated.");
                return(NoContent());
            }
            catch (Exception e)
            {
                return(InternalError($"{location}: {e.Message} - {e.InnerException}"));
            }
        }
Beispiel #18
0
        public Book Update(BookUpdateDto dto, ImageUploadResult url)
        {
            var isExist = GetDetail(dto.Id);

            if (!categoryService.Exist(dto.CategoryId))
            {
                throw new ArgumentException("One/Some of categories not existed");
            }
            if (!authorService.Exist(dto.AuthorId))
            {
                throw new ArgumentException("One/Some of authors not existed");
            }
            dto.Title = FormatString.Trim_MultiSpaces_Title(dto.Title, true);
            if (publisherService.GetDetail(dto.PublisherId) == null)
            {
                throw new ArgumentException("Publisher not existed");
            }
            var entity = new Book();

            if (url != null)
            {
                entity.Id              = dto.Id;
                entity.ISBN            = FormatString.Trim_MultiSpaces_Title(dto.ISBN);
                entity.Title           = dto.Title;
                entity.Summary         = dto.Summary;
                entity.Image           = url.SecureUrl.AbsoluteUri;
                entity.PublicationDate = dto.PublicationDate;
                entity.QuantityInStock = dto.QuantityInStock;
                entity.Price           = dto.Price;
                entity.Sold            = dto.Sold;
                entity.Discount        = dto.Discount;
                entity.PublisherId     = dto.PublisherId;
            }
            else
            {
                entity.Id              = dto.Id;
                entity.ISBN            = FormatString.Trim_MultiSpaces_Title(dto.ISBN);
                entity.Title           = dto.Title;
                entity.Image           = isExist.Image;
                entity.Summary         = dto.Summary;
                entity.PublicationDate = dto.PublicationDate;
                entity.QuantityInStock = dto.QuantityInStock;
                entity.Price           = dto.Price;
                entity.Sold            = dto.Sold;
                entity.Discount        = dto.Discount;
                entity.PublisherId     = dto.PublisherId;
            }

            var book = repository.Update(entity);

            bookCategoryService.Update(book, dto.CategoryId);
            authorBookService.Update(book, dto.AuthorId);
            return(book);
        }
Beispiel #19
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound("Author not found!"));
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookUpdateDto), "Title and Description must be different");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                var bookToAdd = _mapper.Map <Book>(book);
                bookToAdd.Id = id;
                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception("Upserting book failed!");
                }

                var bookToReturn = _mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute(
                           ApiNames.GetBookForAuthor,
                           new { authorId, id = bookToReturn.Id },
                           CreateLinksForBook(bookToReturn)));
            }

            _mapper.Map(book, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception("Update failed!");
            }

            return(NoContent());
        }
Beispiel #20
0
        public IActionResult Put(Guid authorId, Guid id, [FromBody] BookUpdateDto bookDto)
        {
            if (bookDto == null)
            {
                return(BadRequest());
            }

            if (bookDto.Description == bookDto.Title)
            {
                ModelState.AddModelError(nameof(BookUpdateDto), "The description must be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!Repository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            Book book = Repository.GetBook(authorId, id);

            if (book == null)
            {
                var bookToAdd = Mapper.Map <Book>(bookDto);
                //var bookToAdd = Mapper.Map(bookDto, book);
                bookToAdd.Id = id;
                Repository.CreateBook(authorId, bookToAdd);

                if (!Repository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed.");
                }

                var bookCreated = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBook", new { authorId, id = bookCreated.Id }, CreateBookLinks(bookCreated)));
            }

            // Mapper.Map<Book>(bookDto);
            Mapper.Map(bookDto, book);

            Repository.UpdateBook(book);

            if (!Repository.Save())
            {
                throw new Exception($"Failed to update book {id} for author {authorId}");
            }

            return(NoContent());
        }
Beispiel #21
0
        public async Task <SingleResult <BookDto> > UpdateBook(BookUpdateDto model)
        {
            var result = new SingleResult <BookDto>();

            var updateBookResult = await UpdateAsync(_mapper.Map <BookUpdateDto, BookDto>(model));

            result.IsSuccessful = updateBookResult.IsSuccessful;
            result.Data         = updateBookResult.Data;
            result.Message      = updateBookResult.Message;

            return(result);
        }
        public IActionResult PartialUpdateBookForAuthor(Guid authorId, Guid id,
                                                        [FromBody] JsonPatchDocument <BookUpdateDto> patchDoc)
        {
            if (patchDoc == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                var bookDto = new BookUpdateDto();
                patchDoc.ApplyTo(bookDto);

                var bookToAdd = AutoMapper.Mapper.Map <Book>(bookDto);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);
                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting the book {id} for an author {authorId} failed on save.");
                }

                var bookToReturn = AutoMapper.Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId = authorId, id = bookToReturn.Id },
                                      bookToReturn));
            }

            var bookToPatch = AutoMapper.Mapper.Map <BookUpdateDto>(bookForAuthorFromRepo);

            patchDoc.ApplyTo(bookToPatch);

            //add validation

            AutoMapper.Mapper.Map(bookToPatch, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Patching book {id} for author {authorId} failed on Save.");
            }

            return(NoContent());
        }
        public async Task <IActionResult> UpdateBook(BookUpdateDto bookUpdateDto)
        {
            var book = await _bookRepo.GetByIdAsync(bookUpdateDto.Id);

            if (book == null)
            {
                return(NotFound("User not found"));
            }
            var updateBook = _mapper.Map <Book>(bookUpdateDto);

            _bookRepo.Update(updateBook);
            return(NoContent());
        }
Beispiel #24
0
        public async Task <ActionResult> Update(int id, [FromBody] BookUpdateDto bookUpdateDto)
        {
            Book book = await _bookRepository.FindByIdAsync(id);

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

            _mapper.Map(bookUpdateDto, book);
            await _bookRepository.UpdateAsync(book);

            return(NoContent());
        }
Beispiel #25
0
        public ActionResult UpdateBook(int bookId, BookUpdateDto bookUpdateDto)
        {
            var bookModelFromRepo = _baseLibRepository.GetBook(bookId);

            if (bookModelFromRepo == null)
            {
                return(NotFound());
            }
            _mapper.Map(bookUpdateDto, bookModelFromRepo);
            _baseLibRepository.UpdateBook(bookModelFromRepo);
            _baseLibRepository.SaveChanges();

            return(NoContent());
        }
Beispiel #26
0
        public async Task UpdateBookAsync(Guid id, BookUpdateDto bookUpdateDto)
        {
            ValidateId(id);
            ValidateEntity(bookUpdateDto);

            var book = await _bookRepository.GetByIdAsync(id);

            if (book == null)
            {
                throw new BookNotFoundException(id);
            }

            _mapper.Map(bookUpdateDto, book);
            await _bookRepository.UpdateBookAsync(book);
        }
Beispiel #27
0
        public async Task <IActionResult> UpdateBook([FromBody] BookUpdateDto model)
        {
            if (!ModelState.IsValid)
            {
                var badResult = new OperationResult();
                badResult.Message = string.Join("; ", ModelState.Values
                                                .SelectMany(x => x.Errors)
                                                .Select(x => x.ErrorMessage));
                return(new OkObjectResult(badResult));
            }

            var result = await _bookService.UpdateBook(model);

            return(new OkObjectResult(result));
        }
Beispiel #28
0
        public bool Update(BookUpdateDto bookUpdate, BookOutputDto bookOutput)
        {
            try
            {
                var bookUpdated = _mapper.Map(bookUpdate, bookOutput);
                var book        = _mapper.Map <BookOutputDto, Book>(bookUpdated);

                _bookService.Update(book);
                return(Commit());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #29
0
        public async Task <IActionResult> PutBook(int id, BookUpdateDto bookDto)
        {
            if (id < 1 || id != bookDto.Id || bookDto == null)
            {
                return(BadRequest("Invalid book details provided."));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(new { Book = ModelState, Message = "Incomplete book details." }));
            }

            await _bookService.Update(_mapper.Map <Book>(bookDto));

            return(NoContent());
        }
Beispiel #30
0
        public async Task <BookOutputDto> UpdateBook([FromBody] BookUpdateDto input)
        {
            var result = new Book();

            try
            {
                var book = _mapper.Map <Book>(input);
                result = await _bookManager.UpdateAsync(book);
            }
            catch (System.Exception ex)
            {
                throw;
            }

            return(_mapper.Map <BookOutputDto>(result));
        }