Esempio n. 1
0
        public void EventTest()
        {
            Random   rnd = new Random();
            string   title1 = "Dziady", author1 = "Adam Mickiewicz", currency1 = "PLN";
            string   name1 = "Jan", lastName1 = "Kowalski";
            int      stock1    = rnd.Next(10, int.MaxValue);
            double   prize1    = rnd.NextDouble() * stock1;
            Reader   tester    = new Reader(name1, lastName1);
            BookItem testBook  = new BookItem(title1, author1);
            CopyInfo testCopy  = new CopyInfo(testBook, stock1, prize1, currency1);
            Event    testEvent = new Borrowing(tester, testCopy);

            Assert.Contains("Borrowing", testEvent.ToString());
            Assert.Contains((prize1 * 0.2).ToString("0.00"), testEvent.ToString());
            Assert.Contains(title1, testEvent.ToString());
            Assert.Contains(name1, testEvent.ToString());
            DateTime date1 = new DateTime(2015, 1, 1);

            date1 = date1.AddDays(rnd.Next(200, 2000));
            DateTime date2 = date1.AddDays(rnd.Next(1, 200));

            testEvent = new Borrowing(tester, testCopy, date1);
            Assert.Contains(date1.ToString(), testEvent.ToString());
            testEvent = new Borrowing(tester, testCopy, date1, date2);
            Borrowing testBorrowingCopy = new Borrowing(tester, testCopy, date1, date2);

            Assert.True(testEvent.Equals(testBorrowingCopy));
            testEvent = new Purchase(tester, testCopy);
            Assert.Contains("Purchase", testEvent.ToString());
            Assert.Contains(title1, testEvent.ToString());
            Assert.Contains(name1, testEvent.ToString());
            Assert.Contains(prize1.ToString("0.00"), testEvent.ToString());
        }
Esempio n. 2
0
        public IHttpActionResult CreateBorrowing(NewBorrowingDto newBorrowing)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var member = _context.Members.Single(m => m.Id == newBorrowing.MemberId);
            var books  = _context.Books.Where(b => newBorrowing.BookIds.Contains(b.Id));

            foreach (var book in books)
            {
                var borrowing = new Borrowing {
                    Member = member, Book = book, DateBorrowed = DateTime.Today, DateReturned = DateTime.Today, HasReturned = false
                };
                // If we have it in stock, add it as a borrowing, and reduce the number in stock
                if (book.NumberInStock > 0)
                {
                    _context.Borrowings.Add(borrowing);
                    book.NumberInStock--;
                }
                else
                {
                    return(BadRequest());
                }
            }

            _context.SaveChanges();

            return(Ok());
        }
        public async Task <ActionResult <Borrowing> > PostBorrowing(Borrowing borrowing)
        {
            InventoryItem item = await _context.InventoryItems.FirstOrDefaultAsync(i => i.InventoryID == borrowing.InventoryID);

            if (borrowing == null || item == null)
            {
                return(NotFound());
            }
            if (!item.Available)
            {
                return(BadRequest("Item not available.")); //?? Är detta det bästa i detta fall?
            }
            _context.Borrowings.Add(borrowing);

            try
            {
                item.Available = false;
                _context.InventoryItems.Update(item);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (BorrowingExists(borrowing.InventoryID, borrowing.BorrowerID))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetBorrowing", new { id = borrowing.BorrowerID }, borrowing));
        }
Esempio n. 4
0
        public void Update(Borrowing a)
        {
            DB db = new DB();

            db.Entry(a).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
                // Your code...
                // Could also be before try if you know the exception occurs in SaveChanges
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                                                       validationErrors.Entry.Entity.ToString(),
                                                       validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }
        }
Esempio n. 5
0
        public bool AddBorrowing(int memberID, int bookID, string fromDate)
        {
            Borrowing borrowing = new Borrowing();

            borrowing.MemberID = memberID;
            borrowing.BookID   = bookID;
            DateTime fromDateObject;
            bool     success = DateTime.TryParseExact(fromDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDateObject);

            if (success)
            {
                borrowing.From = fromDateObject;

                try
                {
                    using (BookLibraryContext db = new BookLibraryContext())
                    {
                        db.Borrowings.Add(borrowing);
                        db.SaveChanges();
                    }
                }
                catch (Exception exc)
                {
                    return(false);
                }

                return(true);
            }

            return(false);
        }
Esempio n. 6
0
        public List <Borrowing> GetAllBorrowings()
        {
            var query = from c in dataContext.get_all_borrows()
                        select new
            {
                ISBN       = c.ISBN,
                CopyID     = c.CopyID,
                CustomerID = c.CustomerID,
                Name       = c.Name
            };
            List <Borrowing> borrowings = new List <Borrowing>();

            foreach (var item in query)
            {
                Book book = new Book();
                book.ISBN = item.ISBN;

                BookCopy bc = new BookCopy();
                bc.Book   = book;
                bc.CopyID = item.CopyID;

                Customer cust = new Customer();
                cust.CustomerID = item.CustomerID;
                cust.Name       = item.Name;

                Borrowing b = new Borrowing();
                b.BookCopy = bc;
                b.Customer = cust;

                borrowings.Add(b);
            }
            return(borrowings);
        }
Esempio n. 7
0
        public Borrowing Create(string bookTitle, string accountName)
        {
            // TODO Should be dependency injection here 2x
            var dbBookService = new DbBookService(Database);
            var book          = dbBookService.Read(bookTitle);

            var dbAccountService = new DbAccountService(Database);
            var account          = dbAccountService.Read(accountName);

            if (Database.BorrowingsTbl.Any(x => x.BookId == book.Id))
            {
                return(null);
            }
            else
            {
                var borrowing = new Borrowing {
                    WhenBorrowed = DateTime.Now
                };

                book.Borrowings.Add(borrowing);
                account.BooksBorrowed.Add(borrowing);
                Database.SaveChanges();

                return(borrowing);
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,RentalDate")] Borrowing borrowing)
        {
            if (id != borrowing.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    await _borrowingService.UpdateAsync(borrowing);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!(await BorrowingExists(borrowing.Id)))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(borrowing));
        }
Esempio n. 9
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,BookId,ApplicationUserId,StartDate,MaxDate,EndDate, Description")] Borrowing borrowing)
        {
            if (id != borrowing.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(borrowing);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BorrowingExists(borrowing.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ApplicationUserId"] = new SelectList(_context.ApplicationUser, "Id", "UserName", borrowing.ApplicationUserId);
            ViewData["BookId"]            = new SelectList(_context.Book, "Id", "Title", borrowing.BookId);
            return(View(borrowing));
        }
Esempio n. 10
0
        // GET: Borrowings/Create
        public IActionResult Create()
        {
            Borrowing borrowing = new Borrowing();

            borrowing.StartDate           = DateTime.Now;
            borrowing.MaxDate             = DateTime.Now.AddDays(30);
            ViewData["ApplicationUserId"] = new SelectList(_context.ApplicationUser, "Id", "UserName");

            var AllBooks = _context.Book.Include(b => b.Borrowing);

            List <Book> books = new List <Book>();

            foreach (Book b in AllBooks)
            {
                if (b.Borrowing.Any())
                {
                    if (b.Borrowing.Last().EndDate != null)
                    {
                        books.Add(b);
                    }
                }
                else
                {
                    books.Add(b);
                }
            }


            ViewData["BookId"] = new SelectList(books, "Id", "Title");
            return(View(borrowing));
        }
Esempio n. 11
0
        public bool ReturnBorrowing(int borrowingID, string toDate)
        {
            try
            {
                using (BookLibraryContext db = new BookLibraryContext())
                {
                    Borrowing borrowing = db.Borrowings.Single(b => b.BorrowingID == borrowingID);
                    if (borrowing != null)
                    {
                        DateTime toDateObject = DateTime.MinValue;
                        if (DateTime.TryParseExact(toDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDateObject))
                        {
                            borrowing.To = toDateObject;
                            db.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,CreateDate,IdBorrower,IdLibrarian")] Borrowing borrowing)
        {
            if (id != borrowing.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(borrowing);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BorrowingExists(borrowing.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["IdBorrower"]  = new SelectList(_context.Borrowers, "Id", "Id", borrowing.IdBorrower);
            ViewData["IdLibrarian"] = new SelectList(_context.Librarians, "Id", "Id", borrowing.IdLibrarian);
            return(View(borrowing));
        }
Esempio n. 13
0
                             > Post([FromBody] AddBorrowing borrowing)
        {
            var newBorrowing = new Borrowing
            {
                BookId   = borrowing.BookId,
                AuthorId = borrowing.AuthorId
            };

            var book = _BooksDbContext.Books.FirstOrDefault(b => b.Id == borrowing.BookId);

            if (book == null || book.Copies <= 3)
            {
                return(NotFound("El libro no existe o no hay suficientes copias disponibles."));
            }

            var bookTmp = _BooksDbContext.Books.FirstOrDefault(b => b.Id == book.Id);

            if (bookTmp == null)
            {
                return(NotFound("El libro no existe o no hay suficientes copias disponibles."));
            }
            else
            {
                bookTmp.Copies -= 1;
                _BooksDbContext.Entry(bookTmp).CurrentValues.SetValues(bookTmp);
            }

            _BooksDbContext.Borrowings.Add(newBorrowing);
            _BooksDbContext.SaveChanges();

            return(newBorrowing);
        }
Esempio n. 14
0
        private bool BorrowResource()
        {
            if (!DbUtils.HasUserAlreadyBorrowedResource(dbContext, resource, reader))
            {
                List <Reservation> reservations = dbContext.Reservations
                                                  .Include("Reader")
                                                  .Include("Resource")
                                                  .Where(r => r.ReaderId == reader.Id)
                                                  .Where(r => r.ResourceId == resource.Id)
                                                  .ToList();
                dbContext.Reservations.RemoveRange(reservations);

                Borrowing borrowing = new Borrowing();

                borrowing.BorrowingDate = DateTime.Now;
                borrowing.ReturnDate    = null;
                borrowing.ReturnTerm    = datePicker.Value;
                borrowing.Reader        = reader;
                borrowing.Resource      = resource;
                borrowing.User          = librarian;

                dbContext.Borrowings.Add(borrowing);
                dbContext.SaveChanges();

                return(true);
            }

            MessageBox.Show("Użytkownik już wypożyczył ten zasób!", "Błąd");
            return(false);
        }
Esempio n. 15
0
        public static bool ShouldEqual(this Borrowing actual, Borrowing expected)
        {
            actual.Borrower.ShouldEqual(expected.Borrower);
            actual.Ownership.ShouldEqual(expected.Ownership);
            actual.Borrower.ShouldEqual(expected.Borrower);

            return(true);
        }
Esempio n. 16
0
        private string[] GenerateMagazineNumberRow(Borrowing borrowing)
        {
            MagazineNumber magazineNumber = (MagazineNumber)borrowing.Resource.Position;

            string[] row = { magazineNumber.Magazine.Title, "", ((DateTime)magazineNumber.PublicationDate).ToShortDateString(), borrowing.BorrowingDate.ToShortDateString(), borrowing.ReturnTerm.ToShortDateString() };

            return(row);
        }
Esempio n. 17
0
        private string[] GenerateGameRow(Borrowing borrowing)
        {
            Game game = (Game)borrowing.Resource.Position;

            string[] row = { game.Name, "", "", borrowing.BorrowingDate.ToShortDateString(), borrowing.ReturnTerm.ToShortDateString() };

            return(row);
        }
Esempio n. 18
0
        private static Borrowing PrepareBorrowing(ApplicationUser user, Book book)
        {
            var borrowing = new Borrowing();

            borrowing.SetBorrower(user);
            borrowing.SetBook(book);
            return(borrowing);
        }
Esempio n. 19
0
        public void BorrowBook(String isbn, String cardId)
        {
            Reader reader = dao.FindReader(cardId);
            Book   book   = dao.FindBook(isbn);

            Borrowing borrowing = new Borrowing(book, reader);

            dao.SaveBorrowing(borrowing);
        }
Esempio n. 20
0
        public void GetBorrowingTest()
        {
            DataRepository dataRepository = new DataRepository(new ConstFiller());

            Borrowing tmp  = new Borrowing(dataRepository.GetReader(2), new DateTime(2018, 3, 4), dataRepository.GetState(1));
            Borrowing tmp2 = dataRepository.GetBorrowing(dataRepository.GetReader(2).PersonalID, dataRepository.GetState(1).book.BookID);

            Assert.AreEqual(tmp.GetHashCode(), tmp2.GetHashCode());
        }
Esempio n. 21
0
        public Borrowing Find(int id)
        {
            Borrowing u  = new Borrowing();
            DB        db = new DB();

            db.Borrowings.Attach(u);
            u = db.Borrowings.Find(id);
            return(u);
        }
Esempio n. 22
0
        public void Dodaj(Borrowing u)
        {
            DB mDb = new DB();

            mDb.Borrowings.Add(u);
            mDb.Configuration.ValidateOnSaveEnabled = false;
            //LayerBus.BusPass.DodajFilm(u);
            mDb.SaveChanges();
        }
        public string[] InorderTraversalToStringArraysave(AbstractNode <T> root)
        {
            Stack <AbstractNode <T> > stack = new Stack <AbstractNode <T> >();
            List <string>             list  = new List <string>();

            if (root == null)
            {
                return(null);
            }

            AbstractNode <T> current = root;

            while (current != null)
            {
                stack.Push(current);
                current = current.Left;
            }

            while (stack.Count > 0)
            {
                current = stack.Pop();

                var s = "";
                if (current.Data is Book)
                {
                    T    newt = (T)(object)current.Data;
                    Book b    = (Book)(object)newt;
                    s = b.ToStringSave();
                }
                else if (current.Data is Borrowing)
                {
                    T         newt = (T)(object)current.Data;
                    Borrowing b    = (Borrowing)(object)newt;
                    s = b.ToStringSave();
                }
                else
                {
                    s = current.Data.ToString();
                }

                list.Add(s);

                if (current.Right != null)
                {
                    current = current.Right;

                    while (current != null)
                    {
                        stack.Push(current);
                        current = current.Left;
                    }
                }
            }

            return(list.ToArray());
        }
Esempio n. 24
0
 /// <summary>
 /// Add a new borrowing
 /// </summary>
 /// <param name="borrowing">The borrowing to add</param>
 /// <returns>True if borrowing is added successfuly otherwise false</returns>
 public bool AddNewBorrowing(Borrowing borrowing)
 {
     if (borrowing != null)
     {
         db.Borrowing.Add(borrowing);
         db.SaveChanges();
         return(true);
     }
     return(false);
 }
        public async Task <IActionResult> Create([Bind("Borrower, Book")] Borrowing borrowing)
        {
            if (ModelState.IsValid)
            {
                await _borrowingService.CreateAsync(borrowing);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(borrowing));
        }
Esempio n. 26
0
        public ActionResult Edit(Borrowing Borrowing)
        {
            if (ModelState.IsValid)
            {
                BorrowingsRepository.Update(Borrowing);
                return(RedirectToAction("Index"));
            }

            return(View(Borrowing));
        }
Esempio n. 27
0
        public bool HasGameBorrowed(Guid id)
        {
            Borrowing borrowingAlias = null;

            var query = Session.QueryOver <Friend>()
                        .Inner.JoinAlias(f => f.Borrowings, () => borrowingAlias)
                        .Where(f => f.Id == id);

            return(query.RowCount() > 0);;
        }
Esempio n. 28
0
        public bool IsBorrowed(Guid id)
        {
            Borrowing borrowingAlias = null;

            var query = Session.QueryOver <Game>()
                        .Inner.JoinAlias(g => g.Borrowings, () => borrowingAlias)
                        .Where(g => g.Id == id);

            return(query.RowCount() > 0);
        }
Esempio n. 29
0
        private Borrowing join(String borrowing_id)
        {
            Borrowing borrowing = this.borrowingRepository.SelectByID(borrowing_id);

            if (borrowing != null)
            {
                join(new Borrowing[] { borrowing });
            }

            return(borrowing);
        }
Esempio n. 30
0
        //
        // GET: /Borrowing/Edit/5

        public ActionResult Edit(String id)
        {
            Borrowing Borrowing = BorrowingsRepository.SelectByID(id);

            if (Borrowing == null)
            {
                return(HttpNotFound());
            }

            return(View(Borrowing));
        }