public async Task AddBookAsyncTest()
        {
            // Act
            var result = await _bookRepository.AddAsync(_bookBuilder.CreateValidBook());

            // Assert
            result.Id.Should().BePositive();
        }
Ejemplo n.º 2
0
        public async Task HandleAysnc(BookChangeEvent domainEvent, CancellationToken cancellationToken = default)
        {
            await _repo.AddAsync(new Aggregates.Book("xx", "x", "x1"), cancellationToken);

            await _repo.AddAsync(new Aggregates.Book("xx", "x", "x1"), cancellationToken);

            await _repo.AddAsync(new Aggregates.Book("xx", "x", "x1"), cancellationToken);
        }
Ejemplo n.º 3
0
        public async Task AddBookAsync(BookDTO bookDTO)
        {
            Category category = await _categoryRepository.GetByNameAsync(bookDTO.CategoryName);

            if (category == null)
            {
                category = new Category(bookDTO.CategoryName);
            }

            Author author = await _authorRepository.GetByNameAsync(bookDTO.AuthorFirstname, bookDTO.AuthorSurname);

            if (author == null)
            {
                author = new Author(bookDTO.AuthorFirstname, bookDTO.AuthorSurname);
            }

            Book book = new Book(
                title: bookDTO.Title,
                price: bookDTO.Price,
                inStock: bookDTO.InStock,
                numberOfPages: bookDTO.NumberOfPages,
                descriptions: bookDTO.Descriptions,
                img: new Img(bookDTO.ImgPath),
                author: author,
                category: category
                );
            await _bookRepository.AddAsync(book);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Dodaj novu knjigu sa random kategorijom
        /// </summary>
        public async Task <bool> AddBokk(Book book)
        {
            int count = await _categoryrepo.CountAsync();

            Random rand = new Random();

            book.CategoryID = rand.Next(0, count);

            Book result = await _bookrepo.AddAsync(book);

            if (result != null)
            {
                List <BookCopy> copies = new List <BookCopy>();

                for (int i = 0; i < 20; i++)
                {
                    BookCopy copy = new BookCopy()
                    {
                        Borrowed = false, BookId = result.Id
                    };
                    copies.Add(copy);
                }

                return(await _copyrepo.AddRangeAsync(copies));
            }

            return(false);
        }
Ejemplo n.º 5
0
        public async Task <BookVm> Handle(CreateBook request, CancellationToken cancellationToken)
        {
            var    book = new Book(Guid.NewGuid(), request.Name, request.ReleaseYear, request.Pages, request.Summary, request.Publisher, request.ArtistId);
            string imageUrl;

            if (request.Poster?.HasValue() == true)
            {
                if (!string.IsNullOrEmpty(book.Poster))
                {
                    await _fileUtils.RemoveByUrlAsync(book.Poster);
                }

                var fileName = $"books/{Guid.NewGuid()}{request.Poster.Name.GetExtension()}";

                imageUrl = await _fileUtils.UploadAsync(request.Poster, fileName);

                if (imageUrl.IsNull())
                {
                    throw new Exception("Erro ao Importar o poster");
                }
            }
            else
            {
                imageUrl = book.Poster;
            }
            book.Poster = imageUrl;
            await _bookRepository.AddAsync(book);

            return(book.ToVm());
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Add or Update Book Async
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <ApiResponse <bool> > AddorUpdateBookAsync(BookModel model)
        {
            try
            {
                var result = _mapper.Map <BookModel, Book>(model);
                result.DateOfPublication = DateTime.Now;
                if (result.Id > 0)
                {
                    await _bookRepository.UpdateAsync(result);
                }
                else
                {
                    await _bookRepository.AddAsync(result);
                }

                var testResult = await Task.FromResult(true);

                return(ApiResponse <bool> .SuccessResult(testResult));
            }
            catch (Exception ex) when(ex is FailException || ex is ValidationException || ex is ArgumentException)
            {
                return(ApiResponse <bool> .ErrorResult(message : ex.Message, statusCode : HttpStatusCode.BadRequest));
            }
            catch (Exception ex) when(ex is ErrorException)
            {
                //LoggingManager.Error(ex.ToString());
                return(ApiResponse <bool> .ErrorResult(message : ex.Message));
            }
            catch (Exception ex)
            {
                //LoggingManager.Error(ex.ToString());
                return(ApiResponse <bool> .ErrorResult(message : ex.Message));
            }
        }
        public async Task <Response <bool> > Handle(AddBookCommand request, CancellationToken cancellationToken)
        {
            var uploadedBookPhotosData = await fileManager.AddMultipleFileAsync(request.BookPhotos, FileTypeEnum.BookPhoto);

            var uploadedBookFileData = await fileManager.AddFileAsync(request.BookFile, FileTypeEnum.BookFile);

            var book = new Book
            {
                publishDate = request.PublishedDate,
                BookName    = request.BookName,

                AuthorId    = request.Userid,
                Price       = request.Price,
                Category    = (BookCategoryEnum)request.Category,
                Description = request.Description,
                File        = new File {
                    Url  = uploadedBookFileData.Url,
                    Path = uploadedBookFileData.Path
                },
                Imgs = uploadedBookPhotosData.Select(u => new Img {
                    Url  = u.Url,
                    Path = u.Path
                }).ToList()
            };
            await bookRepo.AddAsync(book);

            return(Response.Ok());
        }
Ejemplo n.º 8
0
 public async Task AddAsync(Book book)
 {
     if (!RunValidation(new BookValidation(), book))
     {
         return;
     }
     await _bookRepository.AddAsync(book);
 }
        public async Task <Response> Handle(CreateBookCommand request, CancellationToken cancellationToken)
        {
            var book = new Book(request.Title);

            await _bookRepository.AddAsync(book);

            return(new Response("Book criado com sucesso"));
        }
        public async Task <BookId> Handle(CreateBookCommand request, CancellationToken cancellationToken)
        {
            var product = Book.Create(request.BookName, request.AuthorName);

            IBookRepository bookRepository = _productDbContext.BookRepository;
            await bookRepository.AddAsync(product, cancellationToken);

            return(product.Id);
        }
Ejemplo n.º 11
0
 public async Task AddBookAsync(Book newBook)
 {
     try
     {
         await _bookRepository.AddAsync(newBook);
     }
     catch (MemberRelationException e)
     {
         throw;
     }
 }
Ejemplo n.º 12
0
        public async Task CreateAuthorAsync(Book book)
        {
            if (book.Quantity <= 0)
            {
                throw new Exception("No elo cos sie nie zgadza gościu. ");
            }

            await _bookRepository.AddAsync(book);

            await _unitOfWork.CompleteAsync();
        }
Ejemplo n.º 13
0
        public async Task AddBookAsync(string name, Author author, string genre, DateTime relasedAt)
        {
            var book = await _bookRepository.GetAsync(name);

            if (book != null)
            {
                throw new Exception($"Book with name '{name}' already exist.");
            }
            book = new Book(name, author, genre, relasedAt);
            await _bookRepository.AddAsync(book);
        }
Ejemplo n.º 14
0
        public async Task <ActionResult <Book> > Create([FromBody] BookApiModel model)
        {
            if (!_authorRepository.Exists(model.AuthorId))
            {
                return(BadRequest());
            }

            var newBook = await _bookRepository.AddAsync(ApiModelToBook(model));

            return(CreatedAtAction(nameof(Create), BookToApiModel(newBook)));
        }
Ejemplo n.º 15
0
        public async Task SaveAsync(BookEdit bookEdit)
        {
            Book book = bookEdit.Id == null ? new Book() : await bookRepository.GetEntityAsync(bookEdit.Id.Value, true);

            mapper.Map(bookEdit, book);

            if (bookEdit.Id == null)
            {
                await bookRepository.AddAsync(book);
            }
            await bookRepository.SaveChangesAsync();
        }
Ejemplo n.º 16
0
        public async Task CreateAsync(string title, string description, string image, string writer, string publisher, byte numberOfSets)
        {
            var book = new Book(title, description, image, writer, publisher, numberOfSets);

            for (int i = 0; i < book.NumberOfSets; i++)
            {
                Set set = new Set(book, true);

                book.Sets.Add(set);
            }

            await _bookRepository.AddAsync(book);
        }
Ejemplo n.º 17
0
        public async Task <Result <Book> > CreateBook(Book newBook)
        {
            ValidationResult validationResult = _validator.Validate(newBook);

            if (!validationResult.IsValid)
            {
                return(Result.Failure(newBook, validationResult.Errors.Select(s => s.ErrorMessage).ToList()));
            }

            var bookFromEF = await _bookRepository.AddAsync(newBook);

            return(Result.Success(bookFromEF));
        }
Ejemplo n.º 18
0
        public async Task <DbChangeResponse> AddAsync(Book book)
        {
            try
            {
                await _bookRepository.AddAsync(book);

                return(new DbChangeResponse(true, "Book succesfully added.", book));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred while creating the book: { ex.Message}");
                return(new DbChangeResponse(false, $"An error occurred while creatting the book: {ex.Message}", book));
            }
        }
Ejemplo n.º 19
0
        [HttpPost] // PostMapping
        public async Task <IActionResult> AddAsync([FromBody] Book dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            // <>
            var temp = new Book();

            temp.Title       = dto.Title;
            temp.Description = dto.Description;
            temp.Created     = DateTime.Now;
            // </>

            try
            {
                var model = await _repository.AddAsync(temp);

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

                //[!] 다음 항목 중 원하는 방식 사용
                if (DateTime.Now.Second % 60 == 0)
                {
                    return(Ok(model)); // 200 OK
                }
                else if (DateTime.Now.Second % 3 == 0)
                {
                    return(CreatedAtRoute("GetBookById", new { id = model.Id }, model)); // Status: 201 Created
                }
                else if (DateTime.Now.Second % 2 == 0)
                {
                    var uri = Url.Link("GetBookById", new { id = model.Id });
                    return(Created(uri, model)); // 201 Created
                }
                else
                {
                    // GetById 액션 이름 사용해서 입력된 데이터 반환
                    return(CreatedAtAction(nameof(GetById), new { id = model.Id }, model));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(BadRequest());
            }
        }
Ejemplo n.º 20
0
        public async Task <BookSaveResponse> SaveAsync(Book book)
        {
            try
            {
                await _bookRepository.AddAsync(book);

                await _transaction.CompleteAsync();

                return(new BookSaveResponse(book));
            }
            catch (Exception ex)
            {
                return(new BookSaveResponse($"An error occurred while attempting to save the book: {ex.Message}"));
            }
        }
Ejemplo n.º 21
0
        public async Task <BookResponse> SaveAsync(Book book)
        {
            try
            {
                await _bookRepository.AddAsync(book);

                await _unitOfWork.CompleteAsync();

                return(new BookResponse(book));
            }
            catch (Exception ex)
            {
                return(new BookResponse($"An error occurred when saving the book:{ex.Message}"));
            }
        }
        public async Task <ActionResult> BookShip(CreateBookInput input)
        {
            Book order = new Book
            {
                BookNo   = input.BookNo,
                Author   = input.Author,
                BookName = input.BookName,
                Category = input.Category,
                Price    = input.Price
            };

            await _bookRepository.AddAsync(order);

            return(Ok());
        }
Ejemplo n.º 23
0
        public async Task <BookResponse> AddAsync(Book book)
        {
            try
            {
                Book createdBook = await _bookRepository.AddAsync(book);

                return(new BookResponse(createdBook));
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);

                return(new BookResponse($"An error occurred when saving the book: {ex.Message}"));
            }
        }
Ejemplo n.º 24
0
        public async Task <IdResponse> CreateBookAsync(BookProxy book)
        {
            Validate(book);

            await _authorModel.ValidateExistingAuthorAsync(book.AuthorId);

            await ValidateUniqueness(book.Title, null);

            var entity = new Book();

            MapToEntity(book, entity);

            var id = await _repository.AddAsync(entity);

            return(new IdResponse(id));
        }
        public async Task <BookModel> Handle(CreateBookCommand request, CancellationToken cancellationToken)
        {
            IList <Author> authors = new List <Author>();

            if (request.AuthorIds != null && request.AuthorIds.Any())
            {
                authors = await authorRepository.FindWhereInAsync(request.AuthorIds);
            }

            var book = new Book(request.Title, authors);

            await bookRepository.AddAsync(book);

            await bookRepository.UnitOfWork.SaveChangesAsync(cancellationToken);

            return(mapper.MapEntityToModel <Book, BookModel>(book));
        }
Ejemplo n.º 26
0
        public async Task AddBookAsync(BookDetails book)
        {
            List <Language> languages = new List <Language>();

            foreach (var abbriviation in book.Languages)
            {
                Language entity = languageRepository.GetByAbbriviation(abbriviation);
                if (entity == null)
                {
                    entity = await languageRepository.AddLanguageAsync(new Language()
                    {
                        Abbriviation = abbriviation,
                        Name         = GetLanguageNameByAbbriviation(abbriviation)
                    });
                }
                languages.Add(entity);
            }
            await bookRepository.AddAsync(book);
        }
Ejemplo n.º 27
0
        public async Task <IActionResult> Create(CreateViewModel model)
        {
            model.BookId          = Guid.NewGuid();
            model.CreatedByUserId = userManager.GetUserId(User);

            if (ModelState.IsValid)
            {
                try
                {
                    await bookRepository.AddAsync(model);

                    return(RedirectToAction(nameof(Index)));
                }
                catch
                {
                    return(View());
                }
            }
            return(View(model));
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> Post([FromBody] CreationBookDto book)
        {
            if (book == null)
            {
                return(NotFound("Book cannot be null"));
            }

            var bookExist = await _bookRepository.GetByIsbnAsync(book.Isbn);

            if (bookExist != null)
            {
                return(Conflict($"Book with isbn '{book.Isbn}' already exist"));
            }

            var finalBook = _mapper.Map <Book>(book);

            await _bookRepository.AddAsync(finalBook);

            return(CreatedAtRoute("GetBookByIsbn", new { isbn = book.Isbn }, finalBook));
        }
        public async Task <Book> AddOrUpdateBookAsync(Book book)
        {
            Book updated = null;

            if (book.BookId == 0)
            {
                updated = await _booksRespository.AddAsync(book);

                _books.Add(updated);
            }
            else
            {
                updated = await _booksRespository.UpdateAsync(book);

                Book old = _books.Where(c => c.BookId == updated.BookId).Single();
                int  inx = _books.IndexOf(old);
                _books.RemoveAt(inx);
                _books.Insert(inx, updated);
            }
            return(updated);
        }
        public async Task <BookViewModel> AddAsync(BookInputModel bookInputModel)
        {
            var book = mapper.Map <Book>(bookInputModel);

            book.PublishingCompany = await publishingCompanyRepository.GetAsync(bookInputModel.PublishingCompanyId);

            /*
             * var authors = new List<Author>();
             *
             * foreach (var authorId in bookInputModel.AuthorIds)
             * {
             *  authors.Add(await authorRepository.GetAsync(authorId));
             * }
             */

            var authors = await Task.WhenAll(bookInputModel.AuthorIds.Select(async a => await authorRepository.GetAsync(a)));

            /*
             * book.AuthorsLink = new List<BookAuthor>();
             *
             * foreach (var author in authors)
             * {
             *  book.AuthorsLink.Add(new BookAuthor() { Book = book, Author = author });
             * }
             */

            //book.AuthorsLink = new List<BookAuthor> { new BookAuthor { Book = book, Author = authors[0]} };
            book.AuthorsLink = new List <BookAuthor>();
            book.AuthorsLink.AddRange(authors.Select(a => new BookAuthor {
                Book = book, Author = a
            }));

            var result = await repository.AddAsync(book);

            var bookViewModel = mapper.Map <BookViewModel>(result);

            return(bookViewModel);
        }