public ActionResult BooksCreate([DataSourceRequest]DataSourceRequest request, BookViewModel book) { if (ModelState.IsValid) { var db = new LibraryDbContext(); Book newBook = new Book() { Description = book.Description, Author = book.Author, ISBN = book.ISBN, Title = book.Title, Website = book.Website }; var category = db.Categories.FirstOrDefault(x => x.Name == book.CategoryName); category = CreateOrGetCategory(book, db, newBook, category); newBook.Id = db.Books.Add(newBook).Id; db.SaveChanges(); book.Id = newBook.Id; } return Json(new[] { book }.ToDataSourceResult(request, ModelState)); }
public JsonResult CreateBook([DataSourceRequest] DataSourceRequest request, BookViewModel book) { if (book != null && ModelState.IsValid) { int bookId = int.Parse(book.Category); var category = this.Data.Categories.FirstOrDefault(x => x.ID == bookId); var newBook = new Book { Title = book.Title, Description = book.Description, Author = book.Author, Category = category, ISBN = book.ISBN, WebSite = book.WebSite }; this.Data.Books.Add(newBook); this.Data.SaveChanges(); book.ID = newBook.ID; } return Json(new[] { book }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet); }
public SectionViewModel(Book book, BookViewModel currentBookViewModel) { this.bookViewModel = currentBookViewModel; this.CurrentBook = book; sectionContext = new SectionContext(); defineCommands(); }
public ActionResult Create() { var viewModel = new BookViewModel(); InitialazeSelectList(viewModel); return View(viewModel); }
public ViewModelLocator() { _sp = ServiceProviderBase.Instance; // 1 VM for all places that use it. Just an option Book = new BookViewModel(_sp.PageConductor, _sp.BookDataService); }
public BooksForm() { InitializeComponent(); _viewModel = new BookViewModel(new BookModel()); gvBooks.Bind(g => g.DataSource, _viewModel, v => v.BookNames); _viewModel.PropertyChanged += (sender, args) => BindDataGridView(); }
public void BookViewModelCommandsTest() { MockBookView bookView = new MockBookView(); BookViewModel bookViewModel = new BookViewModel(bookView); DelegateCommand mockCommand = new DelegateCommand(() => { }); AssertHelper.PropertyChangedEvent(bookViewModel, x => x.LendToCommand, () => bookViewModel.LendToCommand = mockCommand); Assert.AreEqual(mockCommand, bookViewModel.LendToCommand); }
public BookForm(BookViewModel viewModel) { InitializeComponent(); _viewModel = viewModel; tbName.Bind(tb => tb.Text, _viewModel, v => v.Name); errName.DataSource = _viewModel; var command = new DelegateCommand(d => AddToBookList(), c => !string.IsNullOrEmpty(_viewModel.Name)); _commandManager.Bind(command, btnAdd); }
public void BookViewModelIsValidTest() { MockBookView bookView = new MockBookView(); BookViewModel bookViewModel = new BookViewModel(bookView); Assert.IsTrue(bookViewModel.IsValid); AssertHelper.PropertyChangedEvent(bookViewModel, x => x.IsValid, () => bookViewModel.IsValid = false); Assert.IsFalse(bookViewModel.IsValid); }
public BookController(CompositionContainer container, IShellService shellService, IEntityService entityService, BookViewModel bookViewModel) { this.container = container; this.shellService = shellService; this.entityService = entityService; this.bookViewModel = bookViewModel; this.addNewCommand = new DelegateCommand(AddNewBook, CanAddNewBook); this.removeCommand = new DelegateCommand(RemoveBook, CanRemoveBook); this.lendToCommand = new DelegateCommand(p => LendTo((Book)p)); }
public BookController(IShellService shellService, IEntityService entityService, BookListViewModel bookListViewModel, BookViewModel bookViewModel, ExportFactory<LendToViewModel> lendToViewModelFactory) { this.shellService = shellService; this.entityService = entityService; this.bookListViewModel = bookListViewModel; this.bookViewModel = bookViewModel; this.lendToViewModelFactory = lendToViewModelFactory; this.addNewCommand = new DelegateCommand(AddNewBook, CanAddNewBook); this.removeCommand = new DelegateCommand(RemoveBook, CanRemoveBook); this.lendToCommand = new DelegateCommand(p => LendTo((Book)p)); }
public ActionResult show(string key) { Book b = BookProvider.GetByKey(key); IEnumerable<Page> pages = PageProvider.GetPages(b.PageIds); BookViewModel result = new BookViewModel { Book = b, Pages = pages.ToList() }; return View(result); }
public ActionResult Edit(BookViewModel viewModel) { if (ModelState.IsValid) { var dto = Mapper.Map<BookViewModel, BookDto>(viewModel); client.Update(UrlProvider.WebApiBook, dto); return RedirectToAction("Index"); } InitialazeSelectList(viewModel); return View(viewModel); }
public JsonResult KendoManage([DataSourceRequest]DataSourceRequest request, BookViewModel bookViewModel) { try { Validator.Validate(bookViewModel); } catch (InvalidFieldValueException exception) { this.ModelState.AddModelError(exception.Field, exception.ValidationMessage); return this.Json(new[] { bookViewModel }.ToDataSourceResult(request, this.ModelState)); } this.DomainModel.Manage(bookViewModel); return this.Json(new[] { bookViewModel }.ToDataSourceResult(request, this.ModelState)); }
/// <summary> /// Adds a new book to database. /// </summary> /// <param name="bookVM">Book view model.</param> /// <returns>Book identifier.</returns> public int AddBook(BookViewModel bookVM) { int bookId = 0; using (TransactionScope scope = new TransactionScope()) { Book book = Mapper.Map<Book>(bookVM); this.BookRepository.Add(book); this.BookRepository.SaveChanges(); this.BookRepository.SetAuthors(book.Id, bookVM.AuthorsIds); this.BookRepository.SaveChanges(); bookId = bookVM.Id = book.Id; scope.Complete(); } return bookId; }
public void BookViewModelBookTest() { MockBookView bookView = new MockBookView(); BookViewModel bookViewModel = new BookViewModel(bookView); Assert.IsFalse(bookViewModel.IsEnabled); Book book = new Book(); AssertHelper.PropertyChangedEvent(bookViewModel, x => x.Book, () => bookViewModel.Book = book); Assert.AreEqual(book, bookViewModel.Book); Assert.IsTrue(bookViewModel.IsEnabled); AssertHelper.PropertyChangedEvent(bookViewModel, x => x.IsEnabled, () => bookViewModel.Book = null); Assert.IsNull(bookViewModel.Book); Assert.IsFalse(bookViewModel.IsEnabled); }
private static Category CreateOrGetCategory(BookViewModel book, LibraryDbContext db, Book newBook, Category category) { if (category == null) { category = db.Categories.Add(new Category() { Name = book.CategoryName }); category.Books = new HashSet<Book>(); category.Books.Add(newBook); } else { newBook.Category = category; } return category; }
public JsonResult UpdateBook([DataSourceRequest] DataSourceRequest request, BookViewModel book) { var existingBook = this.Data.Books.FirstOrDefault(x => x.ID == book.ID); if (book != null && ModelState.IsValid) { existingBook.Title = book.Title; existingBook.Description = book.Description; existingBook.Author = book.Author; existingBook.ISBN = book.ISBN; existingBook.WebSite = book.WebSite; int bookId = int.Parse(book.Category); existingBook.Category = this.Data.Categories.FirstOrDefault(x => x.ID == bookId); this.Data.SaveChanges(); } return Json((new[] { book }.ToDataSourceResult(request, ModelState)), JsonRequestBehavior.AllowGet); }
public async Task<ActionResult> ShowBookInfo(int bookId) { BookViewModel result = null; try { Book book = await Task.Run(() => db.Book.Where(b => b.Id == bookId).Single()); result = new BookViewModel { Id = book.Id, Name = book.Name, Authors = book.AuthorToBook.Select(ab => ab.Author), Quantity = book.Quantity, History = book.Journal, isAlreadyTaken = book.Journal.Where(j => j.UserName.Name == User.Identity.Name && j.DateIn == null).Count() > 0 }; } catch (Exception ex) { return View("Error", new HandleErrorInfo(ex, RouteData.Values["controller"].ToString(), RouteData.Values["action"].ToString())); } return View("/Views/Book/BookInfo.cshtml", result); }
// GET: Books/Create public ActionResult Create() { BookViewModel book = new BookViewModel(); return(View(book)); }
private void PopPopulateLists(BookViewModel bookViewModel) { bookViewModel.Genres = bookService.GetGenres(); bookViewModel.Languages = bookService.GetLanguages(); }
public void Delete([FromBody] BookViewModel model) { _bookService.Delete(model); }
// GET: Book/Delete/5 public IActionResult Delete(int?id) { BookViewModel bookViewModel = FetchBookByID(id); return(View(bookViewModel)); }
/// <summary> /// Edits a book in database. /// </summary> /// <param name="bookVM">Book view model.</param> /// <returns>Book identifier.</returns> public int EditBook(BookViewModel bookVM) { using (TransactionScope scope = new TransactionScope()) { Book book = this.BookRepository.FindById(bookVM.Id); Mapper.Map(bookVM, book); this.BookRepository.Modify(book); this.BookRepository.SaveChanges(); book.Authors.Clear(); this.BookRepository.SetAuthors(book.Id, bookVM.AuthorsIds); this.BookRepository.SaveChanges(); scope.Complete(); } return bookVM.Id; }
/// <summary> /// Populates multi select list. /// </summary> /// <param name="bookVM">Book view model.</param> public void PopulateMultiSelectList(BookViewModel bookVM) { bookVM.AuthorsOptions = new MultiSelectList(this.AuthorRepository.GetAll().ToList().Select(author => new SelectListItem() { Text = string.Format("{0} {1}", author.FirstName, author.SecondName), Value = author.Id.ToString(), Selected = bookVM.Authors.FirstOrDefault(bookAuthor => bookAuthor.Id == author.Id) != null }), "Value", "Text").ToList(); }
public BookViewModel Edit([FromBody] BookViewModel book) { service.UpdateBook(book); return(service.GetBookViewModel(book.Id)); }
public DeleteCommand(BookViewModel bookViewModel) { BookViewModel = bookViewModel; }
private static void DeleteRecordFromStorage(BookViewModel book, DataOperationUnit dataOpUnit = null) { Debug.Assert(book != null); BookFacade.DeleteWhereIDIs(book.ID, dataOpUnit); }
public Task <BookViewModel> UpdateBook(int id, BookViewModel vm) { throw new NotImplementedException(); }
public BookWindow(BookViewModel bookViewModel) { InitializeComponent(); BookViewModel = bookViewModel; DataContext = BookViewModel; }
public TopBooksLoanedReportViewModel() { bookDetails = new BookViewModel(); }
public async Task <Book> Post([FromBody] BookViewModel viewModel) { var curr = viewModel.ToModel(); return(await MoneyWiseServices.Instance.AddBookAsync(curr)); }
public async Task <Book> Create(BookViewModel book) { var map = _mapper.Map <BookViewModel, Book>(book); return(await _bookRepository.Create(map)); }
public Task <IActionResult> SaveBook(BookViewModel vm) { throw new NotImplementedException(); }
public BookSaveCommand(BookViewModel book, BookOperation operation) { BookOperation = operation; BookOperation.Target.Name = book.Name; }
public void BookGive(BookViewModel bookVm, string session) { TimeSpan?interval; DateTime?receivingDate, givingDate; receivingDate = null; interval = null; BookOperation bkO = null; if (bookVm.PublisherName == null) { bkO = (from bo in bookDC.BookOperations where bo.UserName == session && bo.BookName == bookVm.BookName && bo.ReceivingDate != null select bo).FirstOrDefault(); } else { bkO = (from bo in bookDC.BookOperations where bo.UserName == session && bo.BookName == bookVm.BookName select bo).FirstOrDefault(); } var authr = (from a in bookDC.Authors where a.AuthorName == bookVm.AuthorName select a).FirstOrDefault(); Penalty penalty = new Penalty(); BookOperation BO = new BookOperation(); if (bkO == null) { BO.UserName = session; BO.CategoryName = bookVm.CategoryName; BO.BookName = bookVm.BookName; BO.PublisherName = bookVm.PublisherName; BO.GivingDate = DateTime.Now; if (!string.IsNullOrEmpty(bookVm.AuthorName)) { BO.AuthorName = bookVm.AuthorName; } else { BO.AuthorName = "-"; } bookDC.BookOperations.Add(BO); bookDC.SaveChanges(); penalty.BookOperationId = BO.Id; penalty.PenaltyQuantity = 0; bookDC.Penalties.Add(penalty); } else { if (bkO.ReceivingDate == null) { BO.UserName = session; BO.CategoryName = bookVm.CategoryName; BO.BookName = bookVm.BookName; BO.PublisherName = bookVm.PublisherName; BO.GivingDate = DateTime.Now; BO.ReceivingDate = null; if (!string.IsNullOrEmpty(bookVm.AuthorName)) { BO.AuthorName = bookVm.AuthorName; } else { BO.AuthorName = "-"; } bookDC.BookOperations.Add(BO); bookDC.SaveChanges(); penalty.BookOperationId = BO.Id; penalty.PenaltyQuantity = 0; bookDC.Penalties.Add(penalty); } else { receivingDate = bkO.ReceivingDate; bkO.GivingDate = DateTime.Now; givingDate = bkO.GivingDate; interval = givingDate - receivingDate; foreach (var item in bookDC.Penalties) { if (item.BookOperationId == bkO.Id) { if (interval.Value.Days <= 7) { item.PenaltyQuantity = 0; } else { item.PenaltyQuantity = (double)interval.Value.Days * 0.50; break; } } } } var bk = (from b in bookDC.Books where b.BookName == bookVm.BookName select b).FirstOrDefault(); Book book = new Book(); if (bk == null) { book.BookName = bookVm.BookName; book.CategoryId = (from item in bookDC.Categories where item.CategoryName == bookVm.CategoryName select item.CategoryId).FirstOrDefault(); book.BookQuantity = 1; bookDC.Books.Add(book); } else { bk.BookQuantity++; } Author author = new Author(); if (authr == null) { if (bookVm.AuthorName != null) { author.AuthorName = bookVm.AuthorName; bookDC.Authors.Add(author); Book_Author BA = new Book_Author(); BA.AuthorId = author.AuthorId; BA.BookId = book.BookId; bookDC.Book_Author.Add(BA); } else { if (bkO.GivingDate != null) { } else { author.AuthorName = "-"; bookDC.Authors.Add(author); Book_Author BA = new Book_Author(); BA.AuthorId = author.AuthorId; BA.BookId = book.BookId; bookDC.Book_Author.Add(BA); } } } var publishr = (from p in bookDC.Publishers where p.PublisherName == bookVm.PublisherName select p).FirstOrDefault(); Publisher publshr = new Publisher(); if (publishr == null) { if (bookVm.PublisherName != null) { publshr.PublisherName = bookVm.PublisherName; bookDC.Publishers.Add(publshr); Book_Publisher BP = new Book_Publisher(); BP.PublisherId = publshr.PublisherId; BP.BookId = book.BookId; bookDC.Book_Publisher.Add(BP); } else { if (bkO.GivingDate != null) { } else { publshr.PublisherName = "-"; bookDC.Publishers.Add(publshr); Book_Publisher BP = new Book_Publisher(); BP.PublisherId = publshr.PublisherId; BP.BookId = book.BookId; bookDC.Book_Publisher.Add(BP); } } } bookDC.SaveChanges(); } }
public BookViewModel Create([FromBody] BookViewModel book) { int id = service.CreateBook(book); return(service.GetBookViewModel(id)); }
public void Can_Show_Sorted_YearDesc_List() { //Arrange //создаем cookie и присваиваем параметру pageSize значение 2 var cookies = new HttpCookieCollection(); cookies.Add(new HttpCookie("pageSize", "2")); //Создаем HttpContext и присваиваем cookies для Request и Response var mockHttpContext = Substitute.For <HttpContextBase>(); mockHttpContext.Request.Cookies.Returns(cookies); mockHttpContext.Response.Cookies.Returns(cookies); // создаем Mock-контейнер и добавляем книги Mock <IBookContainer> mock = new Mock <IBookContainer>(); mock.Setup(m => m.Books).Returns(new List <Book> { new Book { Title = "T1", PublishYear = 1959 }, new Book { Title = "T2", PublishYear = 1971 }, new Book { Title = "T3", PublishYear = 1985 }, new Book { Title = "T4", PublishYear = 1976 }, new Book { Title = "T5", PublishYear = 1951 } }.AsQueryable()); //Создаем экземпляр контроллера BookController controller = new BookController(mock.Object); int pageSize = 4; //Эмулируем httpContext для контроллера controller.ControllerContext = new ControllerContext { Controller = controller, HttpContext = mockHttpContext }; //Act - вызываем сортировку //В качестве страницы передаем null - значение будет браться из cookie (по умолчанию равно 1, если не найдено в cookie) BookViewModel bookViewModel = (BookViewModel)controller.BooksList(null, pageSize, "Year", "Desc").Model; bookViewModel.SortBooks(); Book[] books = bookViewModel.Books.ToArray(); //Assert Assert.AreEqual(books.Count(), 4); Assert.AreEqual(books[0].Title, "T3"); Assert.AreEqual(books[1].Title, "T4"); Assert.AreEqual(books[2].Title, "T2"); Assert.AreEqual(books[3].Title, "T1"); }
public async Task <BookViewModel> ExecuteAsync(string bookCode) { var userId = 0; int.TryParse(_httpContext?.User?.UserId(), out userId); BookViewModel model = new BookViewModel(); if (userId == 0) { model = await(from book in _bookRepository.TableNoTracking.Where(x => x.BookCode == bookCode && x.Enabled.Value) join publisher in _publisherRepository.TableNoTracking on book.PublisherId equals publisher.Id into publishers from publisher in publishers.DefaultIfEmpty() join supplier in _supplierRepository.TableNoTracking on book.SupplierId equals supplier.Id into suppliers from supplier in suppliers.DefaultIfEmpty() join lib in _libraryRepository.TableNoTracking on book.LibraryId equals lib.Id into libs from lib in libs.DefaultIfEmpty() select new BookViewModel { BookId = book.Id, BookCode = book.BookCode, BookName = book.BookName, Tag = book.Tag, Description = book.Description, DateImport = book.DateImport.Value, Amount = book.Amount.Value, AmountAvailable = book.AmountAvailable.Value, Author = book.Author, Publisher = publisher != null ? publisher.Name : "Đang cập nhập", Supplier = supplier != null ? supplier.Name : "Đang cập nhập", Size = book.Size, Format = book.Format, PublicationDate = book.PublicationDate.Value, Pages = book.Pages.Value, MaximumDateBorrow = book.MaximumDateBorrow, Favorite = false, LibraryId = book.LibraryId, LibraryName = lib != null ? lib.Name : "Đang cập nhập", Enabled = book.Enabled.Value }).FirstOrDefaultAsync(); } else { model = await(from book in _bookRepository.TableNoTracking.Where(x => x.BookCode == bookCode && x.Enabled.Value) join publisher in _publisherRepository.TableNoTracking on book.PublisherId equals publisher.Id into publishers from publisher in publishers.DefaultIfEmpty() join supplier in _supplierRepository.TableNoTracking on book.SupplierId equals supplier.Id into suppliers from supplier in suppliers.DefaultIfEmpty() join favorite in _bookFavoriteRepository.TableNoTracking.Where(x => x.UserId == userId) on book.Id equals favorite.BookId into favorites from favorite in favorites.DefaultIfEmpty() join lib in _libraryRepository.TableNoTracking on book.LibraryId equals lib.Id into libs from lib in libs.DefaultIfEmpty() select new BookViewModel { BookId = book.Id, BookCode = book.BookCode, BookName = book.BookName, Tag = book.Tag, Description = book.Description, DateImport = book.DateImport.Value, Amount = book.Amount.Value, AmountAvailable = book.AmountAvailable.Value, Author = book.Author, Publisher = publisher != null ? publisher.Name : "Đang cập nhập", Supplier = supplier != null ? supplier.Name : "Đang cập nhập", Size = book.Size, Format = book.Format, PublicationDate = book.PublicationDate.Value, Pages = book.Pages.Value, MaximumDateBorrow = book.MaximumDateBorrow, Favorite = favorite != null, LibraryId = book.LibraryId, LibraryName = lib != null ? lib.Name : "Đang cập nhập", Enabled = book.Enabled.Value }).FirstOrDefaultAsync(); } return(model); }
public void add(BookViewModel book) { originalBooks.Add(book); }
public JsonResult DeleteBook([DataSourceRequest] DataSourceRequest request, BookViewModel book) { var existingBook = this.Data.Books.FirstOrDefault(x => x.ID == book.ID); this.Data.Books.Remove(existingBook); this.Data.SaveChanges(); return Json(new[] { book }, JsonRequestBehavior.AllowGet); }
public void GenerateBooks() { if (db.Books.Count() > 0) { return; } try { BookViewModel bvm = new BookViewModel() { //ID = 1, Title = "The Lord of the Rings", Author = "J. R. R. Tolkien", Genre = "fantasy", YearPublished = 1954, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 2, Title = "The Alchemist (O Alquimista)", Author = "Paulo Coelho", Genre = "fantasy", YearPublished = 1988, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 3, Title = "The Little Prince (Le Petit Prince)", Author = "Antoine de Saint-Exupéry", Genre = "fantasy", YearPublished = 1943, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 4, Title = "Grimms' Fairy Tales (Kinder- und Hausmärchen)", Author = "Jacob and Wilhelm Grimm", Genre = "folklore", YearPublished = 1812, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 5, Title = "Harry Potter and the Philosopher's Stone", Author = "J. K. Rowling", Genre = "fantasy", YearPublished = 1997, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 6, Title = "The Hobbit", Author = "J. R. R. Tolkien", Genre = "fantasy", YearPublished = 1937, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 7, Title = "And Then There Were None", Author = "Agatha Christie", Genre = "mystery", YearPublished = 1939, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); bvm = new BookViewModel() { //ID = 8, Title = "Dream of the Red Chamber (红楼梦)", Author = "Cao Xueqin", Genre = "family sage", YearPublished = 1791, Edition = "0", ISBN = "", Location = "sydney", DateCreated = DateTime.Today, DateUpdated = DateTime.Today }; db.Add(bvm); db.SaveChanges(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message.ToString()); } }
/// <summary> /// Adds or edits a book. /// </summary> /// <param name="bookVM">Book view model.</param> /// <returns>Book identifier.</returns> public int Manage(BookViewModel bookVM) { return bookVM.Id == 0 ? this.AddBook(bookVM) : this.EditBook(bookVM); }
public void Can_Show_Sorted_TitleAsc_List() { //Arrange //создаем cookie var cookies = new HttpCookieCollection(); cookies.Add(new HttpCookie("pageSize", "2")); cookies.Add(new HttpCookie("pageNum", "3")); //Создаем HttpContext и присваиваем cookies для Request и Response var mockHttpContext = Substitute.For <HttpContextBase>(); mockHttpContext.Request.Cookies.Returns(cookies); mockHttpContext.Response.Cookies.Returns(cookies); // создаем Mock-контейнер и добавляем книги Mock <IBookContainer> mock = new Mock <IBookContainer>(); mock.Setup(m => m.Books).Returns(new List <Book> { new Book { Title = "Apple", PublishYear = 1959 }, new Book { Title = "App", PublishYear = 1971 }, new Book { Title = "Wars", PublishYear = 1985 }, new Book { Title = "Soccer", PublishYear = 1976 }, new Book { Title = "Maps", PublishYear = 1951 }, new Book { Title = "Hockey", PublishYear = 1951 } }.AsQueryable()); //Создаем экземпляр контроллера BookController controller = new BookController(mock.Object); int pageNum = 1; int pagesize = 5; //Эмулируем httpContext для контроллера controller.ControllerContext = new ControllerContext { Controller = controller, HttpContext = mockHttpContext }; //Act - вызываем сортировку BookViewModel bookViewModel = (BookViewModel)controller.BooksList(pageNum, pagesize, "Title", "Asc").Model; bookViewModel.SortBooks(); Book[] books = bookViewModel.Books.ToArray(); //Assert Assert.AreEqual(books.Count(), 5); Assert.AreEqual(books[0].Title, "App"); Assert.AreEqual(books[1].Title, "Apple"); Assert.AreEqual(books[2].Title, "Hockey"); Assert.AreEqual(books[3].Title, "Maps"); Assert.AreEqual(books[4].Title, "Soccer"); }
public void Edit(BookViewModel bookViewModel) { Book book = unitOfWork.Get <int, Book>(bookViewModel.Id); mapper.Map(bookViewModel, book); book.Genre = unitOfWork.Get <int, Genre>(bookViewModel.GenreId); using (var transaction = unitOfWork.BeginTransaction()) { try { if (book.LongRowVersion != bookViewModel.LongRowVersion) { throw new Exception("DbUpdateConcurrencyException"); } var languages = unitOfWork.GetAll <int, Language>(); List <BookLanguage> bookLanguages = (List <BookLanguage>)unitOfWork.FindByCondition <int, BookLanguage>(x => x.BookId == book.Id); if (bookViewModel.LanguageIds == null) { foreach (var bookLanguage in bookLanguages) { unitOfWork.Delete <int, BookLanguage>(bookLanguage); } } else { foreach (var language in languages) { if (bookViewModel.LanguageIds.Contains(language.Id)) { if (bookLanguages.Exists(x => x.LanguageId == language.Id)) { unitOfWork.Update <int, BookLanguage>(bookLanguages.Find(x => x.LanguageId == language.Id)); } else { unitOfWork.Add <int, BookLanguage>(new BookLanguage() { BookId = book.Id, LanguageId = language.Id }); } } else { if (bookLanguages.Exists(x => x.LanguageId == language.Id)) { unitOfWork.Delete <int, BookLanguage>(bookLanguages.Find(x => x.LanguageId == language.Id)); } } } } unitOfWork.Update <int, Book>(book); unitOfWork.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw ex; } } }
public void removeBook(BookViewModel book) { originalBooks.Remove(book); }
public ActionResult Delete(BookViewModel viewMoel) { client.Delete(UrlProvider.WebApiBook + viewMoel.Id); return RedirectToAction("Index"); }
private void CheckCommand(ICommand command, BookListViewModel bookListViewModel, BookViewModel bookViewModel) { Assert.IsTrue(command.CanExecute(null)); AssertHelper.CanExecuteChangedEvent(command, () => bookListViewModel.IsValid = false); Assert.IsFalse(command.CanExecute(null)); AssertHelper.CanExecuteChangedEvent(command, () => bookListViewModel.IsValid = true); Assert.IsTrue(command.CanExecute(null)); AssertHelper.CanExecuteChangedEvent(command, () => bookViewModel.IsValid = false); Assert.IsFalse(command.CanExecute(null)); AssertHelper.CanExecuteChangedEvent(command, () => bookViewModel.IsValid = true); Assert.IsTrue(command.CanExecute(null)); }
private void InitialazeSelectList(BookViewModel viewModel) { var categoriesDto = client.Get<IEnumerable<CategoryDto>>(UrlProvider.WebApiCategory); var categoriesVieModel = Mapper.Map<IEnumerable<CategoryDto>, IEnumerable<CategoryViewModel>>(categoriesDto); viewModel.AllCategories = categoriesVieModel .Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }).ToList(); }
public JsonResult Manage(BookViewModel bookVM) { try { Validator.Validate(bookVM); } catch (InvalidFieldValueException exception) { ModelState.AddModelError(exception.Field, exception.ValidationMessage); return this.Json(new { error = exception.ValidationMessage }); } this.DomainModel.Manage(bookVM); return this.Json(new { Id = bookVM.Id, Name = bookVM.Name, PublishedDate = bookVM.PublishedDate.ToString("MM/dd/yyyy"), PagesCount = bookVM.PagesCount, Rating = bookVM.Rating, Authors = this.DomainModel.GetAuthors(bookVM.Id) }); }
// GET: BooksController public ActionResult Index() { BookViewModel model = _bookService.GetBooks(); return(View(model)); }
// GET: Books/Edit/5 public ActionResult Edit(int id) { BookViewModel bookView = (BookViewModel)BookServices.GetBook(id); return(View(bookView)); }
/// <summary> /// Adds or edits a book. /// </summary> /// <param name="bookVM">Book view model.</param> /// <returns>Book identifier.</returns> public int Manage(BookViewModel bookVM) { return this.DomainModel.Manage(bookVM); }
private static void Resetcontents(BookViewModel book, ObservableCollection <PageViewModel> bookContentPages) { List <PageViewModel> currentPageArray = new List <PageViewModel>(bookContentPages.ToArray()); book.ResetContents(currentPageArray); }
public PartialViewResult ReadOnlyBookReviewModal(BookViewModel bookViewModel) { return(PartialView("~/Views/PartialViews/ReadOnlyBookReviewModal.cshtml", bookViewModel)); }
public IActionResult Library() { BookViewModel model = _bookService.GetBooks(); return(View(model)); }
/// <summary> /// Adds or edits a book. /// </summary> /// <param name="bookVM">Book view model.</param> public void Manage(BookViewModel bookVM) { int bookId = this.DomainModel.Manage(Mapper.Map<BookWebService.BookViewModel>(bookVM)); bookVM.Id = bookId; }
public async Task <ActionResult <Book> > PostBook([FromForm] BookViewModel book) { var url = ""; var form = Request.Form; var images = form.Files; try { if (images.Count == 0) { return(BadRequest("No files received from the upload")); } if (storageConfig.AccountKey == string.Empty || storageConfig.AccountName == string.Empty) { return(BadRequest("sorry, can't retrieve your azure storage details from appsettings.js, make sure that you add azure storage details there")); } if (storageConfig.ImageContainer == string.Empty) { return(BadRequest("Please provide a name for your image container in the azure blob storage")); } foreach (var formFile in images) { if (formFile.Length > 0) { using (Stream stream = formFile.OpenReadStream()) { url = await StorageHelper.UploadFileToStorage(stream, formFile.FileName, storageConfig); } } } if (url != string.Empty) { var newBook = new Book { Title = book.Title, Author = book.Author, Synopsis = book.Synopsis, ReleaseYear = book.ReleaseYear, CoverURL = url }; _context.Book.Add(newBook); await _context.SaveChangesAsync(); return(CreatedAtAction("GetBook", new { id = book.Id }, book)); } else { return(BadRequest("Can't get image URL")); } } catch (Exception ex) { return(BadRequest(ex.Message)); } }
void Books_Loaded(object sender, RoutedEventArgs e) { bookViewModel = new BookViewModel(); this.DataContext = bookViewModel; }
public ActionResult BookEdit(BookViewModel bookViewModel) { bookViewModel.Author = _authorService.GetAuthor(bookViewModel.AuthorId); _bookService.UpdateBook(bookViewModel); return(Json(bookViewModel)); }