コード例 #1
0
        private static void FindBooksByName(string substring)
        {
            Console.WriteLine("\nFinding books by name '{0}':", substring);

            SQLiteCommand mySqlCommand = new SQLiteCommand(@"SELECT Title, Author, PublishDate, ISBN
                                                             FROM Books
                                                             WHERE CHARINDEX(@substring, Title)", mySqlConnection);

            mySqlCommand.Parameters.AddWithValue("@substring", substring);

            using (SQLiteDataReader reader = mySqlCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    var title = reader["Title"].ToString();
                    var author = reader["Author"].ToString();
                    var publishDate = (DateTime)reader["PublishDate"];
                    var isbn = reader["ISBN"].ToString();

                    var book = new Book()
                    {
                        Title = title,
                        Author = author,
                        PublishDate = publishDate,
                        ISBN = isbn
                    };

                    Console.WriteLine(book);
                }
            }
        }
コード例 #2
0
ファイル: BookController.cs プロジェクト: Gcobani/urbanbooks
        public ActionResult ByCategory(string name, int CategoryID)
        {
            #region Init

            BusinessLogicHandler myHandler = new BusinessLogicHandler();
            SearchViewModel model = new SearchViewModel();
            Book helper = new Book();
            #endregion

            #region Get Books By Category

            if (name != null)
            {
                model.BookResults = myHandler.CategoryBookSearch(name);
                model.BCategory = new BookCategory();
                helper = (Book)model.BookResults.Take(1).FirstOrDefault();
                model.BCategory = myHandler.GetBookType(helper.BookCategoryID);

            }
            else if (CategoryID != 0)
            {
                model.BookResults = myHandler.GetBooksByCategory(CategoryID);
                model.BCategory = new BookCategory();
                model.BCategory = myHandler.GetBookType(CategoryID);
            }

            #endregion

            return View(model);
        }
コード例 #3
0
        public Book Update(Book entity)
        {
            context.Entry(entity).State = EntityState.Modified;
            entity.DateModified = DateTime.Now;

            return entity;
        }
コード例 #4
0
        public static void Main()
        {
            var documents = new List<Manuscript>();
            var formatter = new FancyFormatter(); // new BackwardsFormatter();

            var faq = new Faq(formatter) { Title = "The Bridge Pattern FAQ" };
            faq.Questions.Add("What is it?", "A design pattern");
            faq.Questions.Add("When do we use it?", "When you need to separate an abstraction from an implementation.");
            documents.Add(faq);

            var book = new Book(formatter)
            {
                Title = "Lots of Patterns",
                Author = "John Sonmez",
                Text = "Blah blah blah..."
            };
            documents.Add(book);

            var paper = new TermPaper(formatter)
            {
                Class = "Design Patterns",
                Student = "Joe N00b",
                Text = "Blah blah blah...",
                References = "GOF"
            };
            documents.Add(paper);

            foreach (var doc in documents)
            {
                doc.Print();
            }

            // Wait for user
            Console.ReadKey();
        }
コード例 #5
0
 static void Main(string[] args)
 {
     var temp = new Book("one", "One");
     var first = new Book("Роулинг Джоанн", "Гарри Поттер и философский камень", "Фантастика", "РОСМЭН-Издат",
         300);
     var seventh = new Book("J.K.Rouling", "Harry Potter and the deathly Hallows");
     var bookList = new BookListService();
     bookList.AddBook(first);
     bookList.AddBook(seventh);
     bookList.AddBook(temp);
     try { bookList.AddBook(null); } catch (ArgumentNullException) { }
     try { bookList.AddBook(new Book("one", "One")); } catch (ArgumentException) { }
     try { bookList.RemoveBook(null); } catch (ArgumentNullException) { }
     try { bookList.RemoveBook(new Book("two", "Two")); } catch (ArgumentException) { }
     Console.WriteLine("BookListService");
     var brw = new BinaryReaderWriter("books_new.bin");
     bookList.SaveBooks(brw);
     bookList.PrintBooks();
     Console.WriteLine();
     bookList.SortBooksByAuthor();
     bookList.PrintBooks();
     Console.WriteLine();
     bookList.SortBooksByTitle();
     bookList.PrintBooks();
     Console.WriteLine();
     var newList = new BookListService();
     newList.LoadBooks(brw);
     newList.PrintBooks();
     Console.ReadLine();
 }
コード例 #6
0
        public void ShouldAddAndRemoveCoverFromBook()
        {
            Book book = new Book
                {
                    CategoryId = 1,
                    Title = "Book title",
                    Author = "pawel",
                    AdditionalInfoLine1 = "Additional Info",
                    ISBN = "222226"
                };

            Bitmap bitmap = new Bitmap(4, 4);
            for (int x = 0; x < bitmap.Height; ++x)
                for (int y = 0; y < bitmap.Width; ++y)
                    bitmap.SetPixel(x, y, Color.Red);

            book.Cover = bitmap;

            var status = BooksManager.InsertBook(book);
            Assert.Greater(book.Id, 0);
            Assert.IsNotNull(status.Data.Cover);

            status.Data.Cover = null;
            var status2 = BooksManager.UpdateBook(book);
            Assert.AreEqual(status2.Result, OperationResult.Passed);

            var bookWithNoCover = BooksManager.GetBook(book.Id);
            Assert.IsNull(bookWithNoCover.Cover);
        }
コード例 #7
0
        public async Task<IHttpActionResult> PutBook(int id, Book book)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

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

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

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

            return StatusCode(HttpStatusCode.NoContent);
        }
コード例 #8
0
ファイル: TagFilter.cs プロジェクト: Ozerich/labs
 public override bool Check(Book book)
 {
     foreach (string tag in book.Tags)
         if (Options.Equals(tag))
             return true;
     return false;
 }
コード例 #9
0
        public void BooksInDeletedCategoryShouldBeVisibleInMainCategory()
        {
            string isbn = "347563487562347856";
            Category newCategory = new Category
            {
                Name = "Category to delete",
                Parent = BooksManager.GetCategoryList(Constants.ROOT_CATEGORY, false)[0]
            };

            var result = BooksManager.InsertCategory(newCategory);

            Book newBook = new Book
                {
                    CategoryId = result.Data.Id,
                    Title = "Book title",
                    Author = "pawel",
                    AdditionalInfoLine1 = "Additional Info",
                    ISBN = isbn
                };

            BooksManager.InsertBook(newBook);

            BooksManager.DeleteCategory(newCategory);
            var books = BooksManager.GetBooksList(new BookFilter { ISBN = isbn });
            Assert.AreEqual(books.Count, 1);
            Assert.IsNull(books[0].Category);
        }
コード例 #10
0
 public Book DeleteBook(Book book)
 {
     var query = Ninject.Get<DeleteBookQuery>();
     query.Book = book;
     query.Execute();
     return book;
 }
コード例 #11
0
 public void Add(Book b)
 {
     if (b == null)
         throw new ArgumentNullException("Book cannot be null.");
     //
     this.Books.Add(b);
 }
コード例 #12
0
        public ActionResult EditBook(int id, Book data, bool onlyStock, int modifyStock, string plusOrMinus)
        {
            try
            {                
                if (onlyStock)
                {
                    adminService.EditStockData(id, modifyStock, plusOrMinus);
                    return RedirectToAction("ControlPanel");
                }

                if (ModelState.IsValid)
                {
                    adminService.EditBookData(id, data, modifyStock, plusOrMinus);
                    return RedirectToAction("ControlPanel");
                }

                throw new Exception();
            }
            catch (Exception ex)
            {
                if (ex.InnerException is SqlException)
                {
                    ViewBag.EditError = ex.InnerException.Message;
                    return View(data);
                }

                return View(data);
            }
        }
コード例 #13
0
 public Book AddBook(Book book)
 {
     var query = Ninject.Get<InsertBookQuery>();
     query.Book = book;
     query.Execute();
     return book;
 }
コード例 #14
0
 public void New_OrderWith3Book_Price24DescPesos()
 {
     Book book = new Book() { Price = 8 };
     _orderItem.Book = _orderItem.TotalBookDesc(book, 3, .10);
     double total = _orderItem.Book.Price;
     Assert.AreEqual(22.9, Convert.ToDecimal(total.ToString(".##")));
 }
コード例 #15
0
ファイル: BookShop.cs プロジェクト: krasi070/OOP
 static void Main()
 {
     Book readyPlayerOne = new Book("Ready Player One", "Ernest Cline", 16.90);
     Console.WriteLine(readyPlayerOne.ToString());
     GoldenEditionBook fahrenheit = new GoldenEditionBook("Fahrenheit 451", "Ray Bradbury", 11.90);
     Console.WriteLine(fahrenheit.ToString());
 }
コード例 #16
0
 public void New_OrderWith2Book_Price16DescPesos()
 {
     Book book = new Book() { Price = 8 };
     _orderItem.Book = _orderItem.TotalBookDesc(book, 2, .05);
     double total = _orderItem.Book.Price;
     Assert.AreEqual(14.95, Convert.ToDecimal(total.ToString(".##")));
 }
コード例 #17
0
ファイル: TestDataBuilder.cs プロジェクト: JornWildt/Peach
        protected void BuildBooks()
        {
            PageRepository.DeleteAll();
              BookRepository.DeleteAll();

              Console.WriteLine("Add books");

              Book b = new Book("mexikansk-mad", "Mexikansk mad", "En samling af mine yndlingsopskrifter fra Mexiko",
                        TestDataConstants.Profiles.SimonProfileId);
              b.PublishedDate = DateTime.UtcNow;

              Page p1 = new TextPage("Velbekomme", 1, "Demo");
              PageRepository.Add(p1);
              b.AddPage(p1.Id);

              RecipePage p2 = new RecipePage(MexicanskeBurritosRecipe.Title, 2, MexicanskeBurritosRecipe.Id);
              PageRepository.Add(p2);
              b.AddPage(p2.Id);

              RecipePage p3 = new RecipePage(BonneMosRecipe.Title, 3, BonneMosRecipe.Id);
              PageRepository.Add(p3);
              b.AddPage(p3.Id);

              BookRepository.Add(b);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: Maceage/DesignPatterns
        private static void Print(IFormatter formatter)
        {
            List<Publication> documents = new List<Publication>();

            var newspaper = new Newspaper(formatter);
            newspaper.Title = "The Publicist";
            newspaper.Articles.Add("Sugar linked to bad eyesight", "Rod Sugar");
            newspaper.Articles.Add("Sweden bans chocolate", "Willy Wonka");
            newspaper.Articles.Add("Opera house to be painted orange", "Orange Arup");
            documents.Add(newspaper);

            var book = new Book(formatter)
            {
                Title = "Price of Silence",
                Author = "Jay and Silent Bob",
                Text = "Blah-de-blah-de-blah..."
            };

            documents.Add(book);

            var magazine = new Magazine(formatter)
            {
                Name = "MixMag",
                PrintDate = "30/08/1993",
                CoverHeadline = "Downloads outstrip CD sales"
            };

            documents.Add(magazine);

            foreach (var doc in documents)
            {
                doc.Print();
            }
        }
コード例 #19
0
 public void New_OrderWith2Book_Price16Pesos()
 {
     Book book = new Book() { Price = 8 };
     _orderItem.Book = _orderItem.TotalBook(book, 2);
     double total = _orderItem.Book.Price;
     Assert.AreEqual(16, total);
 }
コード例 #20
0
        static void Main(string[] args)
        {
            Book book = new Book() { Id = 1, Title = "Book 1", Author = "Author 1" };
            book.Save(book);

            Console.Read();
        }
コード例 #21
0
 public BookViewModel(Book book)
 {
     Id = book.id;
     Name = book.name;
     Author = book.Author.name;
     Category = book.Category.name;
 }
コード例 #22
0
ファイル: Book_PutAwayEx.cs プロジェクト: Robobeurre/NRaas
            public override bool Test(Sim a, Book target, bool isAutonomous, ref GreyedOutTooltipCallback greyedOutTooltipCallback)
            {
                if (target is BookToddler)
                {
                    if (!a.Inventory.Contains(target))
                    {
                        if (isAutonomous) return false;
                    }

                    if (a.LotHome != a.LotCurrent) return false;
                }
                else
                {
                    if (a.Inventory.Contains(target) && (a.LotCurrent != a.LotHome))
                    {
                        return false;
                    }
                }

                if (target.InUse || (Bookshelf.FindClosestBookshelf(a, target, a.Inventory.Contains(target)) == null))
                {
                    return false;
                }

                if (!target.IsServiceableBySim(a))
                {
                    return false;
                }

                return true;
            }
コード例 #23
0
ファイル: ApiRequest.cs プロジェクト: BloomBooks/BloomDesktop
 public static bool Handle(EndpointRegistration endpointRegistration, IRequestInfo info, CollectionSettings collectionSettings, Book.Book currentBook)
 {
     var request = new ApiRequest(info, collectionSettings, currentBook);
     try
     {
         if(Program.RunningUnitTests)
         {
             endpointRegistration.Handler(request);
         }
         else
         {
             var formForSynchronizing = Application.OpenForms.Cast<Form>().Last();
             if (endpointRegistration.HandleOnUIThread && formForSynchronizing.InvokeRequired)
             {
                 formForSynchronizing.Invoke(endpointRegistration.Handler, request);
             }
             else
             {
                 endpointRegistration.Handler(request);
             }
         }
         if(!info.HaveOutput)
         {
             throw new ApplicationException(string.Format("The EndpointHandler for {0} never called a Succeeded(), Failed(), or ReplyWith() Function.", info.RawUrl.ToString()));
         }
     }
     catch (Exception e)
     {
         SIL.Reporting.ErrorReport.ReportNonFatalExceptionWithMessage(e, info.RawUrl);
         return false;
     }
     return true;
 }
コード例 #24
0
    // Use this for initialization
    void Start () {
        if (!ControledBook)
            ControledBook = GetComponent<Book>();
        if (AutoStartFlip)
            StartFlipping();
        ControledBook.OnFlip.AddListener(new UnityEngine.Events.UnityAction(PageFlipped));
	}
コード例 #25
0
ファイル: ApiRequest.cs プロジェクト: BloomBooks/BloomDesktop
 public ApiRequest(IRequestInfo requestinfo, CollectionSettings currentCollectionSettings, Book.Book currentBook)
 {
     _requestInfo = requestinfo;
     CurrentCollectionSettings = currentCollectionSettings;
     CurrentBook = currentBook;
     Parameters = requestinfo.GetQueryParameters();
 }
コード例 #26
0
        private static void WriteDefaultValues(string fileName)
        {
            Book first = new Book("Author1", "Title1", "Pub1", 1990, 200);
            Book second = new Book("Author2", "Title2", "Pub1", 1999, 250);
            Book third = new Book("Author3", "Title3", "Pub1", 1998, 205);
            BookListService bls = new BookListService();
            bls.AddBook(first);
            bls.AddBook(second);
            bls.AddBook(third);
            
            FileStream fs = new FileStream(fileName, FileMode.Create);

            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, bls);                

            }
            catch (SerializationException e)
            {
                log.Error("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
        }
コード例 #27
0
ファイル: MainForm.cs プロジェクト: gedgei/BookDbSharp
 private static void OpenBook(Book book)
 {
     Process proc = new Process();
     proc.EnableRaisingEvents = false;
     proc.StartInfo.FileName = book.Path;
     proc.Start();
 }
コード例 #28
0
 /// <summary>ListBook</summary>
 /// <param name="branch">Branch</param>
 /// <returns>List(Of Book)</returns>
 public List<Book> ListBook(int branch)
 {
     List<Book> items = new List<Book>();
     try
     {
         SqlParameter[] sqlparameters = new SqlParameter[1];
         sqlparameters[0] = new SqlParameter("@Branch", SqlDbType.Int) { Value = branch };
         SqlConnection connection = new SqlConnection(connectionstring);
         SqlDataReader reader = DataHelper.CommandQuerying(connection, "ListBook", sqlparameters);
         while (reader.Read())
         {
             Book item = new Book();
             item.Author = reader["Author"] != DBNull.Value ? (string)reader["Author"] : "";
             item.Code = reader["Branch"] != DBNull.Value ? (int)reader["Branch"] : 0;
             item.Distance = reader["Distance"] != DBNull.Value ? (double)reader["Distance"] : 0;
             item.ISBN = reader["ISBN"] != DBNull.Value ? (string)reader["ISBN"] : "";
             item.Title = reader["Title"] != DBNull.Value ? (string)reader["Title"] : "";
             if (!item.ISBN.Equals("")) item.Image = string.Format("http://library.newcastle.gov.uk/ThumbnailImages/{0}.JPG", item.ISBN.Trim());
             items.Add(item);
         }
         return items;
     }
     catch
     {
         return items;
     }
 }
コード例 #29
0
ファイル: TestLibrary.cs プロジェクト: VaniaStoicheva/Library
    static void Main(string[] args)
    {
        Book firstBook = new Book("C#", "Svetlin Nakov");
        Book secondBook = new Book("Java", "Svetlin Nakov");
        Book thirdBook = new Book(".NET", "Svetlin Nakov");
        Book fourthBook = new Book("Ice and fire", "George Martin");

        Library telerikLib = new Library("Telerik Library");
        
        
        telerikLib.Add(firstBook);
        telerikLib.Add(secondBook);
        telerikLib.Add(thirdBook);
        telerikLib.Add(fourthBook);
        Console.WriteLine("Display library :");
        telerikLib.DisplayAll();

        int startIndx = 0;
        int indxFound;

        while (telerikLib.IndexOf("Svetlin Nakov", startIndx, SearchOption.Author) != -1)
        {
            indxFound = telerikLib.IndexOf("Svetlin Nakov", startIndx, SearchOption.Author);
            telerikLib.DeleteAt(indxFound);
        }
        Console.WriteLine("\nAfter deleting :");
        telerikLib.DisplayAll();
    }
コード例 #30
0
ファイル: home.aspx.cs プロジェクト: nutsukae/E-library
    private void LoadSideBanner()
    {
        Book book = new Book();

        DataSet ds = new DataSet();
        ds = book.ListInteriorBooks();

        DataTable dt = new DataTable();
        dt = ds.Tables[0];

        int RowCount = dt.Rows.Count;

        if (RowCount > 0)
        {
            BookPanel.Controls.Add(new LiteralControl("<ul id=\"mycarousel\" class=\"jcarousel jcarousel-skin-tango\">"));
            for (int i = 0; i < RowCount; i++)
            {
                string control = string.Format("<li><a href=\"ViewBook.aspx?bookid={0}\">"
                    + "<img src=\"../E-Library/{1}\" width=\"150\" height=\"150\" alt=\"\" /></li>"
                        , Convert.ToString(dt.Rows[i]["bookid"]), Convert.ToString(dt.Rows[i]["imgpath"]));
                BookPanel.Controls.Add(new LiteralControl(control));
            }
            BookPanel.Controls.Add(new LiteralControl("</ul>"));
        }
    }
コード例 #31
0
 public IActionResult Delete(Book book)
 {
     _service.Delete(book.Id);
     _service.SaveChanges();
     return(RedirectToAction("Index"));
 }
コード例 #32
0
 public async Task OnGetAsync(int id)
 {
     Book = await _db.Book.FindAsync(id);
 }
コード例 #33
0
 private static void SetBookProperties(BaseItemDto dto, Book item)
 {
     dto.SeriesName = item.SeriesName;
 }
コード例 #34
0
 public void Edit(int id, Book book)
 {
     throw new NotImplementedException();
 }
コード例 #35
0
 public void Add(Book book)
 {
     throw new NotImplementedException();
 }
コード例 #36
0
 public void CreateBook(Book book)
 {
     _dbContext.Add(book);
     _dbContext.SaveChanges();
 }
コード例 #37
0
        public ViewResult Edit(int ISBN)
        {
            Book book = Repository.Books.FirstOrDefault(b => b.ISBN == ISBN);

            return(View(book));
        }
コード例 #38
0
 public void Visit(Book book)
 {
     auteurs.Add(book.Author);
 }
コード例 #39
0
 public Book Create(Book dto)
 {
     var db = _client.GetDatabase("booksStore");
     db.GetCollection<Book>("book").InsertOne(dto);
     return dto;
 }
コード例 #40
0
        public ActionResult Delete(int id)
        {
            Book book = UoW.BookRepository.Get(item => item.BookId == id);

            return(View(book));
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: Mikhail-Z/ECommerceApp
        static void Main(string[] args)
        {
            Customer customer = new Customer(
                "Петр",
                "Петров",
                null,
                Sex.Male,
                "+7 999 999 99 99",
                "*****@*****.**",
                "12345678");
            Author        GregorHopp = new Author("Грегор", "ХопBo");
            Author        BobbiWolf  = new Author("Бобби", "Вульф");
            ISet <Author> authors    = new HashSet <Author>()
            {
                GregorHopp, BobbiWolf
            };

            PublishingHouse williamsPublishing = new PublishingHouse("Вильямс");

            ProductCategory bookProductCategory       = new ProductCategory("Книги", null);
            ProductCategory nonFictionProductCategory =
                new ProductCategory("Нехудожественная литература", bookProductCategory);
            ProductCategory computerTechnologiesProductCategory =
                new ProductCategory("Компьютерные технологии", nonFictionProductCategory);

            Book book = new Book(
                "Шаблоны интеграции корпоративных приложений", authors,
                williamsPublishing, Language.Russian, BookType.Paper,
                BookCoverType.HardBack, 672,
                @"В данной книге исследуются стратегии интеграции корпоративных приложений с помощью 
механизмов обмена сообщениями. Авторы рассматривают шаблоны проектирования и приводят практические 
примеры интеграции приложений, демонстрирующие преимущества обмена сообщениями и эффективность решений, 
создаваемых на основе этой технологии. Каждый шаблон сопровождается описанием некоторой задачи 
проектирования, обсуждением исходных условий и представлением элегантного, сбалансированного решения. 
Авторы подчеркивают как преимущества, так и недостатки обмена сообщениями, 
а также дают практические советы по написанию кода подключения приложения к системе обмена сообщениями, 
маршрутизации сообщений и мониторинга состояния системы.Книга ориентирована на разработчиков программного 
обеспечения и системных интеграторов, использующих различные технологии и продукты для обмена сообщениями, 
такие как Java Message Service (JMS), Microsoft Message Queuing (MSMQ), IBM WebSphere MQ, 
Microsoft BizTalk, TIBCO, WebMethods, SeeBeyond, Vitria и др.", "978-5-907144-45-3",
                2019, new decimal(2829), DateTime.Now,
                computerTechnologiesProductCategory, true);
            Cart cart = new Cart(customer);

            cart.Add(book);
            cart.Add(book);
            var      deliveryPoint = new DeliveryPoint("г. Рязань, ул. Новоселов, д. 49");
            var      deliveryCost  = DeliveryService.CalculateDeliveryCost(customer, cart.Products, deliveryPoint);
            Delivery delivery      = new Delivery(
                deliveryPoint,
                deliveryCost,
                new DateTime(2019, 11, 26),
                DeliveryType.PointOfIssue);
            Order order = new Order(cart, PaymentType.Cash, delivery);

            customer.UpdatePersonalData("Иван", "Иванов", Sex.Male, null);
            Payment payment = new Payment(order);

            //Через некоторое время после успешного взаимодействия со сторонними сервисами по оплате
            order.OrderStage = OrderStage.SuccessfullyMade;
            order.OrderStage = OrderStage.Packaging;
            order.OrderStage = OrderStage.DeliveredToDeliveryPoint;
            order.OrderStage = OrderStage.ReadyForDelivery;
            order.OrderStage = OrderStage.Issued;
        }
コード例 #42
0
        /// <summary>
        /// Finds the book in the database with the same BookID and matches the fields to the BookBLL passed in.
        /// </summary>
        /// <param name="updater"></param>
        public void UpdateBookFields(BookUpdater updater)
        {
            //First check if a new author needs to be created
            if (updater.AuthorBuilder != null)
            {
                AddAuthorToDatabase(updater);
            }
            using (LibraryDBEntities context = new LibraryDBEntities())
            {
                Book book = (from b in context.Books
                             where b.BookID == updater.Book.BookID
                             select b).FirstOrDefault();
                //Update the fields of the book record to match any new data
                if (updater.ChangeAuthorID)
                {
                    if (updater.AuthorBuilder != null && updater.AuthorBuilder.IsNewPerson)
                    {
                        updater.AuthorID = updater.Book.AuthorID;
                    }
                    book.AuthorID = updater.AuthorID;
                }

                if (updater.ChangeTitle)
                {
                    book.Title = updater.Title;
                }
                if (updater.ChangeISBN)
                {
                    book.ISBN = updater.ISBN;
                }
                if (updater.ChangeLanguage)
                {
                    book.Language = updater.Language;
                }
                if (updater.ChangeNumberOfCopies)
                {
                    book.NumberOfCopies = updater.NumberOfCopies;
                }
                if (updater.ChangeNumPages)
                {
                    book.NumPages = updater.NumPages;
                }
                if (updater.ChangePublisher)
                {
                    book.Publisher = updater.Publisher;
                }
                if (updater.ChangeDescription)
                {
                    book.Description = updater.Description;
                }
                if (updater.ChangeSubject)
                {
                    book.Subject = updater.Subject;
                }
                if (updater.ChangeYearPublished)
                {
                    book.YearPublished = updater.YearPublished;
                }

                context.SaveChanges();
            }
            updater.FinalizeChanges();
        }
コード例 #43
0
 public void DeleteBook(Book book)
 {
     _context.Books.Remove(book);
 }
コード例 #44
0
 public Task AddBookAsync(Book book) => throw new NotImplementedException();
コード例 #45
0
        public static string ImportAuthors(BookShopContext context, string jsonString)
        {
            StringBuilder sb = new StringBuilder();

            ImportAuthorDto[] authorDtos =
                JsonConvert.DeserializeObject <ImportAuthorDto[]>(jsonString);

            List <Author> authors = new List <Author>();

            foreach (ImportAuthorDto authorDto in authorDtos)
            {
                if (!IsValid(authorDto))
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                if (authors.Any(a => a.Email == authorDto.Email))
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                Author author = new Author()
                {
                    FirstName = authorDto.FirstName,
                    LastName  = authorDto.LastName,
                    Email     = authorDto.Email,
                    Phone     = authorDto.Phone
                };

                foreach (ImportAuthorBookDto bookDto in authorDto.Books)
                {
                    if (!bookDto.BookId.HasValue)
                    {
                        continue;
                    }
                    Book book = context
                                .Books
                                .FirstOrDefault(b => b.Id == bookDto.BookId);

                    if (book == null)
                    {
                        continue;
                    }

                    author.AuthorsBooks.Add(new AuthorBook
                    {
                        Author = author,
                        Book   = book
                    });
                }

                if (author.AuthorsBooks.Count == 0)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                authors.Add(author);
                sb.AppendLine(String.Format(SuccessfullyImportedAuthor,
                                            (author.FirstName + ' ' + author.LastName),
                                            author.AuthorsBooks.Count));
            }
            context.Authors.AddRange(authors);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
コード例 #46
0
        /// <summary>
        /// method which displays details of a specific book in database
        /// </summary>
        /// <param name="id">book to be displayed</param>
        /// <returns>a formated view of the book to the view</returns>
        // GET: Books/Details/5
        public ActionResult Details(int id)
        {
            ViewData["CanUpdate"]       = false;
            ViewData["CanLeaveReview"]  = false;
            ViewData["AlreadyReviewed"] = " ";


            if (TempData["AlreadyInCart"] == null)
            {
                TempData["AlreadyInCart"] = "";
            }

            //get book
            Book book = UoW.BookRepository.Get(item => item.BookId == id);

            //add book details to viewmodel
            PartialTestViewModel pvm = new PartialTestViewModel();

            pvm.book             = book;
            pvm.book.Author      = book.Author;
            pvm.book.BookTitle   = book.BookTitle;
            pvm.book.Description = book.Description;

            pvm.book.Added     = book.Added;
            pvm.book.BookId    = book.BookId;
            pvm.book.Publisher = book.Publisher;
            pvm.book.Supplier  = book.Supplier;
            pvm.Reviews        = book.Reviews.ToList();

            pvm.book.ArtworkURL = "http://placehold.it/300x450";
            pvm.ReviewCount     = book.Reviews.Count();
            pvm.user            = GetCurrentUser();

            //show/hide items based on conditions
            if (GetCurrentUser() != null && GetCurrentUser().AccountRestricted == true)
            {
                ViewData["AlreadyReviewed"] = "Your account is restricted, you are not permitted to leave reviews.";
                ViewData["CanLeaveReview"]  = false;
            }

            //get reviews for the book
            var reviews = UoW.ReviewRepository.GetAll();

            List <string> reviewAuthors = new List <string>();

            //review permissions based on user
            foreach (var r in reviews)
            {
                reviewAuthors.Add(r.Author);

                if (GetCurrentUser() != null && (r.Author.Equals(GetCurrentUser().UserName) && GetCurrentUser().AccountRestricted == false))
                {
                    ViewData["CanUpdate"] = true;
                }
                else
                {
                    ViewData["CanUpdate"] = false;
                }
            }

            if (GetCurrentUser() != null && reviewAuthors.Contains(GetCurrentUser().UserName))
            {
                ViewData["AlreadyReviewed"] = "You have already reviewed this book";
                ViewBag.MustLogIn           = "";
                ViewData["CanLeaveReview"]  = false;
            }
            else if (GetCurrentUser() != null && GetCurrentUser().AccountRestricted == true)
            {
                ViewData["AlreadyReviewed"] = "Your account is restricted, you are not permitted to leave reviews.";
                ViewData["CanLeaveReview"]  = false;
            }
            else
            {
                ViewData["CanLeaveReview"] = true;
            }
            if (IsLoggedIn() == false)
            {
                ViewBag.MustLogIn           = "******";
                ViewData["AlreadyReviewed"] = "";
                ViewData["CanLeaveReview"]  = false;
            }


            int total = 0;

            //work out average stars for book
            foreach (var review in book.Reviews)
            {
                int stars = review.stars;

                total = total + stars;
            }

            if (pvm.ReviewCount != 0)
            {
                pvm.AvgStars = (total / pvm.ReviewCount);
            }

            return(View(pvm));
        }
コード例 #47
0
ファイル: BookTest.cs プロジェクト: peterriley/Books
        public void GetTotalPriceWithDiscountsKata()
        {
            //-- Act
            List<Book> bookList = new List<Book>();
            Book singleBook1_1 = new Book
            {
                Id = 1,
                BookType = BookType.FirstBook,
                BookPrice = 8
            };
            bookList.Add(singleBook1_1);
            Book singleBook1_2 = new Book
            {
                Id = 2,
                BookType = BookType.FirstBook,
                BookPrice = 8
            };
            bookList.Add(singleBook1_2);
            Book singleBook2_1 = new Book
            {
                Id = 3,
                BookType = BookType.SecondBook,
                BookPrice = 8
            };
            bookList.Add(singleBook2_1);
            Book singleBook2_2 = new Book
            {
                Id = 4,
                BookType = BookType.SecondBook,
                BookPrice = 8
            };
            bookList.Add(singleBook2_2);
            Book singleBook3_1 = new Book
            {
                Id = 5,
                BookType = BookType.ThirdBook,
                BookPrice = 8
            };
            bookList.Add(singleBook3_1);
            Book singleBook3_2 = new Book
            {
                Id = 6,
                BookType = BookType.ThirdBook,
                BookPrice = 8
            };
            bookList.Add(singleBook3_2);
            Book singleBook4 = new Book
            {
                Id = 7,
                BookType = BookType.FourthBook,
                BookPrice = 8
            };
            bookList.Add(singleBook4);
            Book singleBook5 = new Book
            {
                Id = 8,
                BookType = BookType.FifthBook,
                BookPrice = 8
            };
            bookList.Add(singleBook5);

            var expected = 51.60m;

            //-- Arrange
            //var actual = Book.GetTotalPriceWithDiscounts(bookList);
            var actual = BookRepository.GetBasketPrice(bookList, 0);

            //-- Assert
            Assert.AreEqual(expected, actual);
        }
コード例 #48
0
 public Book Add(Book model)
 {
     return(_bookDal.Add(model));
 }
コード例 #49
0
 public void Insert(Book book)
 {
     db.Book.Add(book);
     db.SaveChanges();
 }
コード例 #50
0
 public void Update(Book book)
 {
     db.Entry(book).State = EntityState.Modified;
     db.SaveChanges();
 }
コード例 #51
0
        private void GenerateVerses(string path)
        {
            Razor.Compile(_versesTemplate, "versesTemplate");

            for (int i = 1; i < _english.Books.Count + 1; i++)
            {
                string bookPath = path + Path.DirectorySeparatorChar + i;
                Directory.CreateDirectory(bookPath);

                Book englishBook   = _english.Books[i - 1];
                Book malayalamBook = _malayalam.Books[i - 1];
                Book hindiBook     = _hindi.Books[i - 1];

                Log.Info("Generating " + englishBook.Name);

                for (int j = 1; j < englishBook.Chapters.Count + 1; j++)
                {
                    string chapterPath = bookPath + Path.DirectorySeparatorChar + j;
                    Directory.CreateDirectory(chapterPath);

                    Chapter englishChapter   = englishBook.Chapters[j - 1];
                    Chapter malayalamChapter = malayalamBook.Chapters[j - 1];
                    Chapter hindiChapter     = hindiBook.Chapters[j - 1];

                    BookChapter bookChapter = new BookChapter(englishBook.Name + " " + englishChapter.Id);

                    if (englishBook.Id == 1 && englishChapter.Id == 1)
                    {
                        bookChapter.HasBack = false;
                    }
                    else
                    {
                        int backBook    = englishBook.Id;
                        int backChapter = englishChapter.Id - 1;
                        if (backChapter == 0)
                        {
                            backBook--;
                            backChapter = Book.ChaptersPerBook[backBook];
                        }
                        bookChapter.BackPath = string.Format("../../{0}/{1}/index.html", backBook, backChapter);
                    }
                    if (englishBook.Id == 66 && englishChapter.Id == 22)
                    {
                        bookChapter.HasForward = false;
                    }
                    else
                    {
                        int forwardBook    = englishBook.Id;
                        int forwardChapter = englishChapter.Id + 1;
                        if (forwardChapter > Book.ChaptersPerBook[forwardBook])
                        {
                            forwardBook++;
                            forwardChapter = 1;
                        }
                        bookChapter.ForwardPath = string.Format("../../{0}/{1}/index.html", forwardBook, forwardChapter);
                    }

                    int maxVerses = Math.Max(Math.Max(englishChapter.Verses.Count, malayalamChapter.Verses.Count), hindiChapter.Verses.Count);
                    for (int k = 0; k < maxVerses; k++)
                    {
                        BookChapterVerse verse = new BookChapterVerse();
                        if (k < englishChapter.Verses.Count)
                        {
                            verse.InEnglish = true;
                            verse.English   = englishChapter.Verses[k];
                        }
                        if (k < malayalamChapter.Verses.Count)
                        {
                            verse.InMalayalam = true;
                            verse.Malayalam   = malayalamChapter.Verses[k];
                        }
                        if (k < hindiChapter.Verses.Count)
                        {
                            verse.InHindi = true;
                            verse.Hindi   = hindiChapter.Verses[k];
                        }
                        bookChapter.Verses.Add(verse);
                    }

                    string template = File.ReadAllText(_versesTemplate);
                    string result   = Razor.Parse(template, bookChapter);

                    //string result = Razor.Run("versesTemplate", bookChapter);

                    File.WriteAllText(chapterPath + Path.DirectorySeparatorChar + "index.html", result);
                }
            }
        }
コード例 #52
0
 public int insertBook(Book book)
 {
     db.Books.Add(book);
     db.SaveChanges();
     return(book.ID);
 }
コード例 #53
0
 public async Task<bool> Delete(Book entity) {
   _db.Books.Remove(entity); // this isn't doing anything asynchronously, just updating a local (in-memory) entity
   return await Save(); // this "Save" function is asyncronous, so we do need the await
 }
コード例 #54
0
 public bool IsMatch(Book b, string tag)
 {
     return(b.Title.Equals(tag));
 }
コード例 #55
0
        public async Task <bool> Create(Book entity)
        {
            await _context.Books.AddAsync(entity);

            return(await Save());
        }
コード例 #56
0
 public void ShowBook(Book book)
 {
     pageViewController.Show(book);
 }
コード例 #57
0
 public WishListBook()
 {
     Book = new Book();
 }
コード例 #58
0
 public async Task <bool> Update(Book entity)
 {
     _context.Books.Update(entity);
     return(await Save());
 }
コード例 #59
0
 public async Task <bool> Delete(Book entity)
 {
     _context.Books.Remove(entity);
     return(await Save());
 }
コード例 #60
0
 // Create (add) a new book record for the Books table in the db
 public async Task<bool> Create(Book entity) {
   await _db.Books.AddAsync(entity);
   return await Save();
 }