コード例 #1
0
 public void MakeSubscription(Book book, string userId, bool isToTheLibrary)
 {
     using (var context = new LibraryContext())
     {
         DateTime returnDate;
         if (isToTheLibrary)
         {
             returnDate = DateTime.Today;
         }
         else
         {
             returnDate = DateTime.Today.AddDays(14);
         }
         context.InSubscriptions.Add(new InSubscription
         {
             ISBN = book.ISBN,
             IsInUse = true,
             UserId = userId,
             DateOfReceipt = DateTime.Today,
             ReturnDate = returnDate
         });
         book.Quantity -= 1;
         EditBook(book);
         context.SaveChanges();
     }
 }
コード例 #2
0
 public void AddBook(Book book)
 {
     using (var context = new LibraryContext())
     {
         book.isDeleted = false;
         context.Books.Add(book);
         context.SaveChanges();
     }
 }
コード例 #3
0
        public ActionResult AddBook(AccountRoomModel model)
        {
            using (var con = new LibraryContext())
            {
                con.Books.Add(new Book
                {
                    Author = model.EditBook.Author,
                    Name = model.EditBook.Name,
                    Description = model.EditBook.Description,
                    ISBN = model.EditBook.Isbn
                });

                con.SaveChanges();

                model.AllBooks = con.Books.Take(10).ToList();

            }

            return PartialView("Librarian/_EditBooksDatabasePartial", model);
        }
コード例 #4
0
        public Book CreateBook(string title, string authorID, string publicationDate)
        {
            int      parsedAuthorID = 0;
            DateTime parsedPublicationdate;

            // Trim the values so we don't need to do it a bunch of times later.
            authorID        = !(string.IsNullOrWhiteSpace(authorID) || string.IsNullOrEmpty(authorID)) ? authorID.Trim() : null;
            title           = !(string.IsNullOrWhiteSpace(title) || string.IsNullOrEmpty(title)) ? title.Trim() : null;
            publicationDate = !(string.IsNullOrWhiteSpace(publicationDate) || string.IsNullOrEmpty(publicationDate)) ? publicationDate.Trim() : null;

            using LibraryContext context = new LibraryContext();
            // No value for authorID.
            if (string.IsNullOrWhiteSpace(authorID))
            {
                throw new Exception("AuthorID Not Provided");
            }
            else
            {
                // Author ID fails parse.
                if (!int.TryParse(authorID, out parsedAuthorID))
                {
                    throw new Exception("Author ID Not Valid");
                }
                else
                {
                    if (!context.Authors.Any(x => x.ID == parsedAuthorID))
                    {
                        throw new Exception("Author Does Not Exist");
                    }
                }
            }

            // No value for title.
            if (string.IsNullOrWhiteSpace(title))
            {
                throw new Exception("Title Not Provided");
            }
            else
            {
                if (title.Length > 100)
                {
                    throw new Exception("Title length exceeds 100 characters");
                }
                else
                {
                    List <int> authorList = context.Books.Where(x => x.Title.ToLower() == title.ToLower()).Select(x => x.AuthorID).ToList();
                    if (authorList.Any() && authorList.Contains(parsedAuthorID))
                    {
                        throw new Exception($"The Title already exists for this Author.");
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(publicationDate))
            {
                throw new Exception("Publication Date  Not Provided");
            }
            else
            {
                // publicationDate fails parse.
                if (!DateTime.TryParse(publicationDate, out parsedPublicationdate))
                {
                    throw new Exception("Publication Date Not Valid");
                }
                else
                {
                    if (parsedPublicationdate > DateTime.Today)
                    {
                        throw new Exception("Publication date can not be in future.");
                    }
                }
            }

            Book newBook = new Book()
            {
                AuthorID        = int.Parse(authorID),
                Title           = title.Trim(),
                PublicationDate = DateTime.Parse(publicationDate)
            };

            context.Books.Add(newBook);
            context.SaveChanges();
            return(newBook);
        }
コード例 #5
0
 public IActionResult createMovie([FromBody] Movie newMovie)
 {
     context.movies.Add(newMovie);
     context.SaveChanges();
     return(Created("", newMovie));
 }
コード例 #6
0
 public void RemoveBook(string isbn)
 {
     using (var context = new LibraryContext())
     {
         context.Books.Find(isbn).isDeleted = true;
         context.SaveChanges();
     }
 }
コード例 #7
0
 public void Add(Patron newPatron)
 {
     _context.Add(newPatron);
     _context.SaveChanges();
 }
コード例 #8
0
 public void Add(LibraryAsset newAsset)
 {
     _context.Add(newAsset);
     _context.SaveChanges();
 }
コード例 #9
0
 public void AddAsset(LibraryAsset newAsset)
 {
     _libraryContext.LibraryAssets.Add(newAsset);
     _libraryContext.SaveChanges();
 }
コード例 #10
0
 /// <summary>
 /// Lägger till en författare
 /// </summary>
 /// <param name="book">Författaren som ska läggas till</param>
 public void Add(Author author)
 {
     _context.Add(author);
     _context.SaveChanges();
 }
        public static void ReturnBorrowByID(string id)
        {
            int parsedID = 0;
            ValidationException exception = new ValidationException();

            using LibraryContext context = new LibraryContext();
            // Trim the values so we don't need to do it a bunch of times later.
            id = !(string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(id)) ? id.Trim() : null;

            if (string.IsNullOrWhiteSpace(id))
            {
                exception.ValidationExceptions.Add(new Exception("Can't find Book ID"));
            }
            else
            {
                // Book ID fails parse.
                if (!int.TryParse(id, out parsedID))
                {
                    exception.ValidationExceptions.Add(new Exception("Book ID Not Valid"));
                }
                else
                {
                    Book book = context.Books.Where(x => x.ID == parsedID).Include(x => x.Borrows).SingleOrDefault();
                    if (book == null)
                    {
                        exception.ValidationExceptions.Add(new Exception("Book Does Not Exist"));
                    }
                    else
                    {
                        if (!book.Borrows.Any())
                        {
                            exception.ValidationExceptions.Add(new Exception("Book has never been checked out"));
                        }
                        //if book is not returned, it can't be borrowed
                        else if (!book.Borrows.Any(x => x.ReturnedDate == null))
                        {
                            exception.ValidationExceptions.Add(new Exception("Book has not been checked out after last return"));
                        }
                        else if (book.Borrows.Where(x => x.ReturnedDate == null).SingleOrDefault().CheckedOutDate > DateTime.Today)
                        {
                            exception.ValidationExceptions.Add(new Exception("Return date can not be prior to CheckedOut Date"));
                        }
                    }
                }
            }
            if (exception.ValidationExceptions.Count > 0)
            {
                throw exception;
            }


            //Citation
            //https://github.com/dotnet/efcore/issues/19583
            //Above source suggested to break my query into 2 steps- storing result of Where clause query in a var and then applying LastorDefault() on it as apparently LastOrDefault() don't work on Dbset for avoiding unauthorized accesses
            //Note: I was getting exception when trying to do in one go- that Linq expression can't be translated to query
            var    listRequiredBorrow = context.Borrows.Where(borrow => borrow.BookID == parsedID).ToList();
            Borrow requiredBorrow     = listRequiredBorrow.LastOrDefault();

            //End Citation
            requiredBorrow.ReturnedDate = DateTime.Today;
            context.SaveChanges();
        }
コード例 #12
0
ファイル: UnitOfWork.cs プロジェクト: Glassgow666/Laba345
 public void Save()
 {
     db.SaveChanges();
 }
        public static void CreateBorrow(string id)
        {
            using LibraryContext context = new LibraryContext();

            int parsedID = 0;
            ValidationException exception = new ValidationException();

            // Trim the values so we don't need to do it a bunch of times later.
            id = !(string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(id)) ? id.Trim() : null;

            if (string.IsNullOrWhiteSpace(id))
            {
                exception.ValidationExceptions.Add(new Exception("Can't find Book ID"));
            }
            else
            {
                // Book ID fails parse.
                if (!int.TryParse(id, out parsedID))
                {
                    exception.ValidationExceptions.Add(new Exception("Book ID Not Valid"));
                }
                else
                {
                    Book book = context.Books.Where(x => x.ID == parsedID).Include(x => x.Borrows).SingleOrDefault();
                    if (book == null)
                    {
                        exception.ValidationExceptions.Add(new Exception("Book Does Not Exist"));
                    }
                    else if (book.Archived == true)
                    {
                        exception.ValidationExceptions.Add(new Exception("Cannot borrow archived book"));
                    }
                    else
                    {
                        if (book.Borrows.Any())
                        {
                            //if book is not returned, it can't be borrowed
                            if (book.Borrows.Any(x => x.ReturnedDate == null))
                            {
                                exception.ValidationExceptions.Add(new Exception("Book already checked out, It can't be borrowed again without returning it."));
                            }
                        }
                    }
                }
            }
            if (exception.ValidationExceptions.Count > 0)
            {
                throw exception;
            }

            Borrow newBorrow = new Borrow()
            {
                CheckedOutDate = DateTime.Today,
                DueDate        = DateTime.Today.AddDays(14),
                ReturnedDate   = null
            };

            newBorrow.BookID = parsedID;
            context.Borrows.Add(newBorrow);
            //context.Books.Where(book => book.ID == int.Parse(id)).Single().Borrows.Add(newBorrow);
            context.SaveChanges();
        }
        public static void ExtendDueDateForBorrowByID(string id)
        {
            int parsedID = 0;
            ValidationException exception = new ValidationException();

            using LibraryContext context = new LibraryContext();
            // Trim the values so we don't need to do it a bunch of times later.
            id = !(string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(id)) ? id.Trim() : null;

            if (string.IsNullOrWhiteSpace(id))
            {
                exception.ValidationExceptions.Add(new Exception("Can't find Book ID"));
            }
            else
            {
                // Book ID fails parse.
                if (!int.TryParse(id, out parsedID))
                {
                    exception.ValidationExceptions.Add(new Exception("Book ID Not Valid"));
                }
                else
                {
                    Book book = context.Books.Where(x => x.ID == parsedID).Include(x => x.Borrows).SingleOrDefault();
                    if (book == null)
                    {
                        exception.ValidationExceptions.Add(new Exception("Book Does Not Exist"));
                    }
                    else
                    {
                        if (!book.Borrows.Any())
                        {
                            exception.ValidationExceptions.Add(new Exception("Book has never been checked out"));
                        }
                        //if book is not returned, it can't be borrowed
                        else if (!book.Borrows.Any(x => x.ReturnedDate == null))
                        {
                            exception.ValidationExceptions.Add(new Exception("Book has not been checked out after last return"));
                        }

                        else if (book.Borrows.LastOrDefault(x => x.ReturnedDate == null).ExtensionCount > 2)
                        {
                            exception.ValidationExceptions.Add(new Exception("Sorry! Only 3 extensions are allowed! Please return the book."));
                        }
                        else
                        {
                            BookController bookController = new BookController();
                            if (bookController.GetOverdueBooks().Select(x => x.ID).Contains(parsedID))
                            {
                                exception.ValidationExceptions.Add(new Exception("Sorry! Overdue books can not be extended. Please return the book."));
                            }
                        }
                    }
                }
            }
            if (exception.ValidationExceptions.Count > 0)
            {
                throw exception;
            }

            var    listRequiredBorrow = context.Borrows.Where(borrow => borrow.BookID == int.Parse(id)).ToList();
            Borrow requiredBorrow     = listRequiredBorrow.LastOrDefault();

            requiredBorrow.DueDate         = requiredBorrow.DueDate.AddDays(7);
            requiredBorrow.ExtensionCount += 1;
            context.SaveChanges();
        }
コード例 #15
0
 public ActionResult Create(Publisher publish)
 {
     objContext.Publisher.Add(publish);
     objContext.SaveChanges();
     return(RedirectToAction("Index"));
 }
コード例 #16
0
        public void Add(Student studentToAdd)
        {
            _context.Students.Add(studentToAdd);

            _context.SaveChanges();
        }
コード例 #17
0
 public void AddBookToAuthor(Book book, Author author)
 {
     author.Books.Add(book);
     _context.SaveChanges();
 }
コード例 #18
0
 //adds a new dvd to the database
 public void CreateDVD(DVD dvd)
 {
     db.DVD.Add(dvd);
     db.SaveChanges();
 }
コード例 #19
0
        private LibraryContext GetContextWithData()
        {
            var options = new DbContextOptionsBuilder <LibraryContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            var context = new LibraryContext(options);

            context.Items.AddRange(ItemFactory.Get(new ItemInfo()
            {
                Author = "Test Author", Description = "A very good testing book", Title = "The best book"
            }, "978-3-16-148410-0"),
                                   ItemFactory.Get(new ItemInfo()
            {
                Author = "Test Author", Description = "A very good testing book", Title = "The best book"
            }, "978-3-16-148410-1"),
                                   ItemFactory.Get(new ItemInfo()
            {
                Author = "Test Author", Description = "A very good testing book", Title = "The best book"
            }, "978-3-16-148410-2"),
                                   ItemFactory.Get(new ItemInfo()
            {
                Author = "Test Author", Description = "A very good testing book", Title = "The best book"
            }),
                                   ItemFactory.Get(new ItemInfo()
            {
                Author = "Test Author", Description = "A very good testing book", Title = "The best book"
            }),
                                   ItemFactory.Get(new ItemInfo()
            {
                Author = "Test Author", Description = "A very good testing book", Title = "The best book"
            }));

            context.LoanRules.AddRange(new LoanRule()
            {
                Id = 1, LoanTime = 5, BookLimit = 5, GracePeriod = 20
            },
                                       new LoanRule()
            {
                Id = 2, LoanTime = 5, BookLimit = 5, GracePeriod = 20
            });

            context.Members.AddRange(MemberFactory.Get(new PersonAPI()
            {
                Address = "Address 1", Email = "*****@*****.**", Name = "Student 1", Password = "******", Phone = "1111111111", PictureId = "std1", Ssn = 112233446
            },
                                                       MemberEnum.Student),
                                     MemberFactory.Get(new PersonAPI()
            {
                Address = "Address 2", Email = "*****@*****.**", Name = "Student 2", Password = "******", Phone = "2222222222", PictureId = "std2", Ssn = 223344556
            },
                                                       MemberEnum.Student),
                                     MemberFactory.Get(new PersonAPI()
            {
                Address = "Address 4", Email = "*****@*****.**", Name = "Teacher 1", Password = "******", Phone = "4444444444", PictureId = "tch1", Ssn = 445566778
            },
                                                       MemberEnum.Teacher),
                                     MemberFactory.Get(new PersonAPI()
            {
                Address = "Address 5", Email = "*****@*****.**", Name = "Teacher 2", Password = "******", Phone = "5555555555", PictureId = "tch2", Ssn = 556677889
            },
                                                       MemberEnum.Teacher));

            context.SaveChanges();

            var items = context.Items.ToList();

            context.Loans.AddRange(new Loan(items[4].Id, 112233446), new Loan(items[1].Id, 112233446), new Loan(items[2].Id, 112233446), new Loan(items[3].Id, 112233446));
            context.SaveChanges();
            // Member 112233445 has 4 loans
            return(context);
        }
コード例 #20
0
 public void Add(Checkout newCheckout)
 {
     _context.Add(newCheckout);
     _context.SaveChanges();
 }
コード例 #21
0
 public void Add(LibraryBranch model)
 {
     _context.Add(model);
     _context.SaveChanges();
 }
コード例 #22
0
ファイル: BranchService.cs プロジェクト: karam-fikre/Library
 public void Add(LibraryBranch newBranch)
 {
     _context.Add(newBranch);
     _context.SaveChanges();
 }
コード例 #23
0
        public void CreateBook(string id, string title, string publicationDate, string authorID)
        {
            ValidationException exception = new ValidationException();

            id = id != null?id.Trim() : null;

            title = title != null?title.Trim().ToUpper() : null;

            authorID = authorID != null?authorID.Trim() : null;

            if (string.IsNullOrWhiteSpace(id))
            {
                exception.ValidationExceptions.Add(new Exception(" ID Not Provided"));
            }
            if (id.Length > 10)
            {
                exception.ValidationExceptions.Add(new Exception("The Book ID Cannot be more than length of 10 !"));
            }


            /**********************************************************
             * Will throw Exception if No Title Provided
             * *******************************************************/
            if (string.IsNullOrWhiteSpace(title))
            {
                exception.ValidationExceptions.Add(new Exception("Name Not Provided"));
            }

            /**********************************************************
             * Will throw Exception if Publication Date is in Future
             * *******************************************************/
            if (DateTime.Parse(publicationDate) > DateTime.Now)
            {
                exception.ValidationExceptions.Add(new Exception("Publication Date Cannot be in future!"));
            }


            using (LibraryContext context = new LibraryContext())
            {
                if (context.Books.Any(x => x.ID == int.Parse(id)))
                {
                    //IF ID Already Exists.
                    exception.ValidationExceptions.Add(new Exception("The ID you Provided already exists!"));
                }
                //IF TItle Already Exists to the Author.
                if (context.Books.Where(x => x.AuthorID == int.Parse(authorID)).Any(x => x.Title == title.Trim().ToUpper()))
                {
                    exception.ValidationExceptions.Add(new Exception("The Book Title already exists with that Author!"));
                }
                // if The Title of the Book exceeds its Charactor Limit!
                if (title.Length > 100)
                {
                    exception.ValidationExceptions.Add(new Exception("The Book Title Cannot be more than 100 Charectors!"));
                }



                if (exception.ValidationExceptions.Count > 0)
                {
                    throw exception;
                }
                context.Books.Add(new Book()
                {
                    ID              = int.Parse(id),
                    Title           = title.Trim().ToUpper(),
                    PublicationDate = DateTime.Parse(publicationDate),

                    AuthorID = int.Parse(authorID)
                });
                context.SaveChanges();
            }
        }
コード例 #24
0
 public int SaveChangesAsync()
 {
     return(_context.SaveChanges());
 }
コード例 #25
0
 public IActionResult CreateAuthor([FromBody] Author newAuthor)
 {
     context.Authors.Add(newAuthor);
     context.SaveChanges();
     return(Created("", newAuthor));
 }
コード例 #26
0
 public bool Save()
 {
     return(_context.SaveChanges() >= 0);
 }
コード例 #27
0
 //adds a new created book to the database
 public void CreateBook(Book book)
 {
     db.Books.Add(book);
     db.SaveChanges();
 }
コード例 #28
0
 public void Create(Book book)
 {
     _databaseLibraryContext.Books.Add(book);
     _databaseLibraryContext.SaveChanges();
 }
コード例 #29
0
 public void ReturnBook(int subscriptionId)
 {
     using (var context = new LibraryContext())
     {
         var original = context.InSubscriptions.Find(subscriptionId);
         original.ReturnDate = DateTime.Today.Date;
         original.IsInUse = false;
         var book = context.Books.First(x => x.ISBN == original.ISBN);
         book.Quantity += 1;
         context.SaveChanges();
     }
 }
コード例 #30
0
ファイル: FakeUnitOfWork.cs プロジェクト: Dandry/CityLibrary
 public void Save()
 {
     dummyContext.SaveChanges();
 }
コード例 #31
0
 public void DeleteBookByID(string id)
 {
     using LibraryContext context = new LibraryContext();
     context.Books.Remove(context.Books.Where(book => book.ID == int.Parse(id)).SingleOrDefault());
     context.SaveChanges();
 }
コード例 #32
0
 public void GiveBook(int subscriptionId)
 {
     using (var context = new LibraryContext())
     {
         var original = context.InSubscriptions.Find(subscriptionId);
         original.IsAccepted = true;
         context.SaveChanges();
     }
 }
コード例 #33
0
        static void Main(string[] args)
        {
            try
            {
                using (LibraryContext context = new LibraryContext())
                {
                    if (context.Database.Exists() == false)
                    {
                        Country country = new Country
                        {
                            CountryName = "Ukraine"
                        };
                        Author author = new Author
                        {
                            LastName  = "Lanskaya",
                            FirstName = "Natalina"
                        };
                        Book book = new Book
                        {
                            Title = "Proud and Money"
                        };
                        Publisher publisher = new Publisher
                        {
                            PublisherName = "Exotic"
                        };
                        //присоединили книгу для автора
                        author.Books.Add(book);
                        //записали в Базу Данну нашего автора
                        context.Authors.Add(author);
                        country.Authors.Add(author);

                        context.Countries.AddRange(
                            new List <Country>
                        {
                            country,
                            new Country  {
                                CountryName = "Litva"
                            }
                        });

                        publisher.Books.Add(book);
                        context.Publishers.Add(publisher);

                        /*
                         * //это мы все отправили в базу данных!
                         * // без этой строки ничего не зайдет в Базу данных
                         * context.SaveChanges();
                         */

                        //второй вариант
                        context.Books.Add(
                            new Book
                        {
                            Title      = "YYY",
                            Publishers = new List <Publisher>
                            {
                                new Publisher {
                                    PublisherName = "Ranok"
                                },
                                publisher
                            }
                        });
                        context.SaveChanges();

                        context.Authors.Add(
                            new Author
                        {
                            LastName  = "Moore",
                            FirstName = "Oliver",
                            Country   = context.Countries.First(c => c.CountryName == "Litva")
                        }
                            );

                        context.SaveChanges();
                        Author author1 = context.Authors.First(a => a.LastName == "Moore" && a.FirstName == "Oliver");
                        ((List <Book>)author1.Books).AddRange
                        (
                            new List <Book>
                        {
                            book,
                            context.Books.First(b => b.Title == "YYY")
                        });

                        context.SaveChanges();
                    }
                    if (context.Database.Exists())
                    {
                        foreach (Book book in context.Books.Include(b => b.Publishers).Include(b => b.Authors).ToList())
                        {
                            Console.Write(new string('\t', 2));
                            Console.WriteLine(book.Title);

                            foreach (Author author in book.Authors)
                            {
                                Console.Write(new string('\t', 3));

                                context.Entry(author).Reference("Country").Load();

                                Console.WriteLine(author + " " + author.Country.CountryName);
                            }

                            foreach (Publisher publ in book.Publishers)
                            {
                                Console.Write(new string('\t', 4));
                                Console.WriteLine(publ.PublisherName);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #34
0
 public void AddLoan(Loan loanToAdd)
 {
     _context.Loans.Add(loanToAdd);
     _context.SaveChanges();
 }
コード例 #35
0
 public Author AddAuthor(Author author)
 {
     _libraryContext.Authors.Add(author);
     _libraryContext.SaveChanges();
     return(author);
 }
コード例 #36
0
 public void EditBook(Book book)
 {
     using (var context = new LibraryContext())
     {
         var original = context.Books.Find(book.ISBN);
         context.Entry(original).CurrentValues.SetValues(book);
         context.SaveChanges();
     }
 }
コード例 #37
0
 public int Put(Book book)
 {
     context.Update(book);
     return(context.SaveChanges());
 }