Esempio n. 1
0
        public async Task <IActionResult> PutBookCategory([FromRoute] long id, [FromBody] BookCategory bookCategory)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != bookCategory.Id)
            {
                return(BadRequest());
            }

            _context.Entry(bookCategory).State = EntityState.Modified;

            try
            {
                _context.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookCategoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 2
0
 public Book(string bookName, BookCategory category, string coverImg, string mediaFile)
 {
     this.BookName  = bookName;
     this.CoverImg  = coverImg;
     this.Category  = category;
     this.MediaFile = mediaFile;
 }
Esempio n. 3
0
        public async Task <IActionResult> Edit(int id, [Bind("BookCategoryId,BookId,CategoryId")] BookCategory bookCategory)
        {
            if (id != bookCategory.CategoryId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(bookCategory);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BookCategoryExists(bookCategory.CategoryId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["BookId"]     = new SelectList(_context.Books, "BookId", "BookId", bookCategory.BookId);
            ViewData["CategoryId"] = new SelectList(_context.Categories, "CategoryId", "CategoryId", bookCategory.CategoryId);
            return(View(bookCategory));
        }
Esempio n. 4
0
 public Book(string Author, BookCategory Genre, string Edition, string Name, int CopyNumber, DateTime PrintDate, double Price)
     : base(Name, CopyNumber, PrintDate, Price)
 {
     this.Edition = Edition;
     this.Genre   = Genre;
     this.Author  = Author;
 }
Esempio n. 5
0
 public Book( String title, String author, BookCategory category, bool available )
 {
     this.title = title;
     this.author = author;
     this.category = category;
     this.available = available;
 }
Esempio n. 6
0
 public Book(string author, DateTime since, string title, BookCategory category)
 {
     Author   = author ?? throw new ArgumentNullException(paramName: nameof(author));
     Since    = since;
     Title    = title ?? throw new ArgumentNullException(paramName: nameof(title));
     Category = category;
 }
Esempio n. 7
0
 public void DeleteBookCategory(BookCategory BookCategory)
 {
     context.Database.ExecuteSqlCommand(
         "exec DeleteBookCategory @ID",
         new SqlParameter("ID", BookCategory.ID)
         );
 }
Esempio n. 8
0
        public async Task <ActionResult <BookCategory> > PostBookCategory(BookCategory bookCategory)
        {
            _context.BookCategories.Add(bookCategory);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBookCategory", new { id = bookCategory.Id }, bookCategory));
        }
        public async Task <object> Handle(DeleteCategoryAdminCommand request, CancellationToken cancellationToken)
        {
            var entity = await _context.Categories.Include(c => c.BookCategories).
                         Where(c => c.Id == request.Id && c.Id != 1).FirstOrDefaultAsync(cancellationToken);

            if (entity == null)
            {
                return(null);
            }
            if (entity.BookCategories.Count() != 0)
            {
                _context.BookCategories.RemoveRange(entity.BookCategories);
            }
            foreach (var iterm in entity.BookCategories)
            {
                var testIdCategory = await _context.BookCategories
                                     .SingleOrDefaultAsync(u => u.CategoryId == 1 && u.BookId == iterm.BookId, cancellationToken);

                if (testIdCategory == null)
                {
                    var bookCategory = new BookCategory
                    {
                        CategoryId = 1,
                        BookId     = iterm.BookId
                    };
                    _context.BookCategories.Add(bookCategory);
                }
            }
            _context.Categories.Remove(entity);
            await _context.SaveChangesAsync(cancellationToken);

            return(entity);
        }
Esempio n. 10
0
        // GET: Books
        public async Task <IActionResult> Index(string bookcategory, string searchstr, string Publisherssear)
        {
            IQueryable <string> categoryquery = from b in _context.Books
                                                orderby b.Category
                                                select b.Category;

            var books = from b in _context.Books
                        select b;

            IQueryable <string> publisherquery = from b in _context.Books
                                                 orderby b.Publisher
                                                 select b.Publisher;

            if (!String.IsNullOrEmpty(searchstr))
            {
                books = books.Where(b => b.Btitle.Contains(searchstr));
            }
            if (!String.IsNullOrEmpty(bookcategory))
            {
                books = books.Where(x => x.Category == bookcategory);
            }
            if (!string.IsNullOrEmpty(Publisherssear))
            {
                books = books.Where(b => b.Publisher == Publisherssear);
            }
            var bookcategoryVM = new BookCategory
            {
                Categories = new SelectList(await categoryquery.Distinct().ToListAsync()),
                Books      = await books.ToListAsync(),
                Publishers = new SelectList(await publisherquery.Distinct().ToListAsync())
            };

            return(View(bookcategoryVM));
            //return View(await _context.Books.ToListAsync());
        }
Esempio n. 11
0
        public bool CreateBook(List <int> authorsId, List <int> categoriesId, Book book)
        {
            var authors    = _bookContext.Authors.Where(a => authorsId.Contains(a.Id)).ToList();
            var categories = _bookContext.Categories.Where(a => categoriesId.Contains(a.Id)).ToList();

            foreach (var author in authors)
            {
                var bookAuthor = new BookAuthor()
                {
                    Author = author,
                    Book   = book
                };
                _bookContext.Add(bookAuthor);
            }
            foreach (var category in categories)
            {
                var bookCategory = new BookCategory()
                {
                    Category = category,
                    Book     = book
                };
                _bookContext.Add(bookCategory);
            }

            _bookContext.Add(book);

            return(Save());
        }
Esempio n. 12
0
        public ActionResult AddCategory(BookCategory category)
        {
            db.BookCategory.Add(category);
            db.SaveChanges();

            return(Json(new { Message = "OK" }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 13
0
        public bool Delete(long?id)
        {
            try
            {
                BookCategory category = db.BookCategories.Find(id);

                if (category == null)
                {
                    return(false);
                }
                foreach (BookCategory item in db.BookCategories)
                {
                    if (item.ParentID == category.ID)
                    {
                        item.ParentID = null;
                    }
                }

                db.BookCategories.Remove(category);
                db.SaveChanges();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 14
0
        public bool CreateBook(List <int> authorsId, List <int> categoriesId, Book book)
        {
            var authors    = _bookDbContext.Authors.Where(a => authorsId.Contains(a.Id)).ToList();
            var categories = _bookDbContext.Categories.Where(c => categoriesId.Contains(c.Id)).ToList();

            foreach (var author in authors)
            {
                var bookAuthor = new BookAuthor()
                {
                    Author = author,
                    Book   = book
                };
                _bookDbContext.Add(bookAuthor);
                // We could also create List<BookAuthor> and add all bookAuthor objects to it,
                // and then use AddRange on the DbContext to add it all at once. Either way is fine.
            }

            foreach (var category in categories)
            {
                var bookCategory = new BookCategory()
                {
                    Category = category,
                    Book     = book
                };
                _bookDbContext.Add(bookCategory);
            }

            _bookDbContext.Add(book);

            return(Save());
        }
Esempio n. 15
0
        public bool UpdateBook(List <int> authorId, List <int> categorieId, Book book)
        {
            var authors    = _bookDBContext.Authors.Where(a => authorId.Contains(a.Id)).ToList();
            var categories = _bookDBContext.Categories.Where(c => categorieId.Contains(c.Id)).ToList();

            var bookauthortodelete   = _bookDBContext.BookAuthors.Where(b => b.BookId == book.Id);
            var bookcategorytodelete = _bookDBContext.BookCategories.Where(c => c.BookId == book.Id);

            _bookDBContext.RemoveRange(bookauthortodelete);
            _bookDBContext.RemoveRange(bookcategorytodelete);

            foreach (var a in authors)
            {
                var bookauthor = new BookAuthor
                {
                    Author = a,
                    Book   = book
                };
            }

            foreach (var c in categories)
            {
                var bookcategories = new BookCategory
                {
                    Category = c,
                    Book     = book
                };
            }

            _bookDBContext.Update(book);

            return(Save());
        }
Esempio n. 16
0
        public ActionResult UpdateBookCategory(BookCategory model)
        {
            if (ModelState.IsValid)
            {
                var dao = new BookCategoryDAO();
                //Kiểm tra xem tên loại sách này đã có chưa
                var exist = dao.BookCategoryExistForUpdate(model.Name, model.ID);
                if (!exist)
                {
                    UserLogin userlogin = (UserLogin)Session["USER_SESSION"];
                    model.ModifiedBy = userlogin.UserName;
                    string metatitle = CastString.Cast(model.Name);
                    model.MetaTitle = metatitle;
                    bool result = dao.UpdateBookCategory(model);
                    if (result)
                    {
                        SetAltert("Update loại sách thành công", 0);
                        return(RedirectToAction("Index", "BookCategory"));
                    }
                    else
                    {
                        SetAltert("Chưa cập nhật được", 2);
                    }
                }
                else
                {
                    SetAltert("Tên loại sách này đã có", 2);
                }
            }
            else
            {
            }

            return(View(model));
        }
Esempio n. 17
0
        public void EditBookDetailsTest()
        {
            var faker           = new Faker();
            var author          = new Author(FullName.Create(faker.Name.FirstName(), faker.Name.LastName()).Value);
            var bookCategory    = BookCategory.Create(CategoryBook.Business, faker.Lorem.Text()).Value;
            var bookDescription = BookDescription
                                  .Create(faker.Lorem.Text(), faker.Date.Random.Number(1, DateTime.Now.Year)).Value;
            var bookIsbn = Isbn.Create(TypeIsbn.Isbn10, "ISBN 1-58182-008-9").Value;
            var book     = new Books(author, bookCategory, bookDescription, bookIsbn);
            var oldId    = book.BookId.Value;

            Assert.NotNull(book);
            var newAuthor          = new Author(FullName.Create(faker.Name.FirstName(), faker.Name.LastName()).Value);
            var newBookCategory    = BookCategory.Create(CategoryBook.Business, faker.Lorem.Text()).Value;
            var newBookDescription = BookDescription
                                     .Create(faker.Lorem.Text(), faker.Date.Random.Number(1, DateTime.Now.Year)).Value;
            var newBookIsbn = Isbn.Create(TypeIsbn.Isbn10, "ISBN 1-55182-008-9").Value;

            book.EditBookDetails(newAuthor, newBookCategory, newBookDescription, newBookIsbn);
            Assert.NotEqual(book.Author.FullName.SureName, author.FullName.Name);
            Assert.NotEqual(book.Author.FullName.SureName, author.FullName.Name);
            Assert.NotEqual(book.BookCategory.CategoryName, bookCategory.CategoryName);
            Assert.NotEqual(book.BookDescription.Title, bookDescription.Title);
            Assert.NotEqual(book.BookDescription.Year, bookDescription.Year);
            Assert.NotEqual(book.Isbn.IsbnCode, bookIsbn.IsbnCode);
            Assert.Equal(oldId, book.BookId.Value);
        }
        public void Add_add_borrowed_book_properly()
        {
            //Arrange
            BookCategory category = BorrowedBookFactory.GenerateDummyBookCategory();

            context.Manipulate(_ => _.BookCategories.Add(category));
            Writer writer = BorrowedBookFactory.GenerateDummyWriter();

            context.Manipulate(_ => _.Writers.Add(writer));
            Book book = BorrowedBookFactory.GenerateDummyBook();

            book.CategoryId = category.Id;
            book.WriterId   = writer.Id;
            context.Manipulate(_ => _.Books.Add(book));
            Member member = BorrowedBookFactory.GenerateDummyMember();

            context.Manipulate(_ => _.Members.Add(member));
            AddBorrowedBookDto dto = new AddBorrowedBookDto()
            {
                MemberAge    = member.Age,
                BookTitle    = book.Title,
                BookAgeRange = book.AgeRange,
            };

            //Act
            sut.Add(dto);

            //Assert
            var expected = readContext.BorrowedBooks.Single(_ => _.Title == dto.BookTitle);

            expected.Title.Should().Be(dto.BookTitle);
            expected.ReturnDate.Should().BeAfter(DateTime.Now);
        }
        public ActionResult Details(int id)
        {
            BookCategory caty = _context.BookCategories.Where(x => x.BookCategoryId == id).SingleOrDefault();

            _context.SaveChanges();
            return(View(caty));
        }
Esempio n. 20
0
        public async Task <IActionResult> PutBookCategory(int id, BookCategory bookCategory)
        {
            if (id != bookCategory.Id)
            {
                return(BadRequest());
            }

            _context.Entry(bookCategory).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookCategoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync(string[] selectedCategories)
        {
            var newBook = new Book();

            if (selectedCategories != null)
            {
                newBook.BookCategories = new List <BookCategory>();
                foreach (var cat in selectedCategories)
                {
                    var catToAdd = new BookCategory
                    {
                        CategoryID = int.Parse(cat)
                    };
                    newBook.BookCategories.Add(catToAdd);
                }
            }
            if (await TryUpdateModelAsync <Book>(
                    newBook,
                    "Book",
                    i => i.Title, i => i.Author,
                    i => i.Price, i => i.PublishingDate, i => i.PublisherID))
            {
                _context.Book.Add(newBook);
                await _context.SaveChangesAsync();

                return(RedirectToPage("./Index"));
            }
            PopulateAssignedCategoryData(_context, newBook);
            return(Page());
        }
Esempio n. 22
0
 public Book(string bookName, BookCategory category, string coverImg, string mediaFile)
 {
     this.BookName = bookName;
     this.CoverImg = coverImg;
     this.Category = category;
     this.MediaFile = mediaFile;
 }
Esempio n. 23
0
        public bool UpdateBook(List <int> authorsId, List <int> categoriesId, Book book)
        {
            var authors    = _bookDbContext.Authors.Where(a => authorsId.Contains(a.Id)).ToList();
            var categories = _bookDbContext.Categories.Where(c => categoriesId.Contains(c.Id)).ToList();

            var bookAuthorsToDelete    = _bookDbContext.BookAuthors.Where(b => b.BookId == book.Id);    // here it's selected the BookId and the AuthorId from BookAuthors;
            var bookCategoriesToDelete = _bookDbContext.BookCategories.Where(b => b.BookId == book.Id); // here it's selected the BookId and the CategoryId from BookCategories;

            _bookDbContext.RemoveRange(bookAuthorsToDelete);
            _bookDbContext.RemoveRange(bookCategoriesToDelete);

            foreach (var author in authors)
            {
                var bookAuthor = new BookAuthor()
                {
                    Author = author,
                    Book   = book
                };
                _bookDbContext.Add(bookAuthor);
            }

            foreach (var category in categories)
            {
                var bookCategory = new BookCategory()
                {
                    Category = category,
                    Book     = book
                };
                _bookDbContext.Add(bookCategory);
            }

            _bookDbContext.Update(book);

            return(Save());
        }
Esempio n. 24
0
        public bool CreateBook(List <int> authorsId, List <int> categoiesId, Book book)
        {
            //Get all the Author object from the list of authorsId passed
            var authors = _bookDbContext.Authors.Where(a => authorsId.Contains(a.Id)).ToList();

            //Get all the Category object from the list of categoriesId passed
            var categories = _bookDbContext.Categories.Where(a => categoiesId.Contains(a.Id)).ToList();

            //Looping through Author object list and populating the BookAuthor table
            foreach (var a in authors)
            {
                var bookAuthor = new BookAuthor()
                {
                    Author = a,
                    Book   = book
                };
                _bookDbContext.Add(bookAuthor);
            }

            //Looping through Category object list and populating the BookCategory table
            foreach (var c in categories)
            {
                var bookCategory = new BookCategory()
                {
                    Category = c,
                    Book     = book
                };
                _bookDbContext.Add(bookCategory);
            }

            //Populating to Books table
            _bookDbContext.Books.Add(book);

            return(Save());
        }
        public void Delete_delete_borrowed_book_properly()
        {
            //Arrange
            BookCategory category = BorrowedBookFactory.GenerateDummyBookCategory();

            context.Manipulate(_ => _.BookCategories.Add(category));
            Writer writer = BorrowedBookFactory.GenerateDummyWriter();

            context.Manipulate(_ => _.Writers.Add(writer));
            Book book = BorrowedBookFactory.GenerateDummyBook();

            book.CategoryId = category.Id;
            book.WriterId   = writer.Id;
            context.Manipulate(_ => _.Books.Add(book));
            Member member = BorrowedBookFactory.GenerateDummyMember();

            context.Manipulate(_ => _.Members.Add(member));
            BorrowedBook borrowedBook = new BorrowedBook()
            {
                Title      = book.Title,
                ReturnDate = DateTime.Parse("02/02/2022")
            };

            context.Manipulate(_ => _.BorrowedBooks.Add(borrowedBook));

            //Act
            sut.Delete(borrowedBook.Id);

            //Assert
            var expected = readContext.BorrowedBooks.FirstOrDefault(_ => _.Id == borrowedBook.Id);

            expected.Should().BeNull();
        }
Esempio n. 26
0
        public JsonResult saveData(string categoryStr, HttpPostedFileBase file)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            BookCategory category = serializer.Deserialize <BookCategory>(categoryStr);

            bool status = false;

            if (file != null)
            {
                category.Image = imgHelper.saveImage(file);
            }

            if (category.ID == 0)
            {
                status = new BookCategoryDAO().insert(category);
            }
            else
            {
                status = new BookCategoryDAO().update(category);
            }

            setViewBagForCategory();

            return(Json(new
            {
                status = status
            }));
        }
Esempio n. 27
0
 public void AddBookCategory(BookCategory bookCategory)
 {
     try
     {
         // check book category code isExist
         BookCategory bc = _context.BookCategory
                           .Where(bc => bc.BookCategoryCode == bookCategory.BookCategoryCode).FirstOrDefault();
         if (bc == null)
         {
             _bookCategoryDAL.AddBookCategory(bookCategory);
         }
         else
         {
             throw new Exception("Mã loại sách đã tồn tại");
         }
     }
     catch (Exception ex)
     {
         if (ex.Message.Contains("Mã loại sách đã tồn tại"))
         {
             throw new Exception(ex.Message.ToString());
         }
         else
         {
             throw new Exception("Error from BookCategoryBLL: " + ex.Message.ToString());
         }
     }
 }
Esempio n. 28
0
        public bool CreateBook(List <int> authorId, List <int> categorieId, Book book)
        {
            var authors    = _bookDBContext.Authors.Where(a => authorId.Contains(a.Id)).ToList();
            var categories = _bookDBContext.Categories.Where(c => categorieId.Contains(c.Id)).ToList();

            foreach (var a in authors)
            {
                var bookauthor = new BookAuthor
                {
                    Author = a,
                    Book   = book
                };
            }

            foreach (var c in categories)
            {
                var bookcategories = new BookCategory
                {
                    Category = c,
                    Book     = book
                };
            }

            _bookDBContext.Add(book);

            return(Save());
        }
Esempio n. 29
0
 public void EditBookCategory(int id, BookCategory newBookCategory)
 {
     try
     {
         // check book category code isExist
         BookCategory bc = _context.BookCategory
                           .Where(bc => bc.BookCategoryCode == newBookCategory.BookCategoryCode &&
                                  bc.Id != newBookCategory.Id).FirstOrDefault();
         if (bc == null)
         {
             BookCategory oldBookCategory = _context.BookCategory.Where(us => us.Id == id).SingleOrDefault();
             _bookCategoryDAL.EditBookCategory(oldBookCategory, newBookCategory);
         }
         else
         {
             throw new Exception("Mã loại sách đã tồn tại");
         }
     }
     catch (Exception ex)
     {
         if (ex.Message.Contains("Mã loại sách đã tồn tại"))
         {
             throw new Exception(ex.Message.ToString());
         }
         else
         {
             throw new Exception("Error from BookCategoryBLL: " + ex.Message.ToString());
         }
     }
 }
Esempio n. 30
0
        public void AddCategories(BookDetailDTO book, long bookCreatedId)
        {
            book.BookCategories.ForEach(c =>
            {
                long catId = 0;

                if (c.Id > 0)
                {
                    catId = c.Id;
                }
                else
                {
                    var newCategory = new Category {
                        CategoryDescription = c.CategoryDescription
                    };
                    _context.Category.Add(newCategory);
                    _context.SaveChanges();
                    catId = newCategory.Id;
                }
                var bookCategory = new BookCategory {
                    BookId = bookCreatedId, CategoryId = catId
                };
                _context.BookCategory.Add(bookCategory);
                _context.SaveChanges();
            });
        }
Esempio n. 31
0
        public async Task <ResponseModel> CreateBookCategoryAsync(BookCategoryManageModel bookCategoryManageModel)
        {
            var bookCategory = await _repository.FetchFirstAsync(x => x.Name == bookCategoryManageModel.Name);

            if (bookCategory != null)
            {
                return(new ResponseModel
                {
                    StatusCode = System.Net.HttpStatusCode.BadRequest,
                    Message = "This BookCategory is exist"
                });
            }
            else
            {
                bookCategory = new BookCategory();
                bookCategoryManageModel.GetBookCategoryFromModel(bookCategory);
                await _repository.InsertAsync(bookCategory);

                return(new ResponseModel
                {
                    StatusCode = System.Net.HttpStatusCode.OK,
                    Data = new BookCategoryViewModel(bookCategory),
                });
            }
        }
Esempio n. 32
0
 public bool Update(BookCategory category)
 {
     try
     {
         BookCategory categoryy = db.BookCategories.Find(category.ID);
         categoryy.Name = category.Name;
         if (category.ParentID != -100)
         {
             categoryy.ParentID = category.ParentID;
             BookCategory child = getBookCategoryByID((long)category.ParentID);
             if (child.ParentID == category.ID)
             {
                 child.ParentID = null;
             }
         }
         else
         {
             categoryy.ParentID = null;
         }
         categoryy.DisplayOrder = category.DisplayOrder;
         categoryy.Status       = category.Status;
         db.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Esempio n. 33
0
 public ActionResult Delete(int BookCategoryID)
 {
     myHandler = new BusinessLogicHandler();
     typeOf = new BookCategory();
     typeOf.BookCategoryID = BookCategoryID;
     typeOf = myHandler.GetBookCategory(BookCategoryID);
     return View(typeOf);
 }
Esempio n. 34
0
 public Book(String isbn, String author, String title, BookCategory category, Int32 count)
 {
     this.isbn = isbn;
     this.title = title;
     this.author = author;
     this.category = category;
     this.availableCount = count;
 }
Esempio n. 35
0
        static void Main(string[] args)
        {
            BookCategory cat = new BookCategory();

            Publisher publish1 = new Publisher { Nom = "Casterman" };
            Author author1 = new Author { Name = "Rowling", FirstName = "Johannes" };
            Book livre1 = new Book { Title = "C#", Lang = "FR-fr", NbPage = 450,Cat=BookCategory.SF };

            livre1.addAuthor(author1, 0);
        }
Esempio n. 36
0
        public static void AddCategory(string name)
        {
            Catalog catalog = new Catalog();

            BookCategory cat = new BookCategory();
            cat.Name = name;

            catalog.BookCategories.InsertOnSubmit(cat);
            catalog.SubmitChanges();
        }
Esempio n. 37
0
 public void addBook(String isbn, String author, String title, BookCategory category, Int32 count)
 {
     if (!this.books.ContainsKey(isbn))
     {
         this.addBook(new Book(isbn, author, title, category, count));
     }
     else
     {
         throw new BookAlreadyExistsException("The ISBN number is already exists (" + isbn + ").");
     }
 }
Esempio n. 38
0
 public static IBook NewBook(this IEntitySession session, BookEdition editions, BookCategory category, string title, string description,
     IPublisher publisher, DateTime? publishedOn, decimal price, IImage coverImage = null)
 {
     var book = session.NewEntity<IBook>();
       book.Editions = editions;
       book.Category = category;
       book.Title = title;
       book.Description = description;
       book.Publisher = publisher;
       book.PublishedOn = publishedOn;
       book.Price = price;
       book.CoverImage = coverImage;
       return book;
 }
Esempio n. 39
0
        public ActionResult Delete(int BookCategoryID, FormCollection collection)
        {
            try
            {
                myHandler = new BusinessLogicHandler();
                typeOf = new BookCategory();
                typeOf.BookCategoryID = BookCategoryID;
                myHandler.DeleteBookType(BookCategoryID);

                TempData["Alert Message"] = "Device Successfully Deleted";
                return RedirectToAction("Index", "BookType");
            }
            catch
            {
                return View();
            }
        }
Esempio n. 40
0
 public ActionResult Create(FormCollection collection)
 {
     try
     {
         myHandler = new BusinessLogicHandler();
         typeOf = new BookCategory();
         TryUpdateModel(typeOf);
         if (ModelState.IsValid)
         {
             myHandler.AddBookType(typeOf);
             return RedirectToAction("Index");
         }
         return View();
     }
     catch
     {
         return View();
     }
 }
Esempio n. 41
0
 private void ImportBooksInCategory(BookCategory category, string keyword, int count)
 {
     var skip = 0;
       var currentCount = 0;
       while(currentCount < count) {
     var volumeSet = _client.GetVolumes(keyword, skip);
     skip += volumeSet.Items.Count;
     foreach (var volume in volumeSet.Items) {
       var vinfo = volume.VolumeInfo;
       if (string.IsNullOrWhiteSpace(vinfo.Publisher)) //some books don't have publisher, just skip these
     continue;
       var title = Trim(vinfo.Title, 120);
       if (_bookCache.ContainsKey(title))
     continue;
       currentCount++;
       var ipub = GetCreatePublisher(vinfo.Publisher);
       var pubDate = ParsePublishedDate(vinfo.PublishedDate);
       var image = LoadImageFromUrl(vinfo.ImageLinks.Thumbnail);
       var price = GetPrice(volume.SaleInfo);
       var ibook = _session.NewBook(BookEdition.Paperback, category, title, vinfo.SubTitle, ipub, pubDate, price, coverImage: image);
       ibook.Abstract = vinfo.Description;
       _bookCache.Add(vinfo.Title, ibook);
       //parse authors
       if (vinfo.Authors != null)
     foreach (var author in vinfo.Authors) {
       var iauth = GetCreateAuthor(author);
       if (iauth != null)
         ibook.Authors.Add(iauth);
     }
     }//foreach volume
       }
       try {
     _session.SaveChanges();
       } catch (Exception ex) {
     System.Diagnostics.Debug.WriteLine("Exception: " + ex.ToLogString());
     throw;
       }
 }
Esempio n. 42
0
        public ActionResult Edit(int id)
        {
            myHandler = new BusinessLogicHandler();
            typeOf = new BookCategory();

            typeOf = myHandler.GetBookCategoryList().Single(tlist => tlist.BookCategoryID == id);

            return View(typeOf);
        }
Esempio n. 43
0
 public ActionResult Edit(BookCategory bc)
 {
     try
     {
         myHandler = new BusinessLogicHandler();
         typeOf = new BookCategory();
         TryUpdateModel(bc);
         if (ModelState.IsValid)
         {
             myHandler.UpdateBookType(bc);
         }
         return RedirectToAction("Index");
     }
     catch
     {
         return View();
     }
 }
Esempio n. 44
0
 public ActionResult ViewBookCategory(BookCategory bookCategory)
 {
     myHandler = new BusinessLogicHandler();
     if (ModelState.IsValid)
     {
         myHandler.AddBookType(bookCategory);
     }
     return Json(new { success = true });
 }
Esempio n. 45
0
 public int IndexOf(BookCategory entity)
 {
     return base.IndexOf(entity);
 }
Esempio n. 46
0
 public bool Contains(BookCategory entity)
 {
     return base.Contains(entity);
 }
Esempio n. 47
0
        public void ORM_LinqQuery_WhereChildren_Any_SectionAndOwner()
        {
            var repo = RF.Concrete<BookRepository>();
            using (RF.TransactionScope(repo))
            {
                var so = new SectionOwner { Name = "huqf" };
                RF.Save(so);
                var category = new BookCategory { Name = "category" };
                RF.Save(category);

                repo.Save(new Book
                {
                    Name = "1",
                    BookCategory = category,
                    ChapterList =
                    {
                        new Chapter
                        {
                            SectionList =
                            {
                                new Section { Name = "need", SectionOwner = so }
                            }
                        },
                    }
                });
                repo.Save(new Book
                {
                    Name = "2",
                    BookCategory = category,
                    ChapterList =
                    {
                        new Chapter
                        {
                            SectionList =
                            {
                                new Section { Name = "need too" }// sectionOwner not match
                            }
                        },
                    }
                });
                repo.Save(new Book
                {
                    Name = "3",
                    //BookCategory = category,// not match
                    ChapterList =
                    {
                        new Chapter
                        {
                            SectionList =
                            {
                                new Section { Name = "need", SectionOwner = so }
                            }
                        },
                    }
                });
                repo.Save(new Book
                {
                    Name = "4",
                    ChapterList =
                    {
                        new Chapter
                        {
                            SectionList =
                            {
                                new Section { Name = "not contained" }//section name not match.
                            }
                        },
                    }
                });

                var list = repo.LinqGetIfChildrenExistsSectionAndOwner(category.Name, "need", so.Name);
                Assert.IsTrue(list.Count == 1);
                Assert.IsTrue(list[0].Name == "1");
            }
        }
Esempio n. 48
0
        public ActionResult CustomerDetails(int ProductID)
        {
            #region Prep Utilities

            myHandler = new BusinessLogicHandler();
            AddNewBookViewModel model = new AddNewBookViewModel();
            book = new Book();
            BookCategory category = new BookCategory();
            Publisher pub = new Publisher();
            Author authors = new Author();

            #endregion

            #region Check Type
            if (myHandler.CheckProductType(ProductID))
            { }
            else
            { return RedirectToAction("Details","Technology", new { ProductID = ProductID }); }
            #endregion

            #region Get Book Data

            book = myHandler.User_GetBook(ProductID);
            model.books = new Book();
            model.books = book;
            model.bookList = new List<Book>();
            model.bookList.Add(book);

            #endregion

            #region Get Book Category Data

            category = myHandler.GetBookType(book.BookCategoryID);
            model.bc = new BookCategory();
            model.bc = category;
            model.bookCategoryList = new List<BookCategory>();
            model.bookCategoryList.Add(category);

            #endregion

            #region Get Publisher Data

            pub = myHandler.GetPublisher(book.PublisherID);
            model.publisher = new Publisher();
            model.publisher = pub;
            model.PublisherList = new List<Publisher>();
            model.PublisherList.Add(pub);

            #endregion

            #region Get Authors Data

            model.AuthorList = myHandler.GetAuthorsPerBook(book.BookID);

            #endregion

            return View(model);
        }
Esempio n. 49
0
 public void Insert(int index, BookCategory entity)
 {
     base.Insert(index, entity);
 }
Esempio n. 50
0
        public void ET_Property_LazyRef_SetId()
        {
            var repo = RF.Concrete<BookRepository>();
            using (RF.TransactionScope(repo))
            {
                var bc = new BookCategory
                {
                    Name = "bc1"
                };
                RF.Save(bc);

                var book = new Book { BookCategoryId = bc.Id };
                Assert.IsTrue(book.BookCategory.Name == bc.Name);

                book.BookCategoryId = null;
                Assert.IsTrue(book.BookCategory == null);
            }
        }
Esempio n. 51
0
        public void ET_Validation_NotUsedByReferenceRule_EntityStatusScope_Delete()
        {
            var repo = RF.Concrete<BookCategoryRepository>();
            using (RF.TransactionScope(repo))
            {
                var cate = new BookCategory { Code = "01" };
                repo.Save(cate);

                var book = new Book { BookCategory = cate };
                RF.Save(book);

                var rules = cate.Validate();
                Assert.IsTrue(rules.Count == 0);

                cate.PersistenceStatus = PersistenceStatus.Deleted;
                rules = cate.Validate();
                Assert.IsTrue(rules.Count == 1);
                Assert.IsTrue(rules[0].Rule.ValidationRule is NotUsedByReferenceRule);
            }
        }
Esempio n. 52
0
 public ActionResult Details(int id)
 {
     myHandler = new BusinessLogicHandler();
     typeOf = myHandler.GetBookCategoryList().Single(typ => typ.BookCategoryID == id);
     return View(typeOf);
 }
Esempio n. 53
0
        static void Main(string[] args)
        {
            var rand = new Random();

            Console.WriteLine("Check DB exists...");
            if (Database.Exists("BookStoreDb"))
            {
                Console.WriteLine("DB exists. Deleting...");
                Database.Delete("BookStoreDb");
            }
            else
            {
                Console.WriteLine("DB does not exist. Skip deleting.");
            }

            using (var db = new Db())
            {
                Console.WriteLine("Creating DB..");
                object tmp = db.Users.ToArray();

                Console.WriteLine("Branches..");
                var br1 = new Branch()
                {
                    Address = "Mira prospect, 11 - 21",
                    Name = "Booko na Mira"
                };

                var br2 = new Branch()
                {
                    Address = "Ulica Vzletnaya, 22",
                    Name = "Booko na Vzletke"
                };

                db.Branches.Add(br1);
                db.Branches.Add(br2);
                db.SaveChanges();

                Console.WriteLine("Creating employees and users..");
                var admin = new Employee
                {
                    Branch = br1,
                    FirstName = "Admin",
                    MiddleName = "Admin",
                    LastName = "Admin",
                    User = new User()
                    {
                        LastLoginTime = DateTime.Now,
                        Login = "******",
                        Password = PasswordManager.CreateHash("admin"),
                        Role = Role.Admin
                    }
                };

                var ivanov = new Employee
                {
                    Branch = br1,
                    FirstName = "Ivan",
                    MiddleName = "Ivanovich",
                    LastName = "Ivanov",
                    User = new User()
                    {
                        LastLoginTime = DateTime.Now,
                        Login = "******",
                        Password = PasswordManager.CreateHash("iii"),
                        Role = Role.User
                    }
                };

                var petrov = new Employee
                {
                    Branch = br2,
                    FirstName = "Petr",
                    MiddleName = "Petrovich",
                    LastName = "Petrov",
                    User = new User()
                    {
                        LastLoginTime = DateTime.Now,
                        Login = "******",
                        Password = PasswordManager.CreateHash("ppp"),
                        Role = Role.User
                    }
                };

                var sidorov = new Employee
                {
                    Branch = br2,
                    FirstName = "Sidor",
                    MiddleName = "Sidorovich",
                    LastName = "Sidorov",
                    User = null
                };

                db.Employees.Add(admin);
                db.Employees.Add(ivanov);
                db.Employees.Add(petrov);
                db.Employees.Add(sidorov);
                db.SaveChanges();

                Console.WriteLine("Customers..");

                var customers = JsonConvert.DeserializeObject<List<Customer>>(File.ReadAllText("Customers.json"));
                customers.ForEach(c => db.Customers.Add(c));
                db.SaveChanges();

                Console.WriteLine("Book categories..");
                var fantasy = new BookCategory { Name = "Fantasy" };
                var detective = new BookCategory { Name = "Detective" };
                var scienceFiction = new BookCategory { Name = "Science Fiction" };
                var novel = new BookCategory { Name = "Novel" };

                db.BookCategories.Add(fantasy);
                db.BookCategories.Add(detective);
                db.BookCategories.Add(scienceFiction);
                db.BookCategories.Add(novel);
                db.SaveChanges();

                Console.WriteLine("Writers..");
                var writers = JsonConvert.DeserializeObject<List<Writer>>(File.ReadAllText("Writers.json"));
                writers.ForEach(w => db.Writers.Add(w));
                db.SaveChanges();

                Console.WriteLine("Books..");
                int k = 0;
                foreach (BookCategory bookCategory in db.BookCategories)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        var book = new Book
                        {
                            Category = bookCategory,
                            ISBN = (100 + k) + "-1477827" + (100 + k),
                            Price = rand.Next(10000, 100000) / 100.0M,
                            PublishYear = rand.Next(1990, 2015),
                            Title = Titles.List[k],
                            Writers = Enumerable.Range(1, k%3+1)
                                .Select(@int => writers[k+@int])
                                .ToList(),
                            Amounts = new List<BookAmount>
                                {
                                    new BookAmount
                                    {
                                        Branch = br1,
                                        Amount = 10,
                                    },
                                    new BookAmount
                                    {
                                        Branch = br2,
                                        Amount = 10,
                                    }
                                }
                        };
                        db.Books.Add(book);
                        k++;
                    }
                }

                db.SaveChanges();
                Console.WriteLine("Done");
            }
        }
Esempio n. 54
0
        public void ORM_LinqQuery_TwoPropertiesConstraint_RefToRef()
        {
            var repo = RF.Concrete<BookRepository>();
            using (RF.TransactionScope(repo))
            {
                var bc1 = new BookCategory { Code = "1", Name = "1" };
                var bc2 = new BookCategory { Code = "2", Name = "1" };
                var bc3 = new BookCategory { Code = "3", Name = "3" };
                RF.Save(bc1);
                RF.Save(bc2);
                RF.Save(bc3);

                var bl1 = new BookLoc { Code = "1" };
                var bl2 = new BookLoc { Code = "2" };
                var bl3 = new BookLoc { Code = "3" };
                RF.Save(bl1);
                RF.Save(bl2);
                RF.Save(bl3);

                repo.Save(new Book { Name = "1", BookCategory = bc1, BookLoc = bl1 });
                repo.Save(new Book { Name = "2", BookCategory = bc2, BookLoc = bl1 });
                repo.Save(new Book { Name = "3", BookCategory = bc2, BookLoc = bl2 });
                repo.Save(new Book { Name = "4", BookCategory = bc3, BookLoc = bl1 });
                repo.Save(new Book { Name = "5", BookCategory = bc3, BookLoc = bl2 });
                repo.Save(new Book { Name = "6", BookCategory = bc3, BookLoc = bl3 });

                var list = repo.LinqGet_RefBCEqualsRefBC();
                Assert.IsTrue(list.Count == 2);
                Assert.IsTrue(list[0].Name == "1");
                Assert.IsTrue(list[1].Name == "6");
            }
        }
Esempio n. 55
0
        public void ORM_LinqQuery_TwoPropertiesConstraint_NormalToRef()
        {
            var bcRepo = RF.Concrete<BookCategoryRepository>();
            var repo = RF.Concrete<BookRepository>();
            using (var tran = RF.TransactionScope(repo))
            {
                var bc = new BookCategory { Code = "1" };
                bcRepo.Save(bc);
                repo.Save(new Book { Code = "1", BookCategory = bc });
                repo.Save(new Book { Code = "2", BookCategory = bc });
                repo.Save(new Book { BookCategory = bc });
                repo.Save(new Book());

                var list = repo.LinqGet_BCIdEqualsRefBCId();
                Assert.IsTrue(list.Count == 3, "查询出第1、2、3个对象。");
            }
        }
            private BookCategory BookCategory()
            {
                var category = new BookCategory();

                Upon(b =>
                {
                    b.IgnoreUnrecognizedAttributes();

                    b.ContentElement<string>("name", x => category.Name = x);
                    b.Element("book", () => category.Books.Add(Book()))
                        .ZeroOrMore();
                });

                return category;
            }
Esempio n. 57
0
 public bool Remove(BookCategory entity)
 {
     return base.Remove(entity);
 }
Esempio n. 58
0
 public void Add(BookCategory entity)
 {
     base.Add(entity);
 }
Esempio n. 59
0
        public ActionResult Edit(int productId)
        {
            #region Prep Utilities

            AddNewBookViewModel model = new AddNewBookViewModel();
            model.model_ID = new Guid("11111111-1111-1111-1111-111111111111").ToString();
            #endregion

            myHandler = new BusinessLogicHandler();
            Book book = myHandler.GetBook(productId);

            IEnumerable<BookAuthor> bookAuthorList = myHandler.GetBookAuthors(book.BookID);

            model.books = new Book();
            model.books = book;

            #region Create
            SupplierHandler supHandler = new SupplierHandler();
            /*TEMP LIST*/
            //List<Supplier> nameList = new List<Supplier>();
            IEnumerable<Supplier> nameList = (IEnumerable<Supplier>)supHandler.GetBookSupplierList();
            var disp = from nameAndId in nameList
                       select new { Value = nameAndId.SupplierID, Text = nameAndId.Name };

            ViewBag.SupplierList = new SelectList(disp.ToList());

            BookCategoryHandler typeHandler = new BookCategoryHandler();
            IEnumerable<BookCategory> typeList = (IEnumerable<BookCategory>)typeHandler.GetBookCategoryList();
            var dispBC = from name in typeList
                         select new { Value = name.BookCategoryID, Text = name.CategoryName };

            ViewBag.BookCategoryList = new SelectList(dispBC.ToList());

            AuthorHandler authHandler = new AuthorHandler();
            IEnumerable<Author> authList = (IEnumerable<Author>)authHandler.GetAuthorList();
            var dispAuth = from nameAndSurname in authList
                           select new { Value = nameAndSurname.AuthorID, Text = nameAndSurname.Name, nameAndSurname.Surname };
            ViewBag.authList = new SelectList(dispAuth.ToList());

            PublisherHandler publHandler = new PublisherHandler();
            IEnumerable<Publisher> pubList = (IEnumerable<Publisher>)publHandler.GetPublisherList();
            var dispPublisher = from pubName in pubList
                                select new { Value = pubName.PublisherID, Text = pubName.Name };
            ViewBag.pubList = new SelectList(dispPublisher.ToList());

            #endregion

            Supplier sp = new Supplier();
            Author ath = new Author();
            BookCategory bkc = new BookCategory();
            Publisher pb = new Publisher();

            foreach (var item in nameList)
            {
                if (item.SupplierID == model.books.SupplierID)
                {
                    sp.SupplierID = item.SupplierID;
                    sp.Name = item.Name;

                }
            }

            int[] authors = new int[bookAuthorList.Count()];
            int x = 0;
            foreach (var item in bookAuthorList)
            {
                if (item.BookID == model.books.BookID)
                {
                    authors[x] = item.AuthorID;
                    x++;
                }
            }

            foreach (var item in pubList)
            {
                if (item.PublisherID == model.books.PublisherID)
                {
                    pb.PublisherID = item.PublisherID;
                    pb.Name = item.Name;
                }
            }

            foreach (var item in typeList)
            {
                if (item.BookCategoryID == model.books.BookCategoryID)
                {
                    bkc.BookCategoryID = item.BookCategoryID;
                    bkc.CategoryName = item.CategoryName;
                }
            }

            #region Display
            List<SelectListItem> publisher = new List<SelectListItem>();
            publisher.Add(new SelectListItem { Value = pb.PublisherID.ToString(), Text = pb.Name, Selected = true });
            foreach (var item in pubList)
            {
                if (item.PublisherID != pb.PublisherID)
                publisher.Add(new SelectListItem { Text = item.Name, Value = item.PublisherID.ToString() });
            }
            model.publishers = new List<SelectListItem>();
            model.publishers = publisher;
            ViewData["publishers"] = publisher;

            List<SelectListItem> bookCategory = new List<SelectListItem>();
            bookCategory.Add(new SelectListItem { Value = bkc.BookCategoryID.ToString(), Text = bkc.CategoryName, Selected = true });
            foreach (var item in typeList)
            {
                if (item.BookCategoryID != bkc.BookCategoryID)
                    bookCategory.Add(new SelectListItem { Text = item.CategoryName, Value = item.BookCategoryID.ToString() });
            }
            model.bookCategories = new List<SelectListItem>();
            model.bookCategories = bookCategory;
            ViewData["bookCategories"] = bookCategory;

            List<SelectListItem> supplier = new List<SelectListItem>();
            supplier.Add(new SelectListItem { Value = sp.SupplierID.ToString(), Text = sp.Name, Selected = true });
            foreach (var item in nameList)
            {
                if (item.SupplierID != sp.SupplierID)
                    supplier.Add(new SelectListItem { Text = item.Name, Value = item.SupplierID.ToString() });
            }
            model.suppliers = new List<SelectListItem>();
            model.suppliers = supplier;
            ViewData["suppliers"] = supplier;

            List<SelectListItem> author = new List<SelectListItem>();

            foreach (var item in authList)
            {
                if (authors.Contains(item.AuthorID))
                { author.Add(new SelectListItem { Text = item.Name, Value = item.AuthorID.ToString(), Selected = true }); }
                else
                { author.Add(new SelectListItem { Text = item.Name, Value = item.AuthorID.ToString() }); }
            }
            model.authors = new List<SelectListItem>();
            model.authors = author;
            ViewData["authors"] = author;
            #endregion

            return View(model);
        }
Esempio n. 60
0
        private static void AddBookForAggtQuery(BookRepository repo)
        {
            var so = new SectionOwner { Name = "huqf" };
            RF.Save(so);
            var category = new BookCategory { Name = "category" };
            RF.Save(category);

            repo.Save(new Book
            {
                Name = "1",//not match
                BookCategory = category,
                ChapterList =
                {
                    new Chapter
                    {
                        Name = "chapterNeed",
                        SectionList =
                        {
                            new Section { Name = "section need", SectionOwner = so },
                            new Section { Name = "need section", SectionOwner = so }
                        }
                    },
                    new Chapter { Name = "1.2"}
                }
            });
            repo.Save(new Book
            {
                Name = "2",
                //BookCategory = category,//not match
                ChapterList =
                {
                    new Chapter
                    {
                        Name = "chapterNeed",
                        SectionList =
                        {
                            new Section { Name = "section need", SectionOwner = so },
                            new Section { Name = "need section", SectionOwner = so }
                        }
                    },
                    new Chapter { Name = "1.2"},
                    new Chapter { Name = "1.3"},
                }
            });
            repo.Save(new Book
            {
                Name = "3",
                BookCategory = category,
                ChapterList =
                {
                    new Chapter
                    {
                        Name = "chapterNeed",
                        SectionList =
                        {
                            new Section { Name = "section need", SectionOwner = so },
                            new Section { Name = "need section", SectionOwner = so }
                        }
                    },
                    //new Chapter { Name = "1.2"}//not match
                }
            });
            repo.Save(new Book
            {
                Name = "4",
                BookCategory = category,
                ChapterList =
                {
                    new Chapter
                    {
                        Name = "4.1",//not match
                        SectionList =
                        {
                            new Section { Name = "section need", SectionOwner = so },
                            new Section { Name = "need section", SectionOwner = so }
                        }
                    },
                    new Chapter { Name = "1.2"},
                }
            });
            repo.Save(new Book
            {
                Name = "5",
                BookCategory = category,
                ChapterList =
                {
                    new Chapter
                    {
                        Name = "chapterNeed",
                        SectionList =
                        {
                            new Section { Name = "section need", SectionOwner = so },
                            new Section { Name = "section", SectionOwner = so }//not match
                        }
                    },
                    new Chapter { Name = "1.2"},
                }
            });
            repo.Save(new Book
            {
                Name = "6",
                BookCategory = category,
                ChapterList =
                {
                    new Chapter
                    {
                        Name = "chapterNeed",
                        SectionList =
                        {
                            new Section { Name = "section need", SectionOwner = so },
                            new Section { Name = "need section" }//not match
                        }
                    },
                    new Chapter { Name = "1.2"},
                }
            });

            //添加 10 个满足条件的数据。
            for (int i = 11; i <= 20; i++)
            {
                repo.Save(new Book
                {
                    Name = i.ToString(),
                    BookCategory = category,
                    ChapterList =
                    {
                        new Chapter
                        {
                            Name = "chapterNeed",
                            SectionList =
                            {
                                new Section { Name = "section need", SectionOwner = so },
                                new Section { Name = "need section", SectionOwner = so }
                            }
                        },
                        new Chapter { Name = "1.2"},
                        new Chapter { Name = "1.3"},
                    }
                });
            }
        }