Exemplo n.º 1
0
        public ActionResult AddBook(NewBookModel newBook)
        {
            if (Request.Form["ok"] != null)
            {
                var book = new Book
                {
                    book_name       = newBook.book_name,
                    available_count = newBook.available_count,
                    price           = newBook.price,
                    description     = newBook.description
                };
                try
                {
                    using (var dbContext = new Bookshop_DBContext())
                    {
                        book.author_id = dbContext.Authors
                                         .First(a => newBook.author_name.Equals(a.first_name + " " + a.last_name)).author_id;

                        dbContext.Books.Add(book);
                        dbContext.SaveChanges();
                    }
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            return(Redirect("Index"));
        }
        public async Task UpdateBookCommand_should_not_be_valid_if_required_fields_are_empty(string title, string author)
        {
            // Arrange
            var file = new byte[] { 1, 2, 3 };

            await using var ms = new MemoryStream(file);
            var contentType = "image/jpeg";

            var newBook = new NewBookModel
            {
                Author      = author,
                Title       = title,
                Description = "Correct",
                Price       = 1,
                Image       = Helpers.CreateTestFormFile(ms, contentType)
            };

            var validator = new UpdateBookCommandValidator();

            // Act
            var result = await validator.ValidateAsync(new UpdateBookCommand(Guid.Empty, newBook));

            // Assert
            Assert.False(result.IsValid);
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Title)));
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Author)));
        }
Exemplo n.º 3
0
        public IActionResult RemoveBookForm()
        {
            var model = new NewBookModel {
            };

            return(View(model));
        }
        public async Task UpdateBookCommand_should_throw_not_found_exception_if_no_book_with_ID_in_DB()
        {
            // Arrange
            var file = new byte[] { 1, 2, 3 };

            await using var ms = new MemoryStream(file);
            var contentType = "image/jpeg";

            var newBook = new NewBookModel
            {
                Author      = "Correct",
                Title       = "Correct",
                Description = "Correct",
                Price       = 1,
                Image       = Helpers.CreateTestFormFile(ms, contentType)
            };

            A.CallTo(() => _repository.GetById(A <Guid> .Ignored, A <bool> .Ignored)).Returns <Book>(null);

            // Act
            var result = await Assert.ThrowsAsync <NotFoundException>(
                () => _handler.Handle(new UpdateBookCommand(Guid.Empty, newBook), default));

            // Assert
            A.CallTo(() => _repository.GetById(A <Guid> .Ignored, A <bool> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => _repository.Update(A <Guid> .Ignored, A <Book> .Ignored, A <CoverImage> .Ignored)).MustNotHaveHappened();
            Assert.Equal($"Book with ID {Guid.Empty} was not found.", result.Message);
        }
Exemplo n.º 5
0
        public async Task AddBookCommand_should_not_be_valid_if_fields_are_too_big()
        {
            // Arrange
            var file = new byte[] { 1, 2, 3 };

            await using var ms = new MemoryStream(file);
            var contentType = "image/pdf";

            var newBook = new NewBookModel
            {
                Author      = new string('a', 129),
                Title       = new string('a', 129),
                Description = new string('a', 2001),
                Price       = 1,
                Image       = Helpers.CreateTestFormFile(ms, contentType)
            };

            var validator = new AddBookCommandValidator();

            // Act
            var result = await validator.ValidateAsync(new AddBookCommand(newBook));

            // Assert
            Assert.False(result.IsValid);
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Title)));
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Author)));
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Description)));
        }
        public void UpdateBook(NewBookModel book)
        {
            Book updated_book = new Book();

            updated_book = GetBooksByCondition(b => b.Title == book.Title).First();

            if (book.AuthorName != null)
            {
                updated_book.AuthorId = (_authorService
                                         .GetAuthorByCondition(b => b.Name == book.AuthorName)
                                         .FirstOrDefault()).AuthorId;
            }

            if (book.GenreName != null)
            {
                updated_book.GenreId = repositoryWrapper.GenreRepository
                                       .FindByCondition(g => g.Name == book.GenreName)
                                       .FirstOrDefault().Id;
            }

            if (book.GenreId != 0)
            {
                updated_book.GenreId = book.GenreId;
            }

            repositoryWrapper.BookRepository.Update(updated_book);
        }
        public async Task UpdateBookCommand_should_not_be_valid_if_image_has_wrong_mime_type()
        {
            // Arrange
            var file = new byte[] { 1, 2, 3 };

            await using var ms = new MemoryStream(file);
            var contentType = "image/pdf";

            var newBook = new NewBookModel
            {
                Author      = "Correct",
                Title       = "Correct",
                Description = "Correct",
                Price       = 1,
                Image       = Helpers.CreateTestFormFile(ms, contentType)
            };

            var validator = new UpdateBookCommandValidator();

            // Act
            var result = await validator.ValidateAsync(new UpdateBookCommand(Guid.Empty, newBook));

            // Assert
            Assert.False(result.IsValid);
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Image.ContentType)));
        }
        public void DeleteBook(NewBookModel book)
        {
            var deleted_book = GetBooksByCondition(b => b.Title == book.Title).First();

            if (deleted_book != null)
            {
                repositoryWrapper.BookRepository.Delete(deleted_book);
            }
        }
Exemplo n.º 9
0
        public Result <NewBookModel> Add(NewBookModel model)
        {
            var newRecord = db.Books.Add(new Book
            {
                Name      = model.Name,
                PageCount = model.PageCount
            });

            db.SaveChanges();

            return(new Result <NewBookModel>(newRecord.Entity.Id));
        }
Exemplo n.º 10
0
        public IActionResult Create([FromBody] NewBookModel newBookModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(BadRequest(this.ModelState.AsResource()));
            }

            var mappedBook = this._mapper.Map <Book>(newBookModel);

            this._books.Create(mappedBook);

            return(NoContent());
        }
Exemplo n.º 11
0
        public ActionResult AddBook(NewBookModel model)
        {
            if (ModelState.IsValid)
            {
                DatabaseAccess dbAccess = new DatabaseAccess();
                dbAccess.AddBook(model.Title, model.Author, model.ISBN, model.NumberCopies);

                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public void AddBook(NewBookModel book)
        {
            Book new_book = new Book
            {
                Title   = book.Title,
                GenreId = repositoryWrapper.GenreRepository.FindByCondition(g => g.Name == book.GenreName).FirstOrDefault().Id,
            };

            var book_author = _authorService.GetAuthorByCondition(b => b.Name == book.AuthorName).FirstOrDefault().AuthorId;

            new_book.AuthorId = book_author;
            repositoryWrapper.BookRepository.Create(new_book);
        }
Exemplo n.º 13
0
        public Result <NewBookModel> Add(NewBookModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Name))
            {
                return(new Result <NewBookModel>("Book Name cannot be blank"));
            }

            if (model.PageCount < 20 || model.PageCount > 2000)
            {
                return(new Result <NewBookModel>("Book with name " + model.Name + " page count can be minimum 20 and maximum 2000"));
            }

            return(_efBook.Add(model));
        }
Exemplo n.º 14
0
        public async Task Book_New_NameNotBlankButPageCountSmaller()
        {
            var postingData = new NewBookModel {
                Name = "Lord Of The Rings", PageCount = 10
            };

            var response = await Client.PostAsync("api/Book/New", new StringContent(JsonConvert.SerializeObject(postingData), Encoding.UTF8, "application/json"));

            Assert.True(response.StatusCode == HttpStatusCode.OK);

            var result = JsonConvert.DeserializeObject <Result <NewBookModel> >(await response.Content.ReadAsStringAsync());

            Assert.True(result.IsErrorExists);
            Assert.True(result.ErrorList.Count == 1);
        }
Exemplo n.º 15
0
 public ActionResult RemoveBook(NewBookModel book)
 {
     try
     {
         _bookService.DeleteBook(book);
         _bookService.Save();
         ModelState.Clear();
         ViewData["Message"] = "1";
     }
     catch
     {
         ViewData["Message"] = "0";
     }
     return(View());
 }
Exemplo n.º 16
0
 public ActionResult EditBook(NewBookModel book)
 {
     try
     {
         _bookService.UpdateBook(book);
         _bookService.Save();
         ModelState.Clear();
         ViewData["Message"] = ViewData["Message"] + "1";
     }
     catch
     {
         ViewData["Message"] = ViewData["Message"] + "0";
     }
     return(RedirectToAction("Detail", "Book", new { book.Id }));
 }
Exemplo n.º 17
0
        public IHttpActionResult CreateBook([FromBody] NewBookModel book)
        {
            try
            {
                var newBook = new Book {
                    Title = book.TItle, Author = book.Author
                };

                var bookId = bookService.Create(newBook);

                return(Ok(bookId));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemplo n.º 18
0
        public async Task UpdateBookCommand_should_not_be_valid_if_image_is_empty()
        {
            // Arrange
            var newBook = new NewBookModel
            {
                Author      = "Correct",
                Title       = "Correct",
                Description = "Correct",
                Price       = 1,
                Image       = null
            };

            var validator = new UpdateBookCommandValidator();

            // Act
            var result = await validator.ValidateAsync(new UpdateBookCommand(Guid.Empty, newBook));

            // Assert
            Assert.False(result.IsValid);
            Assert.Contains(result.Errors, failure => failure.PropertyName.EndsWith(nameof(newBook.Image)));
        }
Exemplo n.º 19
0
        public async Task UpdateBookCommand_should_successfully_store_correct_book()
        {
            // Arrange
            var file = new byte[] { 1, 2, 3 };

            await using var ms = new MemoryStream(file);
            var contentType = "image/jpeg";

            var newBook = new NewBookModel
            {
                Author      = "Correct",
                Title       = "Correct",
                Description = "Correct",
                Price       = 1,
                Image       = Helpers.CreateTestFormFile(ms, contentType)
            };

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

            book.CoverImage = new CoverImage
            {
                Content     = file,
                ContentType = contentType
            };

            A.CallTo(() => _repository.GetById(A <Guid> .Ignored, A <bool> .Ignored)).Returns(book);
            A.CallTo(() => _repository.Update(A <Guid> .Ignored, A <Book> .Ignored, A <CoverImage> .Ignored)).Returns(book);

            // Act
            var result = await _handler.Handle(new UpdateBookCommand(Guid.Empty, newBook), default);

            // Assert
            A.CallTo(() => _repository.GetById(A <Guid> .Ignored, A <bool> .Ignored)).MustHaveHappenedOnceExactly();
            A.CallTo(() => _repository.Update(A <Guid> .Ignored, A <Book> .Ignored, A <CoverImage> .Ignored)).MustHaveHappenedOnceExactly();
            Assert.Equal(newBook.Title, result.Title);
            Assert.Equal(newBook.Author, result.Author);
            Assert.Equal(newBook.Description, result.Description);
            Assert.Equal(newBook.Price, result.Price);
            Assert.Equal($"/books/{result.Id}/image", result.ImageUrl);
        }
Exemplo n.º 20
0
        public async Task Book_New_Success()
        {
            var postingData = new NewBookModel {
                Name = "Lord Of The Rings", PageCount = 500
            };

            var response = await Client.PostAsync("api/Book/New", new StringContent(JsonConvert.SerializeObject(postingData), Encoding.UTF8, "application/json"));

            Assert.True(response.StatusCode == HttpStatusCode.OK);

            var result = JsonConvert.DeserializeObject <Result <NewBookModel> >(await response.Content.ReadAsStringAsync());

            Assert.True(!result.IsErrorExists);

            var lastRecord = db.Books.Find(result.Id);

            Assert.True(lastRecord != null);

            if (lastRecord != null)
            {
                Assert.True(lastRecord.Name == postingData.Name);
                Assert.True(lastRecord.PageCount == postingData.PageCount);
            }
        }
Exemplo n.º 21
0
        public ActionResult newBook(NewBookModel model)
        {
            var UserId = int.Parse(User.Identity.Name);


            if (ModelState.IsValid)
            {
                Book book = null;
                //using (var db = new DataBaseModel())
                //{
                //    book = db.Books.FirstOrDefault(u => u.Name == model.Name);
                //}
                //if (book == null)
                //{
                // создаем новую книгу
                using (var db = new DataBaseModel())
                {
                    db.Books.Add(new Book {
                        Name = model.Name, Autor = model.Autor, Price = model.Price, UserId = UserId
                    });
                    db.SaveChanges();
                }
                // если пользователь удачно добавлен в бд
                //if (book != null)
                //{
                return(RedirectToAction("Buy", "Home"));
                //}

                //}
                //else
                //{
                //    ModelState.AddModelError("", "Такая книга уже существует");
                //}
            }
            return(View(model));
        }
Exemplo n.º 22
0
 public UpdateBookCommand(Guid bookId, NewBookModel model)
 {
     BookId = bookId;
     Book   = model;
 }
Exemplo n.º 23
0
        public async Task <IActionResult> Create([FromForm] NewBookModel book)
        {
            var result = await _mediator.Send(new AddBookCommand(book));

            return(CreatedAtAction(nameof(Get), new { id = result.Id }, result));
        }
Exemplo n.º 24
0
        public IActionResult Create()
        {
            var model = new NewBookModel();

            return(View(model));
        }
Exemplo n.º 25
0
 public AddBookCommand(NewBookModel model)
 {
     Book = model;
 }
Exemplo n.º 26
0
 public Result <NewBookModel> New([FromBody] NewBookModel model)
 {
     return(_blBook.Add(model));
 }
Exemplo n.º 27
0
 public async Task <IActionResult> Update(Guid id, [FromForm] NewBookModel book)
 {
     return(Ok(await _mediator.Send(new UpdateBookCommand(id, book))));
 }