public IActionResult Index() { var model = new NewBookViewModel(); { model.Categories.Add(new SelectListItem { Text = "Barn", Value = "1" }); model.Categories.Add(new SelectListItem { Text = "Deckare", Value = "2" }); model.Categories.Add(new SelectListItem { Text = "Roman", Value = "3" }); model.Categories.Add(new SelectListItem { Text = "Fakta", Value = "4" }); model.Stock.Add(new InStock(1, "I lager")); model.Stock.Add(new InStock(2, "Ej i lager")); } return(View(model)); }
public HttpResponseMessage AddNewBookToLibrary(NewBookViewModel model) { if (!ModelState.IsValid) { var cnt = model.Authors != null?model.Authors.Count() : -1; var error = String.Join("\t", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToArray()); _logger.Debug($"BookController/AddNewBookToLibrary Model errors = {error}"); return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } string loggedInUserId = RequestContext.Principal.Identity.GetUserId(); try { var webClient = new WebClient(); byte[] imageBytes = webClient.DownloadData(model.CoverUrl); _bookService.AddNewBookToLibrary(loggedInUserId, new BookDTO() { Title = model.Title, Year = model.Year, Publisher = model.Publisher, Cover = imageBytes }, model.Authors); return(new HttpResponseMessage(HttpStatusCode.OK)); }catch (Exception e) { _logger.Error($"BooksController/AddNewBookToLibrary Message={e.Message}"); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, new { Message = e.Message }); return(response); } }
public async Task <IActionResult> UpdateBook([FromBody] NewBookViewModel book) { if (ModelState.IsValid) { try { var newBook = Mapper.Map <Book>(book); await _bookService.UpdateBookAsync(newBook); return(Ok("Book successfully updated")); } catch (MemberRelationException e) { return(StatusCode(400, e.Message + " " + e.Column)); } catch (Exception e) { return(StatusCode(500, "Server error. Try to reload page.")); } } else { return(StatusCode(400, "Invalid data format.")); } }
public ActionResult NewBookSearch(Guid clubId) { NewBookViewModel viewModel = new NewBookViewModel { ClubId = clubId }; return(View(viewModel)); }
public NewBook() { InitializeComponent(); _NewBookViewModel = new NewBookViewModel(); DataContext = _NewBookViewModel; _NewBookViewModel.Window = GetWindow(this); Closing += _NewBookViewModel.OnWindowClosing; }
public ActionResult NewBook() { BooksManager manager = new BooksManager(Properties.Settings.Default.ConStr); NewBookViewModel viewModel = new NewBookViewModel(); viewModel.Categories = manager.GetCategories(); return(View(viewModel)); }
public IHttpActionResult Create([FromBody] NewBookViewModel itemViewModel) { var item = Mapper.Map <Book>(itemViewModel); bookBL.CreateBook(item, itemViewModel.authorID, itemViewModel.isbnID, itemViewModel.readerIDs.ToList()); return(Ok()); }
public IActionResult CreatedBook(NewBookViewModel values) { if (ModelState.IsValid) { return(View(values)); } return(View()); }
public ActionResult NewBookDetails(string id, Guid clubId) { NewBookViewModel viewModel = new NewBookViewModel(); viewModel.GoogleVolumeId = id; viewModel.ClubId = clubId; viewModel.Book = Utilities.GoogleBookSearchUtilities.ParseSingleSearchResponse(GoogleBooksAPIHandler.SingleSearch(viewModel.GoogleVolumeId).Result); viewModel.Reviews = db.Reviews.Include("Member").Where(r => r.BookId == viewModel.Book.Id).ToList(); return(View(viewModel)); }
public JsonResult Create(NewBookViewModel model) { if (ModelState.IsValid) { Author author; try { author = dbContext.authors.Single(a => a.id == model.authorId); if (author == null) { ModelState.AddModelError("Author", "ID de Autor Inválido!"); } else { Book book = new Book { author = author, name = model.name }; dbContext.books.Add(book); BookCopyCategory bcce = dbContext.bookCopyCategories.Single(z => z.id == GlobalValues.BookCopyCategory.EXTERNAL); BookCopyCategory bcci = dbContext.bookCopyCategories.Single(z => z.id == GlobalValues.BookCopyCategory.INTERNAL); BookCopyStatus bcs = dbContext.bookCopyStatuses.Single(z => z.id == GlobalValues.BookCopyStatus.AVAILABLE); BookCopy bci = new BookCopy { book = book, category = bcci, status = bcs, enterDate = DateTime.Now }; BookCopy bce = new BookCopy { book = book, category = bcce, status = bcs, enterDate = DateTime.Now }; dbContext.bookCopies.Add(bci); dbContext.bookCopies.Add(bce); dbContext.SaveChanges(); return(Json(new { status = "OK", info = "Operación exitosa!" })); } } catch (Exception ex) { ModelState.AddModelError("Author", ex.Message); } } List <string> messages = new List <string>(); foreach (var ms in ModelState.Values) { foreach (var me in ms.Errors) { messages.Add(me.ErrorMessage); } } return(Json(new { status = "ERROR", info = messages })); }
public ActionResult NewBookSearchResults(NewBookSearchViewModel input) { GoogleBooksSearchResponse response = GoogleBooksAPIHandler.FullSearch(new Models.MiscModels.Search { inauthor = input.InAuthor, intitle = input.InTitle, isbn = input.ISBN, other = input.Other, subject = input.Subject }); NewBookViewModel viewModel = new NewBookViewModel { Books = Utilities.GoogleBookSearchUtilities.ParseSearchResponse(response), ClubId = input.ClubId }; return(View(viewModel)); }
public void AddAuthorBook(NewBookViewModel model) { var author = GetAuthorById(model.AuthorId); author.AuthorBooks.Add( new Book { Title = model.Title } ); _db.Authors.Update(author); _db.SaveChanges(); }
public ActionResult ChooseNewBook(NewBookViewModel viewModel) { var userId = User.Identity.GetUserId(); if (userId == null) { return(RedirectToAction("Login", "Account")); } return(RedirectToAction("Create", "Discussion", new NewDiscussionInputViewModel { ClubId = viewModel.ClubId, GoogleVolumeId = viewModel.GoogleVolumeId })); }
public void Book_AddBook_Should_Return_Invalid_Model_State() { var book = new NewBookViewModel { Isbn = "1" }; _bookController.ModelState.AddModelError("test", "error"); var response = _bookController.AddBook(book); Assert.IsInstanceOf <InvalidModelStateResult>(response); }
public ActionResult New() { //this is a disposable form var genre = _context.Genre.ToList(); //listing genre for the form var viewModel = new NewBookViewModel() { Book = new Book(), //without this new book doesnot form from controller Genre = genre }; return(View("NewBookForm", viewModel)); }
public ActionResult Books() { NewBookViewModel model = new NewBookViewModel(); var categories = db.Categories.Select(c => new { Id = c.Id, Name = c.Name }).ToList(); var publishers = db.Publishers.Select(c => new { Id = c.Id, Name = c.Name }).ToList(); var authours = db.Authours.Select(c => new { Id = c.Id, Name = string.Concat(c.FirstName, " ", c.LastName) }).ToList(); model.Category = new SelectList(categories, "Id", "Name"); model.Categories = new MultiSelectList(categories, "Id", "Name"); model.Authors = new MultiSelectList(authours, "Id", "Name"); model.Publisher = new SelectList(publishers, "Id", "Name"); return(View(model)); }
public ActionResult New(NewBookViewModel model) { if (ModelState.IsValid) { if (model.Save(_bookRepository)) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } } return(View(model)); }
public async Task <ActionResult> Create(NewBookViewModel model) { if (ModelState.IsValid && model.File != null) { Book book = new Book(); book.Title = model.Title; book.Age = model.Age; book.Descriptions = model.Descriptions; book.CategoryId = model.CategoryId; book.Authors = db.Authours.Where(a => model.AuthorsId.Contains(a.Id)).ToList(); book.Categories = db.Categories.Where(c => model.CategoriesId.Contains(c.Id)).ToList(); book.PublisherId = model.PublisherId; book.Print = model.Print; book.PrintDate = model.PrintDate; book.FileName = model.File.FileName; book.CoverImageName = model.CoverImage?.FileName ?? ""; book.CreateDate = DateTime.Now; book.LastUpdate = DateTime.Now; db.Books.Add(book); await db.SaveChangesAsync(); if (model.File.ContentLength > 0) { model.File.SaveAs(Path.Combine(Server.MapPath("~/Resources/BooksFiles"), Path.GetFileName(model.File.FileName))); } if (model.CoverImage?.ContentLength > 0) { string path = Path.Combine(Server.MapPath("~/Resources/BooksCoverImage"), Path.GetFileName(model.CoverImage.FileName)); OptimizeImages.SetCompressionLevel(new Bitmap(model.CoverImage.InputStream), path); } return(RedirectToAction("Index")); } var categories = db.Categories.Select(c => new { Id = c.Id, Name = c.Name }).ToList(); var publishers = db.Publishers.Select(c => new { Id = c.Id, Name = c.Name }).ToList(); var authours = db.Authours.Select(c => new { Id = c.Id, Name = c.FirstName }).ToList(); model.Category = new SelectList(categories, "Id", "Name", model.CategoryId); model.Categories = new MultiSelectList(categories, "Id", "Name", model.CategoriesId); model.Authors = new MultiSelectList(authours, "Id", "Name", model.AuthorsId); model.Publisher = new SelectList(publishers, "Id", "Name", model.PublisherId); return(View(model)); }
//f5 debugger ..shift+f5 -->stop debugger public ActionResult Edit(int id) //this displays edit form { var book = _context.Books.SingleOrDefault(c => c.ID == id); if (book == null) { return(HttpNotFound()); } var viewModel = new NewBookViewModel { Book = book, Genre = _context.Genre.ToList() }; return(View("NewBookForm", viewModel)); //return form with data from viewmodel }
public IActionResult NewBook(NewBookViewModel model) { if (!ModelState.IsValid) { ViewBag.AuthError = "ivyko klaida"; return(RedirectToAction("Index", "Auth")); } Book myNewBook = new Book { Title = model.Title, Author = _authorService.GetAuthorById(model.AuthorId) }; _bookService.CreateBook(myNewBook); return(RedirectToAction("Index")); }
public async Task <IActionResult> Add(NewBookViewModel model) { //https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.0 if (!ModelState.IsValid) { return(BadRequest()); } //Book class is an entity in Data project, here we map the ViewModel to the Book entity //for saving into db using EF Core var newBook = new Book { Id = Guid.NewGuid(), Title = model.Title, Author = model.Author, Genre = model.Genre, Price = model.Price }; //here we are pulling the file that was uploaded with the ViewModel book data //the file is part of the ViewModel and needs to be added to a new MemoryStream //we use the MemoryStream by sending it to the _storage service for saving to Azure Storage using (var memoryStream = new MemoryStream()) { await model.CoverPictureImage.CopyToAsync(memoryStream); var picLocation = await _storage.UploadFileStreamAsync( memoryStream, //image data "CoverPhotos".ToLower(), //name of container in Azure Storage to put image file $"{newBook.Id.ToString()}{Path.GetExtension(model.CoverPictureImage.FileName)}"); //name of image file to store in defined container. this will match Book.Id for easy correlation //make sure to save the URI location of the image in Azure Storage to the Book Entity newBook.CoverPicture = picLocation; } //save the book to the database using EF Core await _context.Books.AddAsync(newBook); await _context.SaveChangesAsync(); //when done, just redirect to Index action return(RedirectToAction("Index")); }
public IHttpActionResult AddBook(NewBookViewModel book) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var bookDto = _mapper.Map <NewBookViewModel, NewBookDTO>(book); SetOrganizationAndUser(bookDto); try { _bookService.AddBook(bookDto); return(Ok()); } catch (BookException e) { return(BadRequest(e.Message)); } }
public IActionResult NewBook(Book book, IFormFile imageFile) { if (imageFile != null) { using (var stream = new MemoryStream()) { imageFile.CopyTo(stream); book.ImageBytes = stream.ToArray(); } } else { book.ImageBytes = InventoryManager.GetItemImage(book.LibraryID); } book.LibraryID = InventoryManager.GetNewLibraryID(); CoreLibrary.Inventory.InventoryManager.AddNewBook(book); NewBookViewModel viewModel = new NewBookViewModel(); viewModel.Book = SearchUtility.GetBookByLibraryID(book.LibraryID); return(View("NewBookResult", viewModel)); }
public ActionResult Save(Book book) //save and update { if (!ModelState.IsValid) { var viewModel = new NewBookViewModel() { Book = book, Genre = _context.Genre.ToList() }; return(View("NewBookForm", viewModel)); } if (book.ID == 0) { _context.Books.Add(book); } else { var BookInDb = _context.Books.Single(c => c.ID == book.ID); BookInDb.Name = book.Name; BookInDb.DateAdded = book.DateAdded; BookInDb.GenreId = book.GenreId; BookInDb.NumberInStock = book.NumberInStock; } //try //{ //required entity can be set here too for no exception to occur _context.SaveChanges(); //} //catch (DbEntityValidationException e) //{ // Console.WriteLine(e); //break point f9 //} return(RedirectToAction("Index", "Books")); }
public ActionResult NewPost() { var allCategories = this.categoryService.GetAllCategories(); var states = this.GetSelectListItems(allCategories); var postVm = (NewPostViewModel)this.TempData["reSubmit"]; if (postVm == null) { var bookVm = new NewBookViewModel() { PublishedOn = DateTime.Now }; postVm = new NewPostViewModel() { Book = bookVm }; } postVm.Book.Categories = states; return(this.View(postVm)); }
public void Book_AddBook_Should_Return_Ok() { IEnumerable <NewBookQuantityViewModel> quantities = new List <NewBookQuantityViewModel> { new NewBookQuantityViewModel { BookQuantity = 1, OfficeId = 1 } }; var book = new NewBookViewModel { Isbn = "1", Title = "Testiness", Author = "Me the Great", QuantityByOffice = quantities }; var response = _bookController.AddBook(book); Assert.IsInstanceOf <OkResult>(response); }
public ActionResult New() { NewBookViewModel model = new NewBookViewModel(_bookRepository); return(View(model)); }
public NewBookPage() { InitializeComponent(); BindingContext = newBookViewModel = new NewBookViewModel(); }
public ActionResult NewBookSearch(NewBookViewModel viewModel) { return(RedirectToAction("NewBookSearchResults", new NewBookSearchViewModel { ClubId = viewModel.ClubId, InAuthor = viewModel.Search.inauthor, InTitle = viewModel.Search.intitle, ISBN = viewModel.Search.isbn, Other = viewModel.Search.other, Subject = viewModel.Search.subject })); }