public void Books_LendBookToUser_SuccessfulLoan()
        {
            // Arrange
            var repo   = new BooksRepository(context);
            int userId = (context.Users.OrderByDescending(u => u.Id).FirstOrDefault()).Id;
            var book   = new Book {
                Title       = "New Book",
                Author      = "Some Guy",
                ReleaseDate = DateTime.Now,
                ISBN        = "5318343518342168435",
                Available   = true,
                Deleted     = false
            };

            context.Books.Add(book);
            context.SaveChanges();

            // Act
            repo.LendBookToUser(userId, book.Id);

            // Assert
            Assert.AreEqual(2, context.Loans.Count());
            Assert.AreEqual(userId, context.Loans.OrderByDescending(l => l.Id).FirstOrDefault().UserId);
            Assert.AreEqual(book.Id, context.Loans.OrderByDescending(l => l.Id).FirstOrDefault().BookId);
        }
Esempio n. 2
0
 public UserMain(UserInfo activeUser)
 {
     try
     {
         //Properties init
         ActiveUser     = activeUser;
         ActiveControls = new Dictionary <Type, UserControl>();
         //Data initialization
         //TODO Add All repos
         BooksRepo = new BooksRepository();
         //XAML components init
         InitializeComponent();
         //Creating custom controls
         ActiveControls.Add(typeof(BooksGrid), new BooksGrid(BooksRepo.BooksViewPoint));
         ActiveControls.Add(typeof(BookContentEditor), new BookContentEditor());
         ActiveControls.Add(typeof(BooksContentFilter), new BooksContentFilter(BooksRepo.BooksViewPoint));
         //Set Books tab as active
         CurrentContentTab = Enums.ContentTab.Books;
         //
         DataViewHolder_Grid.Children.Add(ActiveControls.GetValueOrDefault(typeof(BooksGrid)));
         //set books filter as active
         ContentFilter_Grid.Children.Add(ActiveControls.GetValueOrDefault(typeof(BooksContentFilter)));
         //set books editor as active
         ContentEditor_Grid.Children.Add(new BookContentEditor());
     }
     catch (Exception ex)
     {
         ExceptionLogger.Log(ex);
     }
 }
Esempio n. 3
0
 public DataAccess()
 {
     _context           = new LibraryContext();
     _usersRepository   = new UsersRepository(_context);
     _booksRepository   = new BooksRepository(_context);
     _authorsRepository = new AuthorsRepository(_context);
 }
Esempio n. 4
0
        // PUT: api/Books/5
        public Book Put(int id, [FromBody] Book book)
        {
            BooksRepository booksRepo = new BooksRepository();

            book.Id = id;
            return(booksRepo.Update(book));
        }
Esempio n. 5
0
        public LibraryQuery(BooksRepository booksRepository, AuthorsRepository authorsRepository)
        {
            FieldAsync <ListGraphType <BookType> >(
                "books",
                resolve: async context =>
            {
                return(await booksRepository.GetAllAsync());
            });

            Field <BookType>(
                "book",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context =>
            {
                var id = context.GetArgument <long>("id");
                return(booksRepository.GetById(id));
            });

            Field <ListGraphType <AuthorType> >(
                "authors",
                resolve: context => authorsRepository.GetAuthorsAsync());

            Field <AuthorType>(
                "author",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context =>
            {
                var id = context.GetArgument <long>("id");
                return(authorsRepository.GetAuthorById(id));
            });
        }
        public static void GetBooksAndAuthors()
        {
            var bookRepo = new BooksRepository();
            var books    = bookRepo.GetBooksAuthorsRatings();

            foreach (var book in books)
            {
                if (book.Authors.Count > 0)
                {
                    Console.WriteLine(book.Title + " " + book.ReleaseDate);

                    foreach (var author in book.Authors)
                    {
                        Console.WriteLine("\t" + author.Author.LastName + ", " + author.Author.FirstName);
                    }
                    if (book.Ratings.Count > 0)
                    {
                        foreach (var rating in book.Ratings)
                        {
                            Console.WriteLine("\tRated by: " + rating.Magazine + ", points: " + rating.Points + ", " + rating.RatingDate);
                        }
                    }
                    else
                    {
                        Console.WriteLine("\tBook not rated yet");
                    }
                }
            }
        }
        public static void DisplayBooksEagerLoad()
        {
            var bookRepo = new BooksRepository();
            var books    = bookRepo.GetBooksAuthorsAndQuotes();

            Console.WriteLine("\n\n\n====================\n");
            foreach (var book in books)
            {
                Console.Write(book.Title);
                if (book.Ratings.Count > 0)
                {
                    foreach (var rating in book.Ratings)
                    {
                        Console.WriteLine(" => Magazine: " + rating.Magazine + " Points: " + rating.Points);
                    }
                }
                else
                {
                    Console.WriteLine(" => Not Rated!");
                }
                foreach (var author in book.Authors)
                {
                    Console.WriteLine("\t" + author.Author.FirstName + " " + author.Author.LastName);
                    foreach (var quote in book.Quotes)
                    {
                        Console.WriteLine("\t\t" + quote.Text);
                    }
                }
            }
        }
Esempio n. 8
0
        public static void AddBook()
        {
            HeaderMenu.Show();
            Console.WriteLine("You are at: > Books > Add new book.");
            Console.WriteLine("");

            Book book = new Book();


            Console.WriteLine("Type the title of the book you want to add.");
            book.Title = Console.ReadLine();


            Console.WriteLine("Type the price of the book you want to add.");
            book.Price = Convert.ToDecimal(Console.ReadLine());

            BooksRepository.Insert(book);

            Console.WriteLine("");
            Console.WriteLine("Book inserted successfully!");
            Console.WriteLine("");

            Console.WriteLine("Press any key to return.");
            Console.ReadKey();
        }
Esempio n. 9
0
        public void DeleteBookScenarioBasic()
        {
            var options = new DbContextOptionsBuilder <BooksDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteBookScenarioBasic")
                          .Options;

            // Insert seed data into the database using one instance of the context
            using (var ctx = new BooksDbContext(options))
            {
                ctx.Database.EnsureCreated();
            }

            // Use a clean instance of the context to run the test
            using (var ctx = new BooksDbContext(options))
            {
                var repo = new BooksRepository(ctx);

                repo.DeleteBookAsync(3).Wait();
            }

            // Use a clean instance of the context to run the test
            using (var ctx = new BooksDbContext(options))
            {
                var repo = new BooksRepository(ctx);

                var books = repo.RetrieveBooksAsync().Result;

                Assert.Equal(4, books.Count());
            }
        }
        //PUT: api/Books/5
        public IHttpActionResult Put([FromUri] int id, [FromBody] Book book)
        {
            try
            {
                if (book == null)
                {
                    return(BadRequest("Book cannot be null"));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var booksRepository = new BooksRepository();
                var updateBook      = booksRepository.Save(id, book);

                if (updateBook == null)
                {
                    return(NotFound());
                }

                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Esempio n. 11
0
        public void Books_UpdateLoanRegistration_SuccessfulUpdate()
        {
            // Arrange
            var repo   = new BooksRepository(context);
            int userId = (context.Users.OrderByDescending(u => u.Id).FirstOrDefault()).Id;
            int bookId = (context.Books.OrderByDescending(u => u.Id).FirstOrDefault()).Id;

            var updatedLoan = new LoanView {
                UserId          = userId,
                BookId          = bookId,
                LoanDate        = new DateTime(1999, 12, 24),
                HasBeenReturned = true,
                EndDate         = new DateTime(2019, 12, 24)
            };

            // Act
            repo.UpdateLoanRegistration(userId, bookId, updatedLoan);

            // Assert
            Assert.AreEqual(new DateTime(1999, 12, 24), (context.Loans
                                                         .Where(l => l.UserId == userId && l.BookId == bookId)
                                                         .SingleOrDefault()).LoanDate);
            Assert.AreEqual(new DateTime(2019, 12, 24), (context.Loans
                                                         .Where(l => l.UserId == userId && l.BookId == bookId)
                                                         .SingleOrDefault()).EndDate);
            Assert.AreEqual(true, (context.Loans
                                   .Where(l => l.UserId == userId && l.BookId == bookId)
                                   .SingleOrDefault()).HasBeenReturned);
        }
Esempio n. 12
0
        public async void AddBookTest_AddsBookToTheDatabaseAndReturnIt()
        {
            Book mockBook = new Book
            {
                ISBN   = "Test ISBN",
                Author = "Test Author",
                Title  = "Test Title"
            };

            var connectionMock = new Mock <DbConnection>();

            connectionMock
            .SetupDapperAsync(c => c.ExecuteAsync(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <IDbTransaction>(), It.IsAny <int?>(), It.IsAny <CommandType?>()))
            .ReturnsAsync(1);

            var connectionFactoryMock = new Mock <IDbConnectionFactory>();

            connectionFactoryMock
            .Setup(m => m.CreateConnection())
            .Returns(connectionMock.Object);

            var booksRepository = new BooksRepository(connectionFactoryMock.Object);

            var insertedBook = await booksRepository.InsertAsync(mockBook);

            Assert.Equal(insertedBook, mockBook);
        }
        public IHttpActionResult Get([FromUri] int id)
        {
            try
            {
                //throw new ArgumentNullException("this is a test");
                Book book;
                var  booksRepository = new BooksRepository();

                if (id > 0)
                {
                    var books = booksRepository.Retrieve();
                    book = books.FirstOrDefault(p => p.BookId == id);
                    if (book == null)
                    {
                        return(NotFound());
                    }
                }
                else
                {
                    book = booksRepository.Create();
                }

                return(Ok(book));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        //POST: api/Products
        public IHttpActionResult Post([FromBody] Book book)
        {
            try
            {
                if (book == null)
                {
                    return(BadRequest("Book cannot be null"));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var booksRepository = new BooksRepository();
                var newBook         = booksRepository.Save(book);

                if (newBook == null)
                {
                    return(Conflict());
                }

                var requestUri = Request.RequestUri;
                var newBookId  = newBook.BookId.ToString();
                var location   = requestUri + newBookId;

                return(Created <Book>(location, newBook));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Esempio n. 15
0
        private static void Main(string[] args)
        {
            var rnd       = new Random();
            var booksRepo = new BooksRepository();

            booksRepo.Add(
                new RepoAuthor
            {
                FirstName = "Damon",
                LastName  = "German"
            },
                new RepoTitle
            {
                BookTitle     = "Why it's Hard to Write Clean Code",
                Copyright     = "1998",
                EditionNumber = 5,
                ISBN          = GetRandomString(rnd)
            },
                new RepoTitle
            {
                BookTitle     = "Why Map is my Favorite Data Structure",
                Copyright     = "2007",
                EditionNumber = 1,
                ISBN          = GetRandomString(rnd)
            }
                );

            DisplayAuthorsAndTitles(booksRepo);
            DisplayAuthorsAndISBNs(booksRepo);
        }
Esempio n. 16
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            CreateRoles.Execute();
            Seed.Execute();

            var bookRepo    = new BooksRepository();
            var libraryRepo = new LibrariesRepository();


            bookRepo.GetBookBorrowExpirations();
            SchedulerService.StartAction(24, bookRepo.GetBookBorrowExpirations);

            libraryRepo.GetMembershipExpirations();
            SchedulerService.StartAction(24, libraryRepo.GetMembershipExpirations);

            bookRepo.GetBookReservationExpirations();
            SchedulerService.StartAction(2, bookRepo.GetBookReservationExpirations);
        }
Esempio n. 17
0
        public ActionResult EditBook(int id)
        {
            LibraryManagementSystemContext context    = new LibraryManagementSystemContext();
            BooksRepository      booksRepository      = new BooksRepository(context);
            PublishersRepository publishersRepository = new PublishersRepository(context);
            BooksEditBookVM      model = new BooksEditBookVM();

            Book book = booksRepository.GetByID(id);

            if (id > 0)
            {
                if (book == null)
                {
                    return(RedirectToAction("Index", "Books"));
                }

                model.ID            = book.ID;
                model.Title         = book.Title;
                model.PublisherID   = book.Publisher.ID;
                model.StockCount    = book.StockCount;
                model.DeliveryPrice = book.DeliveryPrice;
                model.DateReceived  = book.DateReceived;
                model.DatePublished = book.DatePublished;
            }
            else
            {
                book = new Book();
            }

            model.Publishers = model.Publishers ?? new List <SelectListItem>();
            model.Publishers = SelectListHandler.Create <Publisher>(
                publishersRepository.GetAll(), p => p.Name, p => p.ID.ToString(), model.PublisherID.ToString());

            return(View(model));
        }
Esempio n. 18
0
        //Här använder jag asyncron metoden för att böcker och författare ska kunna hämtas oberoende av main tråden
        //samt att await pausar all vidare exekvering fram tills alla böcker och författare är framtagna.
        public async static void GetAll()
        {
            var bookRepo   = new BooksRepository();
            var authorRepo = new AuthorsRepository();

            Console.WriteLine("Starting");


            Task <ICollection <Book> > books = bookRepo.GetAllAsync();

            foreach (var book in books.Result)
            {
                Console.WriteLine(book.Title);
            }

            Console.WriteLine("In process");


            Task <ICollection <Author> > authors = authorRepo.GetAllAsync();

            foreach (var author in authors.Result)
            {
                Console.WriteLine(author.FirstName);
            }

            await Task.WhenAll(books, authors);

            Console.WriteLine("Both tasks done");
        }
Esempio n. 19
0
        public ActionResult ReturnBook(string bookInfo, BooksReturnBookVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository        = new BooksRepository(context);

            // makes an book info array in format {Barcode No.}{Empty}{Empty}{Book title}
            string[] bookInfoSplitted = bookInfo.Split(' ', '-');

            if (string.IsNullOrEmpty(bookInfo) || bookInfoSplitted[0] == "")
            {
                ModelState.AddModelError("BookBarcodeNumber", "* barcode required");
            }
            if (!ModelState.IsValid)
            {
                model.DateReturned = DateTime.Now;
                model.Books        = booksRepository.GetAll();

                return(View(model));
            }

            model.BookBarcodeNumber = int.Parse(bookInfoSplitted[0]);
            Book book = booksRepository
                        .GetAll(filter: b => b.Barcodes.FirstOrDefault().BarcodeNumber == model.BookBarcodeNumber)
                        .FirstOrDefault();

            book.StockCount++;
            booksRepository.Save(book);

            return(RedirectToAction("Index", "Books"));
        }
Esempio n. 20
0
        public ActionResult Details(int id, string sortOrder)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            PublishersRepository           publishersRepository = new PublishersRepository(context);
            BooksRepository     booksRepository = new BooksRepository(context);
            PublishersDetailsVM model           = new PublishersDetailsVM();

            this.TryUpdateModel(model);

            var publisher = publishersRepository.GetByID(id);

            if (publisher != null)
            {
                model.ID                           = publisher.ID;
                model.PublisherName                = publisher.Name;
                model.Address                      = publisher.Address;
                model.BooksPager                   = model.BooksPager ?? new GenericPagerVM();
                model.BooksPager.CurrentPage       = model.BooksPager.CurrentPage == 0 ? 1 : model.BooksPager.CurrentPage;
                model.BooksPager.Action            = "Details";
                model.BooksPager.Controller        = "Publishers";
                model.BooksPager.Prefix            = "BooksPager";
                model.BooksPager.CurrentParameters = new Dictionary <string, object>()
                {
                    { "BookTitle", model.BookTitle },
                    { "BooksPager.CurrentPage", model.BooksPager.CurrentPage }
                };

                #region Sorting and Filtering

                Expression <Func <Book, bool> > filter = b =>
                                                         (string.IsNullOrEmpty(model.BookTitle) || b.Title.Contains(model.BookTitle));
                model.BooksPager.PagesCount = GetPagesCount(filter);

                ViewBag.BookSortParam = string.IsNullOrEmpty(sortOrder) ? "book_desc" : "";
                switch (sortOrder)
                {
                case "book_desc":
                    model.Books = booksRepository
                                  .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, x => x.OrderByDescending(b => b.Title))
                                  .Where(b => b.PublisherID == id)
                                  .ToList();
                    break;

                default:
                    model.Books = booksRepository
                                  .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, x => x.OrderBy(b => b.Title))
                                  .Where(b => b.PublisherID == id)
                                  .ToList();
                    break;
                }
                #endregion

                return(View(model));
            }
            else
            {
                return(RedirectToAction("Index", "Publishers"));
            }
        }
Esempio n. 21
0
        public ActionResult Edit(BookModel book, int id)
        {
            BooksRepository r = new BooksRepository();

            r.Edit(book);

            return(RedirectToAction("List"));
        }
Esempio n. 22
0
        public static void DeleteOne()
        {
            var bookRepo = new BooksRepository();
            var book     = bookRepo.FindBy(b => b.Id == 11).FirstOrDefault();

            bookRepo.Delete(book);
            bookRepo.Save();
        }
Esempio n. 23
0
        public ActionResult Search(SearchModel searchData)
        {
            BooksRepository r = new BooksRepository();

            List <BookModel> foundBooks = r.Search(searchData.Text);

            return(View("List", foundBooks));
        }
Esempio n. 24
0
        // GET: Books
        public ActionResult List()
        {
            BooksRepository r = new BooksRepository();

            List <BookModel> myBooks = r.GetAll();

            return(View());
        }
        public void TestInitialize()
        {
            _mockBooks = new Mock <DbSet <Book> >();
            var mockContext = new Mock <ILibraryContext>();

            mockContext.SetupGet(c => c.Books).Returns(_mockBooks.Object);
            _repository = new BooksRepository(mockContext.Object);
        }
 public BookContentEditor(BookInfo initializationBookInfo, BooksRepository booksRepository, BooksGrid booksGrid)
 {
     WorkingBooksGrid       = booksGrid;
     WorkingBooksRepository = booksRepository;
     BookInfoFromDB         = initializationBookInfo;
     WorkingBooksGrid.MainListView.SelectionChanged += Update;
     UpdateAllTextBoxes(initializationBookInfo);
 }
Esempio n. 27
0
 public EditBooks(string codebook)
 {
     InitializeComponent();
     lblCodeBook.Text = codebook;
     books            = new Books();
     booksRepository  = new BooksRepository();
     InitializeEdit();
 }
        public void TestSelectAll()
        {
            BooksRepository <BookModel> repository = new BooksRepository <BookModel>();
            int totalPage          = 1;
            List <BookModel> books = repository.SelectAll(1, 20, out totalPage);

            Assert.IsTrue(books.Count > 0);
        }
Esempio n. 29
0
        public HttpResponseMessage DeleteBook(int id)
        {
            BooksRepository ctxBook = new BooksRepository();

            ctxBook.DeleteBook(id);
            HttpResponseMessage ms = Request.CreateResponse(HttpStatusCode.Accepted);

            return(ms);
        }
 public StorageOfBooks()
 {
     InitializeComponent();
     context         = new Context();
     booksRepo       = new BooksRepository();
     membersRepo     = new MembersRepository();
     borrowedRepo    = new BorrowedRepository();
     reservationRepo = new ReservationRepository();
 }
        public ActionResult Details(int id, string sortOrder)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            PublishersRepository publishersRepository = new PublishersRepository(context);
            BooksRepository booksRepository = new BooksRepository(context);
            PublishersDetailsVM model = new PublishersDetailsVM();
            this.TryUpdateModel(model);

            var publisher = publishersRepository.GetByID(id);
            if (publisher != null)
            {
                model.ID = publisher.ID;
                model.PublisherName = publisher.Name;
                model.Address = publisher.Address;
                model.BooksPager = model.BooksPager ?? new GenericPagerVM();
                model.BooksPager.CurrentPage = model.BooksPager.CurrentPage == 0 ? 1 : model.BooksPager.CurrentPage;
                model.BooksPager.Action = "Details";
                model.BooksPager.Controller = "Publishers";
                model.BooksPager.Prefix = "BooksPager";
                model.BooksPager.CurrentParameters = new Dictionary<string, object>()
                {
                    { "BookTitle", model.BookTitle },
                    { "BooksPager.CurrentPage", model.BooksPager.CurrentPage }
                };

                #region Sorting and Filtering

                Expression<Func<Book, bool>> filter = b =>
                            (string.IsNullOrEmpty(model.BookTitle) || b.Title.Contains(model.BookTitle));
                model.BooksPager.PagesCount = GetPagesCount(filter);

                ViewBag.BookSortParam = string.IsNullOrEmpty(sortOrder) ? "book_desc" : "";
                switch (sortOrder)
                {
                    case "book_desc":
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, x => x.OrderByDescending(b => b.Title))
                            .Where(b => b.PublisherID == id)
                            .ToList();
                        break;
                    default:
                        model.Books = booksRepository
                           .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, x => x.OrderBy(b => b.Title))
                           .Where(b => b.PublisherID == id)
                           .ToList();
                        break;
                }
                #endregion

                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Publishers");
            }
        }
Esempio n. 32
0
        private static void Main(string[] args)
        {
            using (var context = new rubenvh_boekenEntities())
            using (var unitOfWork = new UnitOfWork())
            using (var booksRepo = new BooksRepository(unitOfWork))
            using (var categoriesRepo = new CategoryRepository(unitOfWork))
            using (var authorsRepo = new AuthorRepository(unitOfWork))
            {
                Console.WriteLine("Found {0} books.", context.boeken.Count());

                var categories = categoriesRepo.All.ToList();

                var allBooksQuery = context.boeken
                    .Include(_ => _.Readings)
                    .Include(_ => _.GenreLinks)
                    .Include(_ => _.GenreLinks.Select(g => g.Genre));
                var allBooks = allBooksQuery.ToList();

                var authorDictionary = PrefillAuthors(allBooks, authorsRepo, unitOfWork);
                var newBooks = new List<Book>(allBooks.Count);

                foreach (var book in allBooks)
                {
                    Console.WriteLine("Book {0} in {1}: {2}",
                        book.boekID,
                        book.GenreLinks.First().Genre.naam,
                        book.Readings.Any() ? book.Readings.First().datum.ToString() : "not read");

                    newBooks.Add(new Book()
                    {
                        State = State.Added,
                        FirstPublished = book.jaar.HasValue && book.jaar!=0? new DateTime(book.jaar.Value, 1, 1) : default(DateTime?),
                        Isbn = book.isbn,
                        Pages = book.blz ?? 0,
                        Title = book.titel,
                        Authors = new List<Author>() { authorsRepo.Find(authorDictionary[book.auteurs.ToLower()]) },
                        Readings = book.Readings.Select(_ => new Reading()
                                    {
                                        State = State.Added,
                                        PagesRead = book.blz ?? 0,
                                        Date = _.datum
                                    }).ToList(),
                        CategoryId = categories.Single(_ => _.Name == book.GenreLinks.First().Genre.naam).Id,
                        Tags = book.tags
                    });
                }

                newBooks.ForEach(booksRepo.InsertOrUpdateGraph);
                unitOfWork.Save();
            }
           
        }
        public ActionResult DeleteBook(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            BooksDeleteBookVM model = new BooksDeleteBookVM();

            Book book = booksRepository.GetByID(id);

            model.ID = book.ID;
            model.Title = book.Title;

            return View(model);
        }
        public ActionResult EditRent()
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            CustomersRepository customersRepository = new CustomersRepository(context);
            RentsEditRentVM model = new RentsEditRentVM();

            model.Customers = customersRepository.GetAll();
            model.Books = booksRepository.GetAll();
            model.RentDate = DateTime.Now.Date;
            model.UserID = AuthenticationManager.LoggedUser.ID;

            return View(model);
        }
        public ActionResult AddBookAuthor(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            AuthorsRepository authorsRepository = new AuthorsRepository(context);
            BooksAddBookAuthorVM model = new BooksAddBookAuthorVM();

            Book book = booksRepository.GetByID(id);
            model.ID = book.ID;
            model.Title = book.Title;
            model.Authors = model.Authors ?? new List<SelectListItem>();
            model.Authors = SelectListHandler.Create<Author>(
                authorsRepository.GetAll(), a => (a.FirstName + " " + a.LastName), a => a.ID.ToString(), model.AuthorID.ToString());

            return View(model);
        }
        public ActionResult DeleteBook(BooksDeleteBookVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);

            Book book = booksRepository.GetByID(model.ID);
            if (book == null)
            {
                return HttpNotFound();
            }
            else
            {
                booksRepository.Delete(book);
            }

            return RedirectToAction("Index");
        }
        public ActionResult EditBarcode(int id, int bookID)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BarcodesRepository barcodesRepository = new BarcodesRepository(context);
            BooksRepository booksRepository = new BooksRepository(context);
            BarcodesEditBarcodeVM model = new BarcodesEditBarcodeVM();

            Barcode barcode = barcodesRepository.GetByID(id);
            if (id > 0)
            {
                if (barcode == null)
                {
                    barcode.BookID = bookID;
                }

                model.ID = barcode.ID;
                model.BookID = barcode.BookID;
                model.BarcodeNumber = barcode.BarcodeNumber;
            }

            return View(model);
        }
        public ActionResult AddBookAuthor(BooksAddBookAuthorVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            AuthorsRepository authorsRepository = new AuthorsRepository(context);

            Book book = null;
            Author author = null;
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            else
            {
                book = booksRepository.GetByID(model.ID);
                author = authorsRepository.GetByID(model.AuthorID);

                book.Authors.Add(author);
                booksRepository.Save(book);
            }

            return RedirectToAction("Details/" + model.ID, "Books");
        }
        public ActionResult EditRent(string customerInfo, string bookInfo, RentsEditRentVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            RentsRepository rentsRepository = new RentsRepository(context);
            BooksRepository booksRepository = new BooksRepository(context);
            CustomersRepository customersRepository = new CustomersRepository(context);

            // makes an customer info array in format {Personal No.}{Empty}{Empty}{First name}{Last name}
            string[] customerInfoSplitted = customerInfo.Split(' ', '-');

            // makes an book info array in format {Barcode No.}{Empty}{Empty}{Book title}
            string[] bookInfoSplitted = bookInfo.Split(' ', '-');

            if (string.IsNullOrEmpty(customerInfo) || customerInfoSplitted[0] == "")
            {
                ModelState.AddModelError("CustomerPersonalNumber", "* personal No. required");
            }
            if (string.IsNullOrEmpty(bookInfo) || bookInfoSplitted[0] == "")
            {
                ModelState.AddModelError("BookBarcodeNumber", "* barcode required");
            }
            if (!ModelState.IsValid)
            {
                if (model.ID <= 0)
                {
                    model.RentDate = DateTime.Now;
                }

                model.Customers = customersRepository.GetAll();
                model.Books = booksRepository.GetAll();

                return View(model);
            }

            model.CustomerPersonalNumber = int.Parse(customerInfoSplitted[0]);
            model.Customer = customersRepository
                .GetAll(filter: c => c.PersonalNumber == model.CustomerPersonalNumber)
                .FirstOrDefault();

            model.BookBarcodeNumber = int.Parse(bookInfoSplitted[0]);
            model.Books = booksRepository
                .GetAll(filter: b => b.Barcodes.Any(bc => bc.BarcodeNumber == model.BookBarcodeNumber));

            if (model.Books.Any(b => b.StockCount > 0))
            {
                Rent rent = new Rent();
                rent.Books = new List<Book>();
                rent.Books = model.Books;
                rent.Books.FirstOrDefault().StockCount--;
                rent.DateToReturn = DateTime.Now.AddMonths(1);
                rent.RentDate = model.RentDate;
                rent.UserID = model.UserID;
                rent.CustomerID = model.Customer.ID;

                rentsRepository.Save(rent);
            }
            else
            {
                ModelState.AddModelError("BookBarcodeNumber", "* book not in stock at the moment");

                if (model.ID <= 0)
                {
                    model.RentDate = DateTime.Now;
                }

                model.Customers = customersRepository.GetAll();
                model.Books = booksRepository.GetAll();

                return View(model);
            }

            return RedirectToAction("Index", "Rents");
        }
        public ActionResult Details(int id, string sortOrder)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            AuthorsRepository authorsRepository = new AuthorsRepository(context);
            BooksRepository booksRepository = new BooksRepository(context);
            AuthorsDetailsVM model = new AuthorsDetailsVM();
            this.TryUpdateModel(model);

            Author author = authorsRepository.GetByID(id);
            if (author != null)
            {
                model.ID = author.ID;
                model.AuhtorName = author.ToString();
                model.BooksPager = model.BooksPager ?? new GenericPagerVM();
                model.BooksPager.CurrentPage = model.BooksPager.CurrentPage == 0 ? 1 : model.BooksPager.CurrentPage;
                model.BooksPager.Action = "Details";
                model.BooksPager.Controller = "Authors";
                model.BooksPager.Prefix = "BooksPager";
                model.BooksPager.CurrentParameters = new Dictionary<string, object>()
                {
                    { "BookTitle", model.BookTitle },
                    { "PublisherName", model.PublisherName },
                    { "BooksPager.CurrentPage", model.BooksPager.CurrentPage }
                };

                #region Sorting and Filtering
                Expression<Func<Book, bool>> filter = b =>
                           (string.IsNullOrEmpty(model.BookTitle) || b.Title.Contains(model.BookTitle)) &&
                           (string.IsNullOrEmpty(model.PublisherName) || b.Publisher.Name.Contains(model.PublisherName));
                model.BooksPager.PagesCount = GetPagesCount(filter);

                ViewBag.TitleSortParam = string.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
                ViewBag.PublisherSortParam = sortOrder == "Publisher" ? "publisher_desc" : "Publisher";
                ViewBag.StockCountSortParam = sortOrder == "StockCount" ? "stockCount_desc" : "StockCount";
                switch (sortOrder)
                {
                    case "title_desc":
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(b => b.Title))
                            .Where(b => b.Authors.Any(a => a.ID == id))
                            .ToList();
                        break;
                    case "Publisher":
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(b => b.Publisher.Name))
                            .Where(b => b.Authors.Any(a => a.ID == id))
                            .ToList();
                        break;
                    case "publisher_desc":
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(b => b.Publisher.Name))
                            .Where(b => b.Authors.Any(a => a.ID == id))
                            .ToList();
                        break;
                    case "StockCount":
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(b => b.StockCount))
                            .Where(b => b.Authors.Any(a => a.ID == id))
                            .ToList();
                        break;
                    case "stockCount_desc":
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(b => b.StockCount))
                            .Where(b => b.Authors.Any(a => a.ID == id))
                            .ToList();
                        break;
                    default:
                        model.Books = booksRepository
                            .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(b => b.Title))
                            .Where(b => b.Authors.Any(a => a.ID == id))
                            .ToList();
                        break;
                }
                #endregion

                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Authors");
            }
        }
        public ActionResult EditBook(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            PublishersRepository publishersRepository = new PublishersRepository(context);
            BooksEditBookVM model = new BooksEditBookVM();

            Book book = booksRepository.GetByID(id);
            if (id > 0)
            {
                if (book == null)
                {
                    return RedirectToAction("Index", "Books");
                }

                model.ID = book.ID;
                model.Title = book.Title;
                model.PublisherID = book.Publisher.ID;
                model.StockCount = book.StockCount;
                model.DeliveryPrice = book.DeliveryPrice;
                model.DateReceived = book.DateReceived;
                model.DatePublished = book.DatePublished;
            }
            else
            {
                book = new Book();
            }

            model.Publishers = model.Publishers ?? new List<SelectListItem>();
            model.Publishers = SelectListHandler.Create<Publisher>(
                publishersRepository.GetAll(), p => p.Name, p => p.ID.ToString(), model.PublisherID.ToString());

            return View(model);
        }
        public ActionResult EditBook(BooksEditBookVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            PublishersRepository publishersRepository = new PublishersRepository(context);

            Book book = null;
            if (!ModelState.IsValid)
            {
                model.Publishers = model.Publishers ?? new List<SelectListItem>();
                model.Publishers = SelectListHandler.Create<Publisher>(
                    publishersRepository.GetAll(), p => p.Name, p => p.ID.ToString(), model.PublisherID.ToString());
                return View(model);
            }
            else
            {
                if (model.ID > 0)
                {
                    book = booksRepository.GetByID(model.ID);
                }
                else
                {
                    book = new Book();
                }

                book.ID = model.ID;
                book.Title = model.Title;
                book.PublisherID = model.PublisherID;
                book.StockCount = model.StockCount;
                book.DeliveryPrice = model.DeliveryPrice;
                book.DateReceived = model.DateReceived;
                book.DatePublished = model.DatePublished;

                booksRepository.Save(book);
            }

            return RedirectToAction("Index", "Books");
        }
        public ActionResult Index(string sortOrder)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            BooksIndexVM model = new BooksIndexVM();
            this.TryUpdateModel(model);

            model.BooksPager = model.BooksPager ?? new GenericPagerVM();
            model.BooksPager.CurrentPage = model.BooksPager.CurrentPage == 0 ? 1 : model.BooksPager.CurrentPage;
            model.BooksPager.Prefix = "BooksPager";
            model.BooksPager.Action = "Index";
            model.BooksPager.Controller = "Books";
            model.BooksPager.CurrentParameters = new Dictionary<string, object>()
            {
                { "Title", model.Title },
                { "Publisher", model.Publisher },
                { "BooksPager.CurrentPage", model.BooksPager.CurrentPage }
            };

            #region Sorting and Filtering
            Expression<Func<Book, bool>> filter = b =>
                   (string.IsNullOrEmpty(model.Title) || b.Title.Contains(model.Title)) &&
                   (string.IsNullOrEmpty(model.Publisher) || b.Publisher.Name.Contains(model.Publisher));
            model.BooksPager.PagesCount = GetPagesCount(filter);

            ViewBag.TitleSortParam = string.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
            ViewBag.PublisherSortParam = sortOrder == "Publisher" ? "publisher_desc" : "Publisher";
            ViewBag.StockCountSortParam = sortOrder == "StockCount" ? "stockCount_desc" : "StockCount";
            switch (sortOrder)
            {
                case "title_desc":
                    model.BooksList = booksRepository
                        .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(b => b.Title))
                        .ToList();
                    break;
                case "Publisher":
                    model.BooksList = booksRepository
                        .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(b => b.Publisher.Name))
                        .ToList();
                    break;
                case "publisher_desc":
                    model.BooksList = booksRepository
                        .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(b => b.Publisher.Name))
                        .ToList();
                    break;
                case "StockCount":
                    model.BooksList = booksRepository
                        .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(b => b.StockCount))
                        .ToList();
                    break;
                case "stockCount_desc":
                    model.BooksList = booksRepository
                        .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(b => b.StockCount))
                        .ToList();
                    break;
                default:
                    model.BooksList = booksRepository
                        .GetAll(model.BooksPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(b => b.Title))
                        .ToList();
                    break;
            }
            #endregion

            return View(model);
        }
        public ActionResult ListBookBarcodes(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            BarcodesRepository barcodesRepository = new BarcodesRepository(context);
            BooksListBookBarcodesVM model = new BooksListBookBarcodesVM();
            this.TryUpdateModel(model);

            var book = booksRepository.GetByID(id);
            if (book != null)
            {
                model.BookID = book.ID;
                model.BookTitle = book.Title;
                model.BarcodesPager = model.BarcodesPager ?? new GenericPagerVM();
                model.BarcodesPager.PagesCount = GetPagesCount();
                model.BarcodesPager.CurrentPage =
                    model.BarcodesPager.CurrentPage == 0 ? 1 : model.BarcodesPager.CurrentPage;
                model.Barcodes = barcodesRepository
                    .GetAll(model.BarcodesPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, b => b.BookID == id)
                    .ToList();
                model.BarcodesPager.Action = "Index";
                model.BarcodesPager.Controller = "Books";
                model.BarcodesPager.Prefix = "BarcodesPager";
                model.BarcodesPager.CurrentParameters = new Dictionary<string, object>()
                {
                    { "BarcodesPager.CurrentPage", model.BarcodesPager.CurrentPage }
                };

                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Books");
            }
        }
        public ActionResult ReturnBook()
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            BooksReturnBookVM model = new BooksReturnBookVM();

            model.DateReturned = DateTime.Now.Date;
            model.Books = booksRepository.GetAll();

            return View(model);
        }
        public ActionResult ReturnBook(string bookInfo, BooksReturnBookVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);

            // makes an book info array in format {Barcode No.}{Empty}{Empty}{Book title}
            string[] bookInfoSplitted = bookInfo.Split(' ', '-');

            if (string.IsNullOrEmpty(bookInfo) || bookInfoSplitted[0] == "")
            {
                ModelState.AddModelError("BookBarcodeNumber", "* barcode required");
            }
            if (!ModelState.IsValid)
            {
                model.DateReturned = DateTime.Now;
                model.Books = booksRepository.GetAll();

                return View(model);
            }

            model.BookBarcodeNumber = int.Parse(bookInfoSplitted[0]);
            Book book = booksRepository
                .GetAll(filter: b => b.Barcodes.FirstOrDefault().BarcodeNumber == model.BookBarcodeNumber)
                .FirstOrDefault();
            book.StockCount++;
            booksRepository.Save(book);

            return RedirectToAction("Index", "Books");
        }
        public int GetPagesCount(Expression<Func<Book, bool>> filter = null)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);

            int pagesCount = 0;
            int pageSize = ApplicationConfiguration.ItemsPerPage;
            int booksCount = 0;
            booksCount = booksRepository.Count(filter);
            pagesCount = booksCount / pageSize;
            if ((booksCount % pageSize) > 0)
            {
                pagesCount++;
            }

            return pagesCount;
        }
        public ActionResult Details(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            BooksRepository booksRepository = new BooksRepository(context);
            AuthorsRepository authorsRepository = new AuthorsRepository(context);
            BooksDetailsVM model = new BooksDetailsVM();
            this.TryUpdateModel(model);

            Book book = booksRepository.GetByID(id);
            Author author = new Author();
            if (book != null)
            {
                model.ID = book.ID;
                model.Title = book.Title;
                model.Publisher = book.Publisher;
                model.StockCount = book.StockCount;
                model.DeliveryPrice = book.DeliveryPrice;
                model.DateReceived = book.DateReceived;
                model.DatePublished = book.DatePublished;
                model.AuthorsPager = model.AuthorsPager ?? new GenericPagerVM();
                model.AuthorsPager.PagesCount = GetPagesCount();
                model.AuthorsPager.CurrentPage =
                    model.AuthorsPager.CurrentPage == 0 ? 1 : model.AuthorsPager.CurrentPage;
                model.Authors = authorsRepository
                    .GetAll(model.AuthorsPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, a => a.Books.Any(b => b.ID == id), order: x => x.OrderBy(a => a.FirstName))
                    .ToList();
                model.AuthorsPager.Action = "Details";
                model.AuthorsPager.Controller = "Books";
                model.AuthorsPager.Prefix = "AuthorsPager";
                model.AuthorsPager.CurrentParameters = new Dictionary<string, object>()
                {
                    { "AuthorsPager.CurrentPage", model.AuthorsPager.CurrentPage }
                };

                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Authors");
            }
        }