public bool SaveBook(AddBookViewModel model) { _bookRepository.SaveBook(model); var result = true; return(result); }
public IActionResult CreateBook() { AddBookViewModel vm = new AddBookViewModel(); vm.WritersList = _db.Writers.ToList(); return(View("AddBook", vm)); }
public ActionResult Index() { var model = new AddBookViewModel(); model.Genres = this.GetGenres(); return(this.View(model)); }
public ActionResult AddBook(AddBookViewModel model) { var name = Request["Name"]; if (ModelState.IsValid) { Book book = new Book() { Name = model.Name, Isbn = model.Isbn, Price = model.Price, CategoryId = model.CategoryId, CreatedDate = DateTime.Now, CreatedBy = HttpContext.User.Identity.Name }; BookStoreService.SaveBook(book); //TempData["message"] = "Hello from Add Book"; return(RedirectToAction("Index")); } var categoryList = BookStoreService.GetCategoryList(); model.CategoryList = new SelectList(categoryList, "Id", "Name", model.CategoryId); //ModelState.AddModelError("", "Some other error such as Book Name already exist"); return(View(model)); }
//private bool DetermineNeedAddingPublicationInPublisihngHouse(AddBookViewModel model) //{ // string[] subStrings = model.PublishingHousesIds.Split(','); // foreach (var subString in subStrings) // { // if (subString == Errors.Error.ToString()) // { // continue; // } // var checkExistPublicationInPublisihngHouse = CheckExistPublicationInPublisihngHouse(publishingHouseId); // } //} public string InsertPublication(AddBookViewModel model) { string queryString = "INSERT INTO Publications (Id, CreationDate, Name, Type)"; queryString += " VALUES (@Id, @CreationDate, @Name, @Type)"; using (SqlConnection connection = new SqlConnection(_dbconnectionString)) { SqlCommand command = new SqlCommand(queryString, connection); try { var creationDate = DateTime.Now; var id = Guid.NewGuid().ToString("N"); command.Parameters.AddWithValue("@Id", id); command.Parameters.AddWithValue("@CreationDate", creationDate); command.Parameters.AddWithValue("@Name", model.PublicationName == null ? string.Empty : model.PublicationName); command.Parameters.AddWithValue("@Type", PublicationType.Book); connection.Open(); command.ExecuteNonQuery(); return(id); } catch (Exception ex) { Console.WriteLine(ex.Message); return(string.Empty); } } }
public IActionResult CreateBook() { AddBookViewModel AddVM = new AddBookViewModel(); AddVM.WritersList = _db.Writers.ToList(); return(View("AddBook", AddVM)); }
public AddBookViewModel GetAddBookViewModel() { var authors = this.Context.Authors .Select(a => new SelectListItem() { Value = a.Id.ToString(), Text = a.FullName }) .ToList(); var categories = this.Context.Categories .Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Name }) .ToList(); AddBookViewModel viewModel = new AddBookViewModel() { Categories = categories, Authors = authors }; return(viewModel); }
public void SaveGenresToCacheWithCorrectParameters_WhenCacheIsEmptyAndModelIsNotValid() { // Arrange var genres = new List <Genre>() { new Genre() { Id = 1, Name = "GenreName1" }, new Genre() { Id = 2, Name = "GenreName2" } }; this.mockedGenresService.Setup(x => x.GetAllGenres()).Returns(genres); this.mockedCacheProvider.Setup(x => x.GetValue(Constants.GenresCache)).Returns(null); this.mockedCacheProvider.Setup(x => x.InsertWithSlidingExpiration(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <int>())) .Verifiable(); this.controller.ModelState.AddModelError("error", "message"); var submitModel = new AddBookViewModel(); // Act var result = this.controller.Index(submitModel); // Assert this.mockedCacheProvider.Verify(x => x.InsertWithSlidingExpiration(Constants.GenresCache, It.IsAny <object>(), Constants.GenresExpirationInMinutes), Times.Once); }
public void ReturnModelWithGenres_WhenBookTitleExists() { // Arrange var submitModel = new AddBookViewModel(); var mockedFile = new Mock <HttpPostedFileBase>(); mockedFile.Setup(x => x.ContentType).Returns("image/jpg"); submitModel.CoverFile = mockedFile.Object; var title = "BookTitle"; submitModel.Title = title; this.mockedBooksService.Setup(x => x.BookWithTitleExists(title)).Returns(true); var genres = new List <SelectListItem>(); this.mockedCacheProvider.Setup(x => x.GetValue(Constants.GenresCache)).Returns(genres); // Act var result = this.controller.Index(submitModel) as ViewResult; var model = result.Model as AddBookViewModel; // Assert Assert.AreEqual(genres, model.Genres); }
public string AddBook(AddBookViewModel model, string userId) { var author = model.Author; var title = model.Title; var genreId = model.GenreId; var catalogNumber = model.CatalogNumber; var message = this.IsHasNullData(model); if (string.IsNullOrEmpty(message)) { message = this.CheckDublicateBookAdd(title, author, catalogNumber, userId); if (string.IsNullOrEmpty(message)) { var user = this.context.Users.FirstOrDefault(u => u.Id == userId); var genreObj = this.context.Genres.FirstOrDefault(g => g.Id == genreId && g.DeletedOn == null); var newBook = this.CreateNewBook(model, user, userId, genreObj); this.context.Books.Add(newBook); genreObj.Books.Add(newBook); this.context.SaveChanges(); message = "Успешно добавена книга!"; this.messageService.AddNotificationAtDB(userId, message); } } return(message); }
public void ReturnGenresFromGenresService_WhenCacheIsEmptyAndModelIsNotValid() { // Arrange var genres = new List <Genre>() { new Genre() { Id = 1, Name = "GenreName1" }, new Genre() { Id = 2, Name = "GenreName2" } }; this.mockedGenresService.Setup(x => x.GetAllGenres()).Returns(genres); this.mockedCacheProvider.Setup(x => x.GetValue(Constants.GenresCache)).Returns(null); this.controller.ModelState.AddModelError("error", "message"); var submitModel = new AddBookViewModel(); // Act var result = this.controller.Index(submitModel) as ViewResult; var model = result.Model as AddBookViewModel; // Assert var modelGenres = model.Genres.ToList(); for (int i = 0; i < genres.Count; i++) { Assert.AreEqual(genres[i].Id.ToString(), modelGenres[i].Value); Assert.AreEqual(genres[i].Name, modelGenres[i].Text); } }
internal string IsHasNullData(AddBookViewModel model) { StringBuilder result = new StringBuilder(); if (string.IsNullOrEmpty(model.Title) || string.IsNullOrWhiteSpace(model.Title) || model.Title.Length < 3) { result.Append("Името на книгата трябва да съдържа поне 2 символа!"); } if (string.IsNullOrEmpty(model.Author) || string.IsNullOrWhiteSpace(model.Author) || model.Author.Length < 4) { result.Append("Името на автора трябва да съдържа поне 3 символа!"); } if (string.IsNullOrEmpty(model.CatalogNumber) || string.IsNullOrWhiteSpace(model.CatalogNumber) || model.CatalogNumber.Length < 4) { result.Append("Каталожният номер на книгата трябва да съдържа поне 3 символа!"); } if (string.IsNullOrEmpty(model.Review) || string.IsNullOrWhiteSpace(model.Review) || model.Review.Length < 11) { result.Append("Описанието на книгата трябва да съдържа поне 10 символа!"); } return(result.ToString().Trim()); }
public AddBook() { InitializeComponent(); var addbook = new AddBookViewModel(); DataContext = addbook; }
public IActionResult CreateBook(AddBookViewModel newBook) { //Use ViewModel to build the Writer and then the Book; Add to DbSets; SaveChanges Writer author; if (newBook.AuthorId > 0) { author = _db.Writers.Single(w => w.Id == newBook.AuthorId); } else { author = new Writer { Name = newBook.Name }; } Book book = new Book { Title = newBook.Title, SKU = newBook.SKU, Price = newBook.Price, Author = author }; _db.Books.Add(book); _db.SaveChanges(); //Shows the new book using the Search Listing return(RedirectToAction("Index")); }
public IActionResult EditBook(AddBookViewModel model) { this.StartUp(); var bookId = this.TempData["editBookId"].ToString(); model.BookId = bookId; var pic = model.Logo; var folder = "BooksLogo"; if (pic != null) { var fileName = Path.Combine( this.hostingEnvironment.WebRootPath + "/img/" + folder, Path.GetFileName(this.userId + "_" + pic.FileName)); pic.CopyTo(new FileStream(fileName, FileMode.Create)); model.LogoLocation = "/img/" + folder + "/" + Path.GetFileName(fileName); } var result = this.addBookService.EditBook(model, this.userId); this.ViewData["message"] = result["message"]; var returnModel = this.allAddedBooksServices.PreparedPage(this.userId); return(this.View("AddedBooks", returnModel)); }
public void CallBooksServiceAddBookWithCorrectParams_WhenModelIsValid() { // Arrange var submitModel = new AddBookViewModel(); var mockedFile = new Mock <HttpPostedFileBase>(); mockedFile.Setup(x => x.ContentType).Returns("image/jpg"); var filename = "filename.jpg"; mockedFile.Setup(x => x.FileName).Returns(filename); submitModel.CoverFile = mockedFile.Object; var mockedBookModel = new Mock <BookModel>(); this.mockedMapper.Setup(x => x.Map <BookModel>(It.IsAny <AddBookViewModel>())).Returns(mockedBookModel.Object); this.mockedBooksService.Setup(x => x.AddBook(It.IsAny <BookModel>(), It.IsAny <string>())).Verifiable(); // Act this.controller.Index(submitModel); // Assert this.mockedBooksService.Verify(x => x.AddBook(mockedBookModel.Object, filename), Times.Once); }
public async Task <IActionResult> Add() { var model = new AddBookViewModel(); var authorList = await authorService.GetAll().OrderBy(a => a.NameSurname).ToListAsync(); foreach (var author in authorList) { model.Authors.Add(new BaseSelectModel(author.AuthorID.ToString(), author.NameSurname)); } var bookTypeList = await bookTypeService.GetAll().OrderBy(a => a.TypeName).ToListAsync(); foreach (var bookType in bookTypeList) { model.BookTypes.Add(new BaseSelectModel(bookType.BookTypeID.ToString(), bookType.TypeName)); } var publisherList = await publisherService.GetAll().OrderBy(a => a.PublisherName).ToListAsync(); foreach (var publisher in publisherList) { model.Publishers.Add(new BaseSelectModel(publisher.PublisherID.ToString(), publisher.PublisherName)); } return(View(model)); }
public IActionResult AddBook(AddBookViewModel model) { if (ModelState.IsValid) { var newBook = new Book { Title = HttpUtility.HtmlEncode(model.Title), Description = HttpUtility.HtmlEncode(model.Description), QuantityAvailable = model.Quantity, Author = model.Author, Price = model.Price, Category = _context.Categories.Single(x => x.Id == model.Category) }; try { var addBook = _context.Books.Add(newBook); _context.SaveChanges(); ViewBag.Message = "Book created successfully."; model.Categories = new SelectList(_context.Categories.ToList(), "Id", "Name"); //return View(model); return(RedirectToAction("AddBook")); } catch (Exception ex) { //Refactor to display proper message ViewBag.Message = ex.Message; return(View(model)); } } return(View()); }
public IActionResult CreateBook(AddBookViewModel newBook) { //TODO: Build the Author and the Book given the newBook data. Add to DbSets; SaveChanges Writer author = new Writer(); Book book = new Book(); if (newBook.Name != null) { author.Name = newBook.Name; } else { author = _db.Writers.Single(w => w.Id == newBook.AuthorId); } book.Author = author; book.Price = newBook.Price; book.SKU = newBook.SKU; book.Title = newBook.Title; _db.Books.Add(book); _db.SaveChanges(); //Shows the new book using the Search Listing return(RedirectToAction("Index")); }
public IActionResult Add(AddBookViewModel addBookViewModel) { //extracting the bookcategory text BookCategory bookCategory = context.BookCategories.Single(b => b.ID == addBookViewModel.BookCategoryID); var user = userManager.GetUserId(HttpContext.User); if (ModelState.IsValid) { Book newBook = new Book { Title = addBookViewModel.Title, Author = addBookViewModel.Author, Description = addBookViewModel.Description, BookCategory = bookCategory, Copy = addBookViewModel.Copy, PriceOption = addBookViewModel.PriceOption, CoverPage = UploadedImge(addBookViewModel), File = UploadedFile(addBookViewModel), Price = addBookViewModel.Cost, UserId = int.Parse(userManager.GetUserId(HttpContext.User)) }; context.Books.Add(newBook); context.SaveChanges(); return(Redirect("/Book")); } return(View(addBookViewModel)); }
public ActionResult AddBook(AddBookViewModel addBookViewModel) { if (ModelState.IsValid) { var blResultBook = new BookManager().AddBook(addBookViewModel); if (blResultBook.ErrorMessageObj.Count > 0) { ErrorViewModel errorViewModel = new ErrorViewModel() { Items = blResultBook.ErrorMessageObj, RedirectingUrl = "/Book/AddBook" }; return(View("Error", errorViewModel)); } OkViewModel okViewModel = new OkViewModel() { Title = "Yeni kitap eklendi.." }; return(View("Ok", okViewModel)); } //ViewBag.Categories = new SelectList(blResultCategory.BlResultList, "Id", "Name"); return(View(addBookViewModel)); }
public async Task <ActionResult <Libros> > addBook([FromBody] AddBookViewModel libro) { try { if (libro == null) { return(BadRequest()); } var libroDb = await librosRepository.getLibroDb(libro.Nombre); if (libroDb != null) { ModelState.AddModelError("libro", "Este libro ya ha sido ingresado"); return(BadRequest(ModelState)); } Libros newLibro = new Libros() { Nombre = libro.Nombre, Descripcion = libro.Descripcion, Genero = libro.Genero, Autor = libro.Autor }; var libroAAgregar = await librosRepository.addBook(newLibro); return(CreatedAtAction(nameof(getBook), new { id = libroAAgregar.Id }, libroAAgregar)); } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError, "Error...")); } }
public AddBook() { InitializeComponent(); var addBookViewModel = new AddBookViewModel(this); BindingContext = addBookViewModel; }
public IActionResult AddBook(AddBookViewModel addBookViewModel) { if (!ModelState.IsValid) { return(View(addBookViewModel)); } else { string coverImageFileName = UploadCoverImage(addBookViewModel);; var book = new Book { Author = addBookViewModel.Author, Title = addBookViewModel.Title, Isbn = addBookViewModel.Isbn, ImageFile = coverImageFileName, Description = addBookViewModel.Description }; List <Category> categories = _dbContext.Categories.Where(x => addBookViewModel.SelectedCategories.Contains(x.CategoryId)).ToList(); _dbContext.Books.Add(book); _dbContext.SaveChanges(); foreach (var category in categories) { _dbContext.BookCategories.Add(new BookCategory { Category = category, Book = book }); } _dbContext.SaveChanges(); return(RedirectToAction("AddBook")); } }
public void InsertBook(AddBookViewModel model, string publicationId) { string queryString = "INSERT INTO Books (Id, CreationDate, Author, NumberPages, PublishingYear, Publication_Id)"; queryString += " VALUES (@Id, @CreationDate, @Author, @NumberPages, @PublishingYear, @Publication_Id)"; using (SqlConnection connection = new SqlConnection(_dbconnectionString)) { SqlCommand command = new SqlCommand(queryString, connection); try { var creationDate = DateTime.Now; var id = Guid.NewGuid().ToString("N"); command.Parameters.AddWithValue("@Id", id); command.Parameters.AddWithValue("@CreationDate", creationDate); command.Parameters.AddWithValue("@Author", model.Author == null ? string.Empty : model.Author); command.Parameters.AddWithValue("@NumberPages", model.NumberPages == null ? string.Empty : model.NumberPages); command.Parameters.AddWithValue("@PublishingYear", model.PublishingYear == null ? DateTime.Now : model.PublishingYear); command.Parameters.AddWithValue("@Publication_Id", publicationId); command.Parameters.AddWithValue("@Type", PublicationType.Book); connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public void AddBookPost(AddBookViewModel view) { var publication = InsertPublication(view); InsertBook(view, publication); InsertPublicationInPublisihngHouse(view, publication); }
public ViewResult AddBook() { AddBookViewModel vm = new AddBookViewModel(); vm.Categories = categoryService.Categories; return(View(vm)); }
public async Task <ActionResult> AddBookshelf(AddBookViewModel model) { Book book = Book.Create(model); bool isShelfInDatabase = await _unitOfWork.BookshelfRepository.IsInDatabase(User.Identity.GetUserId(), model.GoogleId); if (isShelfInDatabase) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bookshelf exist in database!")); } try { Book resultBook = await _unitOfWork.BookRepository.FindOrAddAsync(book); Shelf shelf = new Shelf(resultBook.Id, User.Identity.GetUserId()); _unitOfWork.BookshelfRepository.Add(shelf); await _unitOfWork.CompleteAsync(); } catch (Exception e) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } return(Json("Added sucessfully!")); }
public ActionResult Index([Bind(Exclude = "Genres")] AddBookViewModel bookSubmitModel) { if (!ModelState.IsValid) { bookSubmitModel.Genres = this.GetGenres(); return(this.View(bookSubmitModel)); } if (!this.IsImageFile(bookSubmitModel.CoverFile)) { this.ModelState.AddModelError("CoverFile", Constants.CoverFileErrorMessage); bookSubmitModel.Genres = this.GetGenres(); return(this.View(bookSubmitModel)); } if (this.booksService.BookWithTitleExists(bookSubmitModel.Title)) { this.ModelState.AddModelError("Title", Constants.TitleExistsErrorMessage); bookSubmitModel.Genres = this.GetGenres(); return(this.View(bookSubmitModel)); } var filename = bookSubmitModel.CoverFile.FileName; var path = this.serverProvider.MapPath(Constants.ImagesRelativePath + filename); bookSubmitModel.CoverFile.SaveAs(path); var bookModel = this.mapper.Map <BookModel>(bookSubmitModel); var bookId = this.booksService.AddBook(bookModel, filename); this.TempData.Add(Constants.AddBookSuccessKey, Constants.AddBookSuccessMessage); return(this.Redirect($"/book/{bookId}")); }
public ActionResult Create(AddBookViewModel book) { // TODO: Add correct mapping List<string> authors = new List<string>(book.Authors.Split(new[] {',', ' ', '.'}, StringSplitOptions.RemoveEmptyEntries)); List<string> genres = new List<string>(book.Genres.Split(new[] {',', ' ', '.'}, StringSplitOptions.RemoveEmptyEntries)); var bookVM = new BookViewModel { Id = Guid.NewGuid().ToString(), ISBN = Guid.NewGuid().ToString(), PublicationDate = DateTime.Today.ToLongTimeString(), Authors = authors, Genres = genres, Name = book.Name, Description = book.Id, }; var bookDto = Mapper.Map<BookDto>(bookVM); bookService.AddBook(bookDto); return RedirectToAction("Recents"); }