public async Task <IActionResult> AddBookInCart(Guid id) { BookInLibrary bookInLibrary = await _context.BooksInLibraries .Include(bl => bl.Library) .FirstOrDefaultAsync(b => b.Id == id); User user = await _context.Users.FirstOrDefaultAsync(u => u.Login == User.Identity.Name); List <Cart> carts = await _context.Carts .Include(c => c.User) .Include(c => c.BookInLibrary) .ThenInclude(bl => bl.Library) .Where(c => c.User == user) .ToListAsync(); if (bookInLibrary != null && user != null && bookInLibrary.CurrentQuantity > 0) { if (carts == null || carts.Count == 0 || carts[0].BookInLibrary.Library == bookInLibrary.Library) { _context.Carts.Add(new Cart { User = user, BookInLibrary = bookInLibrary }); bookInLibrary.CurrentQuantity--; _context.BooksInLibraries.Update(bookInLibrary); await _context.SaveChangesAsync(); } } return(RedirectToAction("Index", "Home")); }
public ActionResult Rent(int?id, BookInLibraryViewModel model) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); if (bookInLibrary == null || user == null || !IsFriendOrOwner(bookInLibrary, user)) { return(HttpNotFound()); } var rental = new Rental { BookInLibraryId = bookInLibrary.Id, StartOfRental = DateTime.Now, UserId = model.UserId }; db.Rentals.Add(rental); db.SaveChanges(); return(RedirectToAction("More", new { id })); }
private Boolean IsFriendOrOwner(BookInLibrary bookInLibrary, ApplicationUser user) { Boolean isOwner = bookInLibrary.Library.ApplicationUser.Id == user.Id; Boolean isFriend = db.Friendships.Any(f => (f.LibraryId == bookInLibrary.LibraryId && f.ApplicationUserId == user.Id)); return(isOwner || isFriend); }
public ActionResult AddComment(int?id, BookInLibraryViewModel model) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); if (bookInLibrary == null || user == null || !IsFriendOrOwner(bookInLibrary, user)) { return(HttpNotFound()); } var comment = new Comment { Text = model.Comment, BookInLibraryId = bookInLibrary.Id, UserId = user.Id }; db.Comments.Add(comment); db.SaveChanges(); return(RedirectToAction("More", new { id })); }
// GET: BookInLibraries/StartReading/3 // id is the id of a BookInLibrary public ActionResult StartReading(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); if (bookInLibrary == null || user == null || !CanRead(bookInLibrary, user)) { return(HttpNotFound()); } var reading = new Reading { BookInLibrary = bookInLibrary, StartOfReading = DateTime.Now, User = user }; db.Readings.Add(reading); db.SaveChanges(); return(RedirectToAction("More", new { id })); }
public async Task <IActionResult> AddBookInLibrary(AddBookInLibraryViewModel model) { if (ModelState.IsValid) { BookInLibrary book = await _context.BooksInLibraries .Include(b => b.Library) .Include(b => b.Book) .FirstOrDefaultAsync(b => b.Book.Id == model.BookId && b.Library.Id == model.LibraryId); if (book == null) { Library library = await _context.Libraries.FirstOrDefaultAsync(l => l.Id == model.LibraryId); _context.BooksInLibraries.Add(new BookInLibrary { Library = library, Book = await _context.Books.FirstOrDefaultAsync(b => b.Id == model.BookId), TotalQuantity = model.TotalQuantity, CurrentQuantity = model.TotalQuantity }); await _context.SaveChangesAsync(); return(RedirectToAction("Info", library.Id)); } ModelState.AddModelError("", "Вы пытаетесь добавить книгу, которая уже есть в данной библиотеки"); } ViewBag.Books = new SelectList(await _context.Books.ToListAsync(), "Id", "Name"); return(View(model)); }
// GET: BookInLibraries/DeleteBookFromLibrary/3 // id is the id of a BookInLibrary public ActionResult DeleteBookFromLibrary(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); if (bookInLibrary == null || user == null) { return(HttpNotFound()); } if (IsFriendOrOwner(bookInLibrary, user))// deletes only if user has permissions { db.BooksInLibrary.Remove(bookInLibrary); db.SaveChanges(); } else { ViewBag.Title = "Błąd"; ViewBag.Message = "Nie masz uprawnień, żeby usunąć książkę z tej biblioteki."; return(View("Info")); } return(RedirectToAction("Index", "Libraries", new { id = bookInLibrary.LibraryId })); }
public ActionResult DeleteConfirmed(int id) { BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); db.BooksInLibrary.Remove(bookInLibrary); db.SaveChanges(); return(RedirectToAction("Index")); }
// GET: BookInLibraries/MoreAboutRent/3 // id is the id of a BookInLibrary public ActionResult MoreAboutRent(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); var lastRental = db.Rentals.Where(r => r.BookInLibraryId == bookInLibrary.Id && r.EndOfRental == null).FirstOrDefault(); if (bookInLibrary == null || user == null || lastRental == null || !CanGiveBack(lastRental, user)) { return(HttpNotFound()); } // should be only one or null var lastReading = db.Readings.Where(r => r.BookInLibraryId == bookInLibrary.Id && r.EndOfReading == null).FirstOrDefault(); Boolean isCurrentlyReadByMe = false; Boolean isCurrentlyReadBySbElse = false; String otherReaderName = ""; if (lastReading != null) { if (lastReading.UserId == user.Id) { isCurrentlyReadByMe = true; } else { isCurrentlyReadBySbElse = true; otherReaderName = lastReading.User.UserName; } } var isLent = false; var borrowerName = ""; // borrower is the owner of a librry // should be only one or null if (lastRental != null) { isLent = true; borrowerName = lastRental.User.UserName; } var bookInLibraryViewModel = new BookInLibraryViewModel { BookInLibrary = bookInLibrary, IsCurrentlyReadByMe = isCurrentlyReadByMe, IsCurrentlyReadBySbElse = isCurrentlyReadBySbElse, OtherReaderName = otherReaderName, IsLent = isLent, BorrowerName = borrowerName, }; return(View(bookInLibraryViewModel)); }
// checks if user can start/end reading a book private Boolean CanRead(BookInLibrary bookInLibrary, ApplicationUser user) { Boolean canRead = IsFriendOrOwner(bookInLibrary, user); Rental rental = db.Rentals.Where(r => (r.BookInLibraryId == bookInLibrary.Id && r.UserId == user.Id && r.EndOfRental == null)).FirstOrDefault(); if (rental != null) { canRead = canRead || CanGiveBack(rental, user); } return(canRead); }
public ActionResult Edit([Bind(Include = "Id,BookId,LibraryId")] BookInLibrary bookInLibrary) { if (ModelState.IsValid) { db.Entry(bookInLibrary).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.BookId = new SelectList(db.Books, "Id", "Title", bookInLibrary.BookId); ViewBag.LibraryId = new SelectList(db.Libraries, "Id", "Id", bookInLibrary.LibraryId); return(View(bookInLibrary)); }
public ActionResult Create([Bind(Include = "Id,BookId,LibraryId")] BookInLibrary bookInLibrary) { if (ModelState.IsValid) { db.BooksInLibrary.Add(bookInLibrary); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.BookId = new SelectList(db.Books, "Id", "Title", bookInLibrary.BookId); ViewBag.LibraryId = new SelectList(db.Libraries, "Id", "Id", bookInLibrary.LibraryId); return(View(bookInLibrary)); }
// GET: BookInLibraries/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); if (bookInLibrary == null) { return(HttpNotFound()); } return(View(bookInLibrary)); }
// TODO usun // GET: BookInLibraries/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); if (bookInLibrary == null) { return(HttpNotFound()); } ViewBag.BookId = new SelectList(db.Books, "Id", "Title", bookInLibrary.BookId); ViewBag.LibraryId = new SelectList(db.Libraries, "Id", "Id", bookInLibrary.LibraryId); return(View(bookInLibrary)); }
public ActionResult AddBookToLibrary(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Book book = db.Books.Find(id); if (book == null) { return(HttpNotFound()); } var user = UserManager.FindById(User.Identity.GetUserId()); if (user == null) { return(HttpNotFound()); } int libraryId = 0; Int32.TryParse(Request.Form["libraryId"], out libraryId); var library = db.Libraries.Find(libraryId); Boolean canAdd = (user.Library.Id == library.Id) || db.Friendships.Any(f => (f.LibraryId == library.Id && f.ApplicationUserId == user.Id)); if (canAdd) { var bookInLibrary = new BookInLibrary { Book = book, Library = library }; db.BooksInLibrary.Add(bookInLibrary); db.SaveChanges(); return(RedirectToAction("Index", "Books")); } else { ViewBag.Title = "Błąd"; ViewBag.Message = "Nie masz uprawnień, żeby dodawać książki do tej biblioteki."; return(View("Info")); } }
public async Task <IActionResult> RemoveBookInCart(Guid id) { Cart bookInCart = await _context.Carts .Include(c => c.User) .Include(c => c.BookInLibrary) .FirstOrDefaultAsync(c => c.Id == id); User user = await _context.Users.FirstOrDefaultAsync(u => u.Login == User.Identity.Name); if (bookInCart != null && user != null && bookInCart.User == user) { BookInLibrary bookInLibrary = await _context.BooksInLibraries.FirstOrDefaultAsync(b => b == bookInCart.BookInLibrary); bookInLibrary.CurrentQuantity++; _context.BooksInLibraries.Update(bookInLibrary); _context.Carts.Remove(bookInCart); await _context.SaveChangesAsync(); } return(RedirectToAction("Index")); }
// GET: BookInLibraries/GiveBackConfirm/3 public ActionResult GiveBackConfirm(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); var rental = db.Rentals.Where(r => r.BookInLibraryId == bookInLibrary.Id && r.EndOfRental == null).FirstOrDefault(); if (bookInLibrary == null || user == null || rental == null || !IsFriendOrOwner(bookInLibrary, user)) { return(HttpNotFound()); } rental.EndOfRental = DateTime.Now; db.Entry(rental).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("More", new { id })); }
// GET: BookInLibraries/DeleteReading/3 // id is the id of a reading // deletes only if book is in a library of logged user public ActionResult DeleteReading(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Reading reading = db.Readings.Find(id); BookInLibrary bookInLibrary = reading.BookInLibrary; var user = UserManager.FindById(User.Identity.GetUserId()); if (reading == null || user == null) { return(HttpNotFound()); } if (IsFriendOrOwner(bookInLibrary, user))// deletes only if user has permissions { db.Readings.Remove(reading); db.SaveChanges(); } return(RedirectToAction("More", new { bookInLibrary.Id })); }
// GET: BookInLibraries/More/3 // id is the id of a BookInLibrary public ActionResult More(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BookInLibrary bookInLibrary = db.BooksInLibrary.Find(id); var user = UserManager.FindById(User.Identity.GetUserId()); if (bookInLibrary == null || user == null) { return(HttpNotFound()); } // check if logged user has permissions to access this book Boolean isFriendOrOwner = IsFriendOrOwner(bookInLibrary, user); Boolean isRent = db.Rentals.Any(r => (r.BookInLibraryId == bookInLibrary.Id && r.UserId == user.Id && r.EndOfRental == null)); if (isRent) { return(RedirectToAction("MoreAboutRent", new { bookInLibrary.Id })); } else if (!isFriendOrOwner) { // error ViewBag.Title = "Brak uprawnień"; ViewBag.Message = "Nie jesteś właścicielem ani członkiem bibilioteki, w której jest podana książka."; return(View("Info")); } // should be only one or null var lastReading = db.Readings.Where(r => r.BookInLibraryId == bookInLibrary.Id && r.EndOfReading == null).FirstOrDefault(); Boolean isCurrentlyReadByMe = false; Boolean isCurrentlyReadBySbElse = false; String otherReaderName = ""; if (lastReading != null) { if (lastReading.UserId == user.Id) { isCurrentlyReadByMe = true; } else { isCurrentlyReadBySbElse = true; otherReaderName = lastReading.User.UserName; } } var isLent = false; var borrowerName = ""; // should be only one or null var lastRental = db.Rentals.Where(r => r.BookInLibraryId == bookInLibrary.Id && r.EndOfRental == null).FirstOrDefault(); if (lastRental != null) { isLent = true; borrowerName = lastRental.User.UserName; } var isLentOutside = db.RentalsToOutside.Any(r => r.BookInLibraryId == bookInLibrary.Id && r.EndOfRental == null); var bookInLibraryViewModel = new BookInLibraryViewModel { BookInLibrary = bookInLibrary, IsCurrentlyReadByMe = isCurrentlyReadByMe, IsCurrentlyReadBySbElse = isCurrentlyReadBySbElse, OtherReaderName = otherReaderName, IsLent = isLent, BorrowerName = borrowerName, isLentOutside = isLentOutside, Users = new SelectList(db.Users.Where(u => u.Id != bookInLibrary.Library.ApplicationUser.Id), "Id", "UserName") }; return(View(bookInLibraryViewModel)); }
public static void DoItSingleQuery() { using (var ctx = new EFExamplesContext()) { var visitor = new Visitor() { Name = "Oleg", IssuedBooks = new List <IssuedBook>(), }; // посетитель смотрит какие книги есть в наличии в библиотеке var booksQuery = ctx.Libraries // только в библиотеке Big Library .Where(x => x.Name == "Big library") // выбираем смотрим на все реки и из каждого выбираем группу обьектов .SelectMany(x => x.Racks.SelectMany(rack => // явно указываем поля, которые хотим выбрать rack.Books.Select(book => new { book.Id, book.BookId, book.IssueDate, book.Rack, book.PlacedInRackDate }))); // запрос на получение книг в библиотеке в связке с книгами var query2 = ctx.Books.Join(booksQuery, book => book.Id, bookInLibrary => bookInLibrary.BookId, (book, bookInLibrary) => new { book, bookInLibrary }) .Where(x => x.bookInLibrary.IssueDate == null); var presentBooks = query2.ToList(); // где то здесь посетитель решает что ему надо и выбирает первую книгу (для простоты) var bookOfIntereset = presentBooks.First(); visitor.IssuedBooks.Add(new IssuedBook() { BookId = bookOfIntereset.book.Id, IssueDate = DateTime.Now, LibraryId = ctx.Libraries.Where(x => x.Name == "Big library").SingleOrDefault().Id, }); // сохраняем изменения потому что айди посетителя автогенерируется базой ctx.SaveChanges(); // этот обьект создан вручную и НЕ трекается ChangeTracker'om ентити фреймворка var bookInLibraryToModify = new BookInLibrary() { Id = bookOfIntereset.bookInLibrary.Id, BookId = bookOfIntereset.bookInLibrary.BookId, IssueDate = DateTime.Now, IssuedToVisitorId = visitor.Id, Rack = bookOfIntereset.bookInLibrary.Rack, PlacedInRackDate = bookOfIntereset.bookInLibrary.PlacedInRackDate, }; // проверяем: var state = ctx.Entry(bookInLibraryToModify).State; ctx.BooksInLibrary.Attach(bookInLibraryToModify); // проверяем после аттача: state = ctx.Entry(bookInLibraryToModify).State; ctx.Entry(bookInLibraryToModify).State = System.Data.Entity.EntityState.Modified; ctx.SaveChanges(); } }