Inheritance: System.Web.UI.Page
Example #1
0
 public void SetBookInfo(BookInfo bookInfo, Sprite sprite)
 {
     title.text = bookInfo.Title + "\n" + bookInfo.Author + ", " + bookInfo.GetData("pub_date");
     itemImage.sprite = sprite;
     isFlashing = true;
     flashUITimer.Reset();
 }
Example #2
0
 public override void visit(BookInfo bookInfo)
 {
     this.setTitleBlurb("LB-Book: " +
                    bookInfo.getTitleName() +
                    ", Author: " +
                    bookInfo.getAuthor());
 }
 private async void SetBook(BookInfo bookInfo)
 {
     if (bookInfo.BookId == 0)
     {
         Mode = EditBookMode.AddNew;
     }
     else  // get an existing book from the repository
     {
         Mode = EditBookMode.Edit;
         Book = await _booksRepository.GetItemAsync(bookInfo.BookId);
     }
 }
Example #4
0
 public List<BookInfo> EvaluateBookByBook(List<BookInfo> list , BookInfo keyBook)
 {
     foreach(BookInfo b in list)
     {
         b.v = UnityEngine.Random.Range(-0.05f, 0.05f);
         if (b.Author.Contains(keyBook.Author))
             b.v += 3f;
         if (b.Location.Contains(keyBook.Location))
             b.v += 2f;
     }
     List<BookInfo> res = new List<BookInfo>(list);
     res.Sort((x,y) => x.v.CompareTo(y.v));
     return res;
 }
        public void Test()
        {
            var accountService = DependencyResolver.Resolve<ILibraryAccountService>();
            var libraryService = DependencyResolver.Resolve<ILibraryService>();
            var bookService = DependencyResolver.Resolve<IBookService>();
            var repository = DependencyResolver.Resolve<IRepository>();

            //创建借书账号
            var account = accountService.Create(RandomString(), RandomString());

            //创建三本书
            var book1Info = new BookInfo("Java Programming", "ISBN-001", "John", "Publisher1", string.Empty);
            var book2Info = new BookInfo(".Net Programming", "ISBN-002", "Jim", "Publisher2", string.Empty);
            var book3Info = new BookInfo("Mono Develop", "ISBN-003", "Richer", "Publisher3", string.Empty);
            var book1 = bookService.CreateBook(book1Info);
            var book2 = bookService.CreateBook(book2Info);
            var book3 = bookService.CreateBook(book3Info);

            //创建图书馆
            var library = libraryService.Create(RandomString());

            //图书入库
            bookService.AddBookToLibrary(book1.Id, 5, library.Id);
            bookService.AddBookToLibrary(book2.Id, 5, library.Id);
            bookService.AddBookToLibrary(book3.Id, 5, library.Id);

            //借书
            bookService.BorrowBook(book1.Id, account.Id, library.Id, 2);
            bookService.BorrowBook(book1.Id, account.Id, library.Id, 1);
            bookService.BorrowBook(book2.Id, account.Id, library.Id, 5);
            bookService.BorrowBook(book3.Id, account.Id, library.Id, 2);

            //还书
            bookService.ReturnBook(book1.Id, account.Id, library.Id, 1);
            bookService.ReturnBook(book1.Id, account.Id, library.Id, 1);
            bookService.ReturnBook(book2.Id, account.Id, library.Id, 5);
            bookService.ReturnBook(book3.Id, account.Id, library.Id, 1);

            //Assert图书馆剩余书本是否正确
            library = repository.GetById<Library>(library.Id);
            Assert.AreEqual(4, library.BookStoreItems.Single(x => x.BookId == book1.Id).Count);
            Assert.AreEqual(5, library.BookStoreItems.Single(x => x.BookId == book2.Id).Count);
            Assert.AreEqual(4, library.BookStoreItems.Single(x => x.BookId == book3.Id).Count);

            //Assert账号借到的书本是否正确
            account = repository.GetById<LibraryAccount>(account.Id);
            Assert.AreEqual(2, account.ActAs<IBorrower>().BorrowedBooks.Count());
            Assert.AreEqual(1, account.ActAs<IBorrower>().BorrowedBooks.Single(x => x.BookId == book1.Id).Count);
            Assert.AreEqual(1, account.ActAs<IBorrower>().BorrowedBooks.Single(x => x.BookId == book3.Id).Count);
        }
Example #6
0
    // set this in Whirlwind.cs
    public void SetBookInfo(BookInfo bookInfo, Sprite sprite)
    {
        currentBookInfo = bookInfo;

        string[] columns = {"title", "title_subtitle", "name", "pub_date", "pub_place", "note", "scope_content", "history"};
        string text = "";
        for (int i = 0; i < columns.Length; i++) {
            string s = bookInfo.GetData(columns[i]);
            if (s.Length > 1) {
                text += s + "\n\n";
            }

        }

        transform.Find("Fields").GetComponent<ScrollRect>().verticalNormalizedPosition = 1f;
        fields.text = text;
    }
Example #7
0
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            Configuration.Config("EventSourcing.Sample.BookBorrowAndReturn", assembly, assembly);

            var accountService = ObjectContainer.Resolve<ILibraryAccountService>();
            var libraryService = ObjectContainer.Resolve<ILibraryService>();
            var bookService = ObjectContainer.Resolve<IBookService>();

            //创建借书账号
            var account = accountService.Create("00001", "tangxuehua");

            //创建三本书
            var book1Info = new BookInfo("Java Programming", "ISBN-001", "John", "Publisher1", string.Empty);
            var book2Info = new BookInfo(".Net Programming", "ISBN-002", "Jim", "Publisher2", string.Empty);
            var book3Info = new BookInfo("Mono Develop", "ISBN-003", "Richer", "Publisher3", string.Empty);
            var book1 = bookService.CreateBook(book1Info);
            var book2 = bookService.CreateBook(book2Info);
            var book3 = bookService.CreateBook(book3Info);

            //创建图书馆
            var library = libraryService.Create("Sample Book Library");

            //图书入库
            bookService.AddBookToLibrary(book1.Id, 5, library.Id);
            bookService.AddBookToLibrary(book2.Id, 5, library.Id);
            bookService.AddBookToLibrary(book3.Id, 5, library.Id);

            //借书
            bookService.BorrowBook(book1.Id, account.Id, library.Id, 2);
            bookService.BorrowBook(book1.Id, account.Id, library.Id, 1);
            bookService.BorrowBook(book2.Id, account.Id, library.Id, 5);
            bookService.BorrowBook(book3.Id, account.Id, library.Id, 2);

            //还书
            bookService.ReturnBook(book1.Id, account.Id, library.Id, 1);
            bookService.ReturnBook(book1.Id, account.Id, library.Id, 1);
            bookService.ReturnBook(book2.Id, account.Id, library.Id, 5);
            bookService.ReturnBook(book3.Id, account.Id, library.Id, 1);

            Console.Write("Press Enter to exit...");
            Console.ReadLine();
        }
 protected void Button2_Click(object sender, EventArgs e)
 {
     for (int rowindex = 0; rowindex < this.GridView1.Rows.Count; rowindex++)
     {
         bool ischeck = ((CheckBox)this.GridView1.Rows[rowindex].Cells[0].FindControl("chk")).Checked;
         string price = ((TextBox)this.GridView1.Rows[rowindex].Cells[0].FindControl("Price")).Text;
         string memberPrice = ((TextBox)this.GridView1.Rows[rowindex].Cells[0].FindControl("MemberPrice")).Text;
         int intfavID = Convert.ToInt32(this.GridView1.DataKeys[rowindex].Value);
         if (ischeck)
         {
             BookInfo book = new BookInfo();
             book.Price = Convert.ToDecimal(price);
             book.MemberPrice = Convert.ToDecimal(memberPrice);
             book.BookID = intfavID;
             Book.UpdatePrice(book);
             //删除Convert.ToInt32(this.GridView1.DataKeys[rowindex].Value)
         }
     }
     dataBind();
 }
Example #9
0
        protected Mock <IBookStorage> MakeMockStorage(string tempFolderPath, Func <HtmlDom> domGetter)
        {
            var storage = new Moq.Mock <IBookStorage>();

            storage.Setup(x => x.GetLooksOk()).Returns(true);

            storage.SetupGet(x => x.Dom).Returns(domGetter);
            storage.SetupGet(x => x.Key).Returns("testkey");
            storage.Setup(x => x.GetRelocatableCopyOfDom()).Returns(() => storage.Object.Dom.Clone()); // review: the real thing does more than just clone
            storage.Setup(x => x.MakeDomRelocatable(It.IsAny <HtmlDom>())).Returns(
                (HtmlDom x) => { return(x.Clone()); });                                                // review: the real thing does more than just clone

            storage.Setup(x => x.GetFileLocator()).Returns(() => _fileLocator.Object);

            MakeSamplePngImageWithMetadata(Path.Combine(tempFolderPath, "original.png"));
            storage.SetupGet(x => x.FolderPath).Returns(tempFolderPath);            // review: the real thing does more than just clone
            var metadata = new BookInfo(tempFolderPath, true);

            storage.SetupGet(x => x.BookInfo).Returns(metadata);
            storage.Setup(x => x.HandleRetiredXMatterPacks(It.IsAny <HtmlDom>(), It.IsAny <string>()))
            .Returns((HtmlDom dom, string y) => { return(y == "BigBook" ? "Factory" : y); });
            return(storage);
        }
Example #10
0
        async Task <BookFileInfo> ReadBookFile(BookInfo book, string filepath)
        {
            string type = GetFileType(filepath);

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

            byte[] content = await _reader.ReadAllFileAsync(filepath);

            var bookfile = new BookFileInfo
            {
                Id       = filepath,
                FileName = Path.GetFileName(filepath),
                FileType = type,
                FilePath = filepath,
                BookId   = book.Id,
                Content  = content
            };

            return(bookfile);
        }
Example #11
0
        /// <summary>
        /// 根据书名查找书
        /// </summary>
        /// <param name="bookname"></param>
        /// <returns></returns>
        public static BookInfo GetBook(string bookname)
        {
            BookInfo book = new BookInfo();
            string   sql  = "select * from BookInfo where BookName=@bookname";

            MySqlParameter[] par = new MySqlParameter[]
            {
                new MySqlParameter("@bookname", bookname)
            };
            MySqlDataReader sdr = MysqlHelper.ExecuteReader(sql, CommandType.Text, par);

            if (sdr.Read())
            {
                book.BookName    = sdr["BookName"].ToString();
                book.BookPeople  = sdr["BookPeople"].ToString();
                book.BookAddress = sdr["BookAddress"].ToString();
                book.BookDate    = sdr["BookDate"].ToString();
                book.BookID      = Convert.ToInt32(sdr["BookID"]);
                book.BookPrice   = sdr["BookPrice"].ToString();
                book.BookPic     = (byte[])sdr["BookPic"];
            }
            return(book);
        }
Example #12
0
        /// <summary>
        /// tempFolderPath is where to put the book. Note that a few files (e.g., customCollectionStyles.css)
        /// are copied into its parent in order to be in the expected location relative to the book,
        /// so that needs to be a folder we can write in.
        /// </summary>
        public static Book.Book MakeDeviceXmatterTempBook(string bookFolderPath, BookServer bookServer, string tempFolderPath, bool isTemplateBook,
                                                          HashSet <string> omittedPageLabels = null)
        {
            BookStorage.CopyDirectory(bookFolderPath, tempFolderPath);
            var bookInfo = new BookInfo(tempFolderPath, true)
            {
                UseDeviceXMatter = !isTemplateBook
            };
            var modifiedBook = bookServer.GetBookFromBookInfo(bookInfo);

            modifiedBook.BringBookUpToDate(new NullProgress(), true);
            modifiedBook.RemoveNonPublishablePages(omittedPageLabels);
            var domForVideoProcessing  = modifiedBook.OurHtmlDom;
            var videoContainerElements = HtmlDom.SelectChildVideoElements(domForVideoProcessing.RawDom.DocumentElement).Cast <XmlElement>();

            if (videoContainerElements.Any())
            {
                SignLanguageApi.ProcessVideos(videoContainerElements, modifiedBook.FolderPath);
            }
            modifiedBook.Save();
            modifiedBook.Storage.UpdateSupportFiles();
            return(modifiedBook);
        }
Example #13
0
        private Book CreateNewBook(BookInfo info)
        {
            var type = new BookType
            {
                Title       = info.Title,
                Description = info.Description,
                UserAndTeam = info.UserAndTeam,
                Publisher   = info.Publisher
            };

            var book = new Book
            {
                BookNumber   = info.BookNumber,
                NetPrice     = float.Parse(info.NetPrice),
                PurchaseDate = DateTime.Parse(info.PurchaseDate),
                RequestedBy  = info.RequestedBy,
                PurchaseUrl  = info.PurchaseUrl,
                Supplier     = info.Supplier,
                BookType     = type
            };

            return(book);
        }
Example #14
0
        private void BookOnDel(object sender, MouseButtonEventArgs e)
        {
            var book = (sender as Border).DataContext as BookInfo;

            if (book == null || string.IsNullOrEmpty(book.BookId))
            {
                return;
            }
            ConfigSevice.DelBook(book.BookId);
            if (_bookInfo != null && book.BookId == _bookInfo.BookId)
            {
                _bookInfo             = null;
                LsCatalog.ItemsSource = null;
                TbContent.Text        = "";
                TbBookName.Text       = "";
                TbChapter.Text        = "";
                _file = "";
                _chapters.Clear();
                _currentChapter = null;
            }
            LoadBookShelft();
            e.Handled = true;
        }
Example #15
0
        public void DefectBookDiscountApplyDiscountTest()
        {
            List <Genre> genres1 = new List <Genre> {
                new Genre("fantasy")
            };
            BookInfo bookInfo1 = new BookInfo("Harry Potter and the Chamber of Secrets", "J.K.Rowling", genres1);
            decimal  cost      = 500.11m;

            Book book1 = new Book(bookInfo1, cost, DateTime.Today.Date);

            List <Genre> genres2 = new List <Genre> {
                new Genre("other")
            };
            BookInfo bookInfo2 = new BookInfo("One Flew Over the Cuckoo's Nest", " Ken Kesey", genres2);
            Book     book2     = new Book(bookInfo2, 600m, DateTime.Today.AddDays(-110));

            var      expireDate = DateTime.Today.AddDays(1000).Date;
            Discount discount   = new DefectDiscount(expireDate, 80, book1.Guid);

            discount.ApplyDiscount(book1, DateTime.Today.Date).Cost.Should().Be(100.02m);
            discount.ApplyDiscount(book1, DateTime.Today.AddDays(1001).Date).Cost.Should().Be(book1.Cost);
            discount.ApplyDiscount(book2, DateTime.Today.Date).Cost.Should().Be(book2.Cost);
        }
Example #16
0
        public void WhenIAddSeveralBooksWithProperties(Table table)
        {
            //// Using Specflow.Asist CreateSet:
            var booksFromTable = table.CreateSet <BookInfo>();

            foreach (var bookFromTable in booksFromTable)
            {
                var book = new BookInfo
                {
                    Title          = bookFromTable.Title,
                    Author         = bookFromTable.Author,
                    NumberOfPages  = bookFromTable.NumberOfPages,
                    StateInReader  = BookStateInReader.Unloaded,
                    ElectronicInfo = new ElectronicInfo
                    {
                        DataFormat      = DataFormat.Pdf,
                        SizeInMegabytes = 67
                    }
                };

                this.reader.AddTheBookToTheReaderStorage(book);
            }
        }
Example #17
0
        private void GetValueFromDatabase(BookSales bookSales, SqlDataReader reader)
        {
            bookSales.Date         = reader["date"].ToString();
            bookSales.DistrictName = reader["district_id"].ToString();
            bookSales.PartyCode    = reader["party_id"].ToString();
            bookSales.MemoNo       = reader["memo_no"].ToString();
            bookSales.SalesType    = reader["sales_type"].ToString();
            bookSales.Year         = reader["year"].ToString();
            bookSales.GroupName    = reader["group_id"].ToString();
            bookSales.BookId       = int.Parse(reader["book_id"].ToString());
            BookInfo bookInfo = GetBookInfo(bookSales.BookId);

            bookSales.BookRate      = bookInfo.BookRate;
            bookSales.Commisssion   = bookInfo.BookCommission;
            bookSales.Quantity      = Convert.ToDouble(reader["quantity"].ToString());
            bookSales.SalesRate     = Convert.ToDouble(reader["sales_rate"].ToString());
            bookSales.Total         = Convert.ToDouble(reader["total"].ToString());
            bookSales.Packing       = Convert.ToDouble(reader["packing"].ToString());
            bookSales.Bonus         = Convert.ToDouble(reader["bonus"].ToString());
            bookSales.TotalPrice    = Convert.ToDouble(reader["total_price"].ToString());
            bookSales.PaymentAmount = Convert.ToDouble(reader["payment_amount"].ToString());
            bookSales.Dues          = Convert.ToDouble(reader["dues"].ToString());
        }
Example #18
0
        public void RoundTrips_AllowUploading()
        {
            var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName);

            File.WriteAllText(jsonPath, @"{'allowUploadingToBloomLibrary':'false'}");
            var bi = new BookInfo(_folder.Path, true);

            Assert.False(bi.AllowUploading, "CHECK YOUR FixBloomMetaInfo ENV variable! Initial Read Failed to get false. Contents: " + File.ReadAllText(jsonPath));
            bi.Save();
            var bi2 = new BookInfo(_folder.Path, true);

            Assert.False(bi2.AllowUploading, "Read after Save() Failed  to get false. Contents: " + File.ReadAllText(jsonPath));

            File.WriteAllText(jsonPath, @"{'allowUploadingToBloomLibrary':'true'}");
            var bi3 = new BookInfo(_folder.Path, true);

            Assert.That(bi3.AllowUploading, "Initial Read Failed to get true. Contents: " + File.ReadAllText(jsonPath));
            bi3.Save();
            var bi4 = new BookInfo(_folder.Path, true);

            Assert.That(File.ReadAllText(jsonPath).Contains("allowUploadingToBloomLibrary"), "The file doesn't contain 'allowUploadingToBloomLibrary'");
            Assert.That(bi4.AllowUploading, "Read after Save() Failed  to get true. Contents: " + File.ReadAllText(jsonPath));
        }
Example #19
0
        public void BookStorageAddTwoDifferentBooksTest()
        {
            List <Genre> genres1 = new List <Genre> {
                new Genre("fantasy")
            };
            BookInfo bookInfo1 = new BookInfo("Harry Potter and the Chamber of Secrets", "J.K.Rowling", genres1);
            Book     book1     = new Book(bookInfo1, 500m, DateTime.Today);

            List <Genre> genres2 = new List <Genre> {
                new Genre("other")
            };
            BookInfo bookInfo2 = new BookInfo("One Flew Over the Cuckoo's Nest", " Ken Kesey", genres2);
            Book     book2     = new Book(bookInfo2, 600m, DateTime.Today.AddDays(-110));


            BookStorage bookStorage = new BookStorage();

            bookStorage.AddBook(book1);
            bookStorage.AddBook(book2);

            bookStorage.FindByGuidOrDefault(book1.Guid).Should().Be(book1);
            bookStorage.FindByGuidOrDefault(book2.Guid).Should().Be(book2);
        }
        public void InsertBook_NotPresent_InsertsInCorrectOrder()
        {
            var info1      = new BookInfo("book1", true);
            var info2      = new BookInfo("book2", true);
            var info3      = new BookInfo("book10", true);
            var info4      = new BookInfo("book20", true);
            var infoNew    = new BookInfo("book11", true);
            var state      = new List <BookInfo>(new[] { info1, info2, info3, info4 });
            var collection = new BookCollection(state);

            collection.InsertBookInfo(infoNew);
            Assert.That(state[3], Is.EqualTo(infoNew), "book info should be inserted between book10 and book20");

            var infoLast = new BookInfo("book30", true);

            collection.InsertBookInfo(infoLast);
            Assert.That(state[5], Is.EqualTo(infoLast), "book info should be inserted at end");

            var infoFirst = new BookInfo("abc", true);

            collection.InsertBookInfo(infoFirst);
            Assert.That(state[0], Is.EqualTo(infoFirst), "book info should be inserted at start");
        }
Example #21
0
        public ServiceResult Update(BookInfo book)
        {
            var query = _db.Books.FirstOrDefaultAsync(q => q.Id == book.Id);

            if (query.IsCompleted && query.Result == null)
            {
                return(ServiceResult.Error("数据不存在"));
            }
            else
            {
                query.Result.AminId     = book.AminId;
                query.Result.Author     = book.Author;
                query.Result.CoverImage = book.CoverImage;
                query.Result.CreateDT   = book.CreateDT;
                query.Result.Name       = book.Name;
                query.Result.Price      = book.Price;
                query.Result.Publish    = book.Publish;
                query.Result.RealPrice  = book.RealPrice;
                query.Result.SubName    = book.SubName;
                _db.SaveChanges();
                return(ServiceResult.Create(true, "操作成功"));
            }
        }
Example #22
0
    private void ProcessQueryResult(CloudDBZoneSnapshot <BookInfo> snapshot)
    {
        CloudDBZoneObjectList <BookInfo> bookInfoCursor = snapshot.GetSnapshotObjects();

        bookInfoList = new List <BookInfo>();
        try
        {
            while (bookInfoCursor.HasNext())
            {
                BookInfo bookInfo = bookInfoCursor.Next();
                bookInfoList.Add(bookInfo);
                Debug.Log($"{TAG} bookInfoCursor.HasNext() {bookInfo.Id}  {bookInfo.Author}");
            }
        }
        catch (Exception e)
        {
            Debug.Log($"{TAG} processQueryResult:  Exception => " + e.Message);
        }
        finally
        {
            snapshot.Release();
        }
    }
Example #23
0
 //Requires an already-built AuthorProfile and the BaseEndActions.txt file
 // TODO Move non-DI params from constructor to function
 public EndActions(
     AuthorProfileGenerator.Response authorProfile,
     BookInfo book,
     long erl,
     ISecondarySource dataSource,
     Settings settings,
     Func <string, string, string> asinPrompt,
     ILogger logger,
     IHttpClient httpClient,
     IAmazonClient amazonClient,
     IAmazonInfoParser amazonInfoParser)
 {
     _authorProfile    = authorProfile;
     curBook           = book;
     _erl              = erl;
     _dataSource       = dataSource;
     _settings         = settings;
     _asinPrompt       = asinPrompt;
     _logger           = logger;
     _httpClient       = httpClient;
     _amazonClient     = amazonClient;
     _amazonInfoParser = amazonInfoParser;
 }
Example #24
0
        private void GrabGetBookInfo(SqlCommand c, out BookInfo b)
        {
            using (SqlDataReader data = c.ExecuteReader())
            {
                if (!data.HasRows)
                {
                    throw new Exception("No book with the given ID");
                }
                data.Read();
                string title    = data.GetString(data.GetOrdinal("Title"));
                string aFirst   = data.GetString(data.GetOrdinal("AuthorFirstName"));
                string aLast    = data.GetString(data.GetOrdinal("AuthorLastName"));
                string isbn     = data.GetString(data.GetOrdinal("ISBN"));
                int    copyYear = data.GetInt16(data.GetOrdinal("Copyrightyear"));
                string pub      = data.GetString(data.GetOrdinal("PublisherName"));
                string gen      = data.GetString(data.GetOrdinal("Genre"));

                // TODO Add in the book quality and call the correct Book constructor

                b = new BookInfo(title, new Author(aFirst, aLast),
                                 isbn, gen, pub, copyYear);
            }
        }
 private void GrabSearchBookInfo(SqlCommand c, ref List <BookInfo> ss)
 {
     using (SqlDataReader data = c.ExecuteReader())
     {
         while (data.Read())
         {
             bool isCheckedOut = data.GetInt32(data.GetOrdinal("CheckedOut")) != 0;
             if (!isCheckedOut)
             {
                 string   title    = data.GetString(data.GetOrdinal("Title"));
                 string   aFirst   = data.GetString(data.GetOrdinal("AuthorFirstName"));
                 string   aLast    = data.GetString(data.GetOrdinal("AuthorLastName"));
                 string   isbn     = data.GetString(data.GetOrdinal("ISBN"));
                 int      copyYear = data.GetInt16(data.GetOrdinal("Copyrightyear"));
                 string   pub      = data.GetString(data.GetOrdinal("PublisherName"));
                 string   gen      = data.GetString(data.GetOrdinal("Genre"));
                 BookInfo b        = new BookInfo(title, new Author(aFirst, aLast),
                                                  isbn, gen, pub, copyYear);
                 ss.Add(b);
             }
         }
     }
 }
Example #26
0
        private async Task ExploringStep(CancellationToken cancellationToken)
        {
            await RandomDelay(cancellationToken);

            var randomBook = await _booksRepository.GetRandomNotFilledBookAsync();

            await RandomDelay(cancellationToken);

            var bookExists = _seeker.ReadBookInfo(randomBook);

            if (!bookExists)
            {
                BookInfo.MarkAsNotFound(randomBook);
            }
            else
            {
                if (randomBook?.BookType == null)
                {
                    throw new InvalidOperationException(
                              "something went wrong, book properties was not read");
                }

                if (randomBook.ClosureDate.Length <= 4)
                {
                    var properties = _seeker.ReadProperties();
                    randomBook.AddNewProperties(properties);
                }
            }

            await _booksRepository.UpdateBookAsync(randomBook);

            await _booksRepository.AddPropertyFromBookAsync(randomBook);

            await RandomDelay(cancellationToken);

            _seeker.BackToCriteria();
        }
Example #27
0
        /// <summary>
        /// Scrape any notable quotes from Goodreads and grab ratings if missing from book info
        /// Modifies curBook.
        /// </summary>
        public async Task GetExtrasAsync(BookInfo curBook, IProgressBar progress = null, CancellationToken cancellationToken = default)
        {
            var grDoc = await _httpClient.GetPageAsync(curBook.DataUrl, cancellationToken);

            if (curBook.notableClips == null)
            {
                curBook.notableClips = (await GetNotableClipsAsync("", grDoc, progress, cancellationToken).ConfigureAwait(false))?.ToList();
            }

            //Add rating and reviews count if missing from Amazon book info
            var metaNode = grDoc.DocumentNode.SelectSingleNode("//div[@id='bookMeta']");

            if (metaNode != null && curBook.AmazonRating == 0)
            {
                var goodreadsRating = metaNode.SelectSingleNode("//span[@class='value rating']")
                                      ?? metaNode.SelectSingleNode(".//span[@itemprop='ratingValue']");
                if (goodreadsRating != null)
                {
                    curBook.AmazonRating = Math.Round(float.Parse(goodreadsRating.InnerText), 2);
                }
                var passagesNode = metaNode.SelectSingleNode(".//a[@class='actionLinkLite votes' and @href='#other_reviews']")
                                   ?? metaNode.SelectSingleNode(".//span[@class='count value-title']");
                if (passagesNode != null)
                {
                    var match = Regex.Match(passagesNode.InnerText, @"(\d+|\d{1,3}([,\.]\d{3})*)(?=\s)");
                    if (match.Success)
                    {
                        curBook.Reviews = int.Parse(match.Value.Replace(",", "").Replace(".", ""));
                    }
                }
                passagesNode = metaNode.SelectSingleNode(".//meta[@itemprop='reviewCount']");
                if (passagesNode != null && int.TryParse(passagesNode.GetAttributeValue("content", null), out var reviews))
                {
                    curBook.Reviews = reviews;
                }
            }
        }
Example #28
0
        // TODO: All calls to Amazon should check for the captcha page (or ideally avoid it somehow)
        public static async Task <BookInfo> SearchBook(string title, string author, string TLD)
        {
            BookInfo result = null;

            if (title.IndexOf(" (") >= 0)
            {
                title = title.Substring(0, title.IndexOf(" ("));
            }
            //Search "all" Amazon
            string searchUrl = String.Format(@"https://www.amazon.{0}/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords={1}",
                                             TLD, Uri.EscapeDataString(title + " " + author));
            HtmlDocument searchDoc = new HtmlDocument();

            searchDoc.LoadHtml(await HttpDownloader.GetPageHtmlAsync(searchUrl));
            HtmlNode node     = searchDoc.DocumentNode.SelectSingleNode("//li[@id='result_0']");
            HtmlNode nodeASIN = node?.SelectSingleNode(".//a[@title='Kindle Edition']");

            if (nodeASIN == null)
            {
                node     = searchDoc.DocumentNode.SelectSingleNode("//li[@id='result_1']");
                nodeASIN = node?.SelectSingleNode(".//a[@title='Kindle Edition']");
            }
            //At least attempt to verify it might be the same book?
            if (node != null && nodeASIN != null && node.InnerText.IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                Match foundASIN = Regex.Match(nodeASIN.OuterHtml, "(B[A-Z0-9]{9})");
                node = node.SelectSingleNode(".//div/div/div/div[@class='a-fixed-left-grid-col a-col-right']/div/a");
                if (node != null)
                {
                    result = new BookInfo(node.InnerText, author, foundASIN.Value);
                    string trimUrl = nodeASIN.GetAttributeValue("href", "");
                    trimUrl          = trimUrl.Substring(0, trimUrl.IndexOf(foundASIN.Value) + foundASIN.Length);
                    result.amazonUrl = trimUrl; // Grab the true link for good measure
                }
            }
            return(result);
        }
Example #29
0
        public void InstallFreshGuid_works()
        {
            var          jsonPath     = Path.Combine(_folder.Path, BookInfo.MetaDataFileName);
            const string originalGuid = "3988218f-e01c-4a7a-b27d-4a31dd632ccb";
            const string metaData     = @"{'bookInstanceId':'" + originalGuid + @"','experimental':'false','suitableForMakingShells':'true'}";

            File.WriteAllText(jsonPath, metaData);
            var bookOrderPath = BookInfo.BookOrderPath(_folder.Path);

            File.WriteAllText(bookOrderPath, metaData);
            Assert.That(File.Exists(bookOrderPath), Is.True);

            // SUT
            BookInfo.InstallFreshInstanceGuid(_folder.Path);

            // Verification
            var bi = new BookInfo(_folder.Path, true);

            Assert.That(bi.Id, Is.Not.EqualTo(originalGuid));
            Assert.That(bi.IsExperimental, Is.False);
            Assert.That(bi.IsSuitableForMakingShells);
            Assert.That(File.Exists(bookOrderPath), Is.False);
            Assert.That(File.Exists(Path.Combine(_folder.Path, "meta.bak")), Is.False);
        }
Example #30
0
        private void AddBookInfo(string folderPath)
        {
            try
            {
                //this is handy when windows explorer won't let go of the thumbs.db file, but we want to delete the folder
                if (Directory.GetFiles(folderPath, "*.htm").Length == 0 && Directory.GetFiles(folderPath, "*.html").Length == 0)
                {
                    return;
                }
                var bookInfo = new BookInfo(folderPath, Type == CollectionType.TheOneEditableCollection);

                _bookInfos.Add(bookInfo);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                var jsonPath = Path.Combine(folderPath, BookInfo.MetaDataFileName);
                Logger.WriteError("Reading " + jsonPath, e);
                try
                {
                    Logger.WriteEvent(jsonPath + " Contents: " + System.Environment.NewLine + RobustFile.ReadAllText(jsonPath));
                }
                catch (Exception readError)
                {
                    Logger.WriteError("Error reading " + jsonPath, readError);
                }

                //_books.Add(new ErrorBook(e, path, Type == CollectionType.TheOneEditableCollection));
                _bookInfos.Add(new ErrorBookInfo(folderPath, e)
                {
                });
            }
        }
Example #31
0
        FindResultInfo FindBookFiles(BookInfo incoming, FindResultInfo foundResult)
        {
            string [] foundTypes = foundResult.Book.Types.ToArray();

            IEnumerable <string> missing = incoming.Types.Where(t => !foundTypes.Contains(t));

            if (missing.Any())
            {
                return(new FindResultInfo
                {
                    Book = foundResult.Book,
                    Status = MatchStatus.NewFiles,
                    NewTypes = missing
                });
            }
            else
            {
                return(new FindResultInfo
                {
                    Book = foundResult.Book,
                    Status = MatchStatus.UpToDate
                });
            }
        }
Example #32
0
        public async Task <BookInfo> GetBookInfoAsync(string isbn)
        {
            var url     = String.Format(infoUrl, isbn);
            var content = await client.GetStringAsync(url);

            var json      = JObject.Parse(content);
            var totalItem = json["totalItems"].Value <int>();

            if (totalItem == 0)
            {
                return(null);
            }

            var obj = json["items"][0]["volumeInfo"];

            var info = new BookInfo()
            {
                Title     = obj["title"].Value <string>(),
                ISBN      = isbn,
                Thumbnail = obj["imageLinks"]["thumbnail"].Value <string>(),
            };

            return(info);
        }
Example #33
0
        public ActionResult EditBookInfo(string biId, string name, string author, DateTime publishDate, string type, decimal price, decimal original, string describe)
        {
            BookInfo bi = bookManager.FindById(biId);

            bi.Name        = name;
            bi.Author      = author;
            bi.PublishDate = publishDate;
            bi.Type        = type;
            bi.Price       = price;
            bi.Original    = original;
            bi.Describe    = describe;
            if (Session["bookImgPath"] != null && Session["bookImgPath"].ToString() != "")
            {
                bi.ISBN = (string)Session["bookImgPath"];
                Session["bookImgPath"] = null;
            }
            bool result = bookManager.UpdateBookInfo(bi);

            if (result)
            {
                TempData["mess"] = "图书‘" + bi.Name + "’修改成功";
            }
            return(Redirect("Index"));
        }
Example #34
0
        protected override void Seed(BooksLibraryContext context)
        {
            base.Seed(context);

            AuthorIndentity authorIndentity = new AuthorIndentity()
            {
                Login = "******", Password = "******"
            };

            AuthorInfo author = new AuthorInfo()
            {
                AuthorIndentity = authorIndentity,
                LastName        = "Richter",
            };

            PublisherInfo publisher = new PublisherInfo()
            {
                Name = "Grn LLC"
            };

            BookInfo book = new BookInfo()
            {
                Title         = "CLR via C#",
                Date          = new DateTime(2018, 10, 10),
                Price         = 5000,
                PublisherInfo = publisher
            };

            book.Authors = new List <AuthorInfo>()
            {
                author
            };

            context.Books.Add(book);
            context.SaveChanges();
        }
Example #35
0
        private void ShowInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Books.SelectedItems.Count != 0)
                {
                    dynamic selectedItem = Books.SelectedItems[0];
                    if (selectedItem != null)
                    {
                        int      bookId   = (int)selectedItem.Id;
                        BookInfo bookInfo = new BookInfo(bookId, userId);

                        if (bookInfo.ShowDialog() == true)
                        {
                            MessageBox.Show("The book has been added to your wishlist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void textBox9_TextChanged_1(object sender, EventArgs e)
        {
            String circuBookNo = textBox9.Text;

            textBox11.Text   = "";
            textBox10.Text   = "";
            label7.Text      = "";
            label7.ForeColor = Color.Red;
            bookBorrowAble   = false;
            checkBorrowAble();
            if (circuBookNo.Length == 10)
            {
                try
                {
                    CircuBookClass book = BookInfo.queryABookInfo(circuBookNo);
                    textBox11.Text = book.BookName;
                    textBox10.Text = book.PublishingHouse;
                }
                catch (System.ArgumentOutOfRangeException)
                {
                    label7.Text = "图书标识号有误!";
                    return;
                }
                if (!AS.BookBorrowAble(textBox9.Text))
                {
                    label7.Text = "书籍已被借出!";
                }
                else
                {
                    label7.ForeColor = Color.Green;
                    label7.Text      = "该书籍可借阅";
                    bookBorrowAble   = true;
                    checkBorrowAble();
                }
            }
        }
Example #37
0
        /// <summary>
        /// Add book to file.
        /// </summary>
        /// <param name="book"> Adding book.</param>
        public void AppendBookToFile(BookInfo book)
        {
            if (book == null)
            {
                throw new ArgumentNullException($"Book is null");
            }

            logger.Info("Saving book in file");
            try
            {
                using var binaryWriter = new BinaryWriter(File.Open(this.path, FileMode.Append, FileAccess.Write, FileShare.None));
                Writer(binaryWriter, book);
                logger.Info("Save book in file successfully.");
            }
            catch (IOException ex)
            {
                logger.Info("IO exception while adding book in Binary Repository (BookListStorage):");
                logger.Info(ex.Message);
                logger.Error(ex.StackTrace);
                throw;
            }
            catch (ArgumentNullException ex)
            {
                logger.Info("ArgumentNullException while adding book in Binary Repository (BookListStorage):");
                logger.Info(ex.Message);
                logger.Error(ex.StackTrace);
                throw;
            }
            catch (Exception ex)
            {
                logger.Info("Unhandled exception while adding book in Binary Repository (BookListStorage):");
                logger.Info(ex.Message);
                logger.Error(ex.StackTrace);
                throw;
            }
        }
Example #38
0
        private static Book MakeBook(CollectionSettings collectionSettings, string sourceBookFolderPath)
        {
            var xmatterLocations = new List <string>();

            xmatterLocations.Add(ProjectContext.XMatterAppDataFolder);
            xmatterLocations.Add(FileLocator.GetDirectoryDistributedWithApplication(kpathToSHRPTemplates));
            xmatterLocations.Add(FileLocator.GetDirectoryDistributedWithApplication("xMatter"));
            var locator = new BloomFileLocator(collectionSettings, new XMatterPackFinder(xmatterLocations), new string[] {});

            var starter = new BookStarter(locator,
                                          path =>
                                          new BookStorage(path, locator, new BookRenamedEvent(),
                                                          collectionSettings),
                                          collectionSettings);
            var pathToFolderOfNewBook = starter.CreateBookOnDiskFromTemplate(sourceBookFolderPath, collectionSettings.FolderPath);

            var newBookInfo = new BookInfo(pathToFolderOfNewBook, false /*saying not editable works us around a langdisplay issue*/);

            BookStorage bookStorage = new BookStorage(pathToFolderOfNewBook, locator, new BookRenamedEvent(), collectionSettings);
            var         book        = new Book(newBookInfo, bookStorage, null,
                                               collectionSettings, null, null, null, null);

            return(book);
        }
 Book IBookService.CreateBook(BookInfo bookInfo)
 {
     var book = new Book(bookInfo);
     _repository.Add(book);
     return book;
 }
Example #40
0
    public void Initialize(BookInfo bookInfo)
    {
        this.idlePosition = Vector3.zero;
        this.bookInfo = bookInfo;

        itemImage.GetComponent<SpriteRenderer>().sprite = GetItemSprite(bookInfo.FileName);
        transform.position = idlePosition;
    }
Example #41
0
 public SearchWhirlwindItem(WhirlwindItem wwItem)
 {
     this.bookInfo = wwItem.BookInfo;
     this.sprite = wwItem.Sprite;
 }
Example #42
0
 public override void visit(BookInfo bookInfo)
 {
     this.setTitleBlurb("SB-Book: " + bookInfo.getTitleName());
 }
Example #43
0
 public void Insert(BookInfo book)
 {
     Books.InsertOnSubmit(book);
     SubmitChanges();
 }
Example #44
0
    // initialize important information passed from the belt this item belongs to
    public void Initialize(WhirlwindBelt belt, float radius, Vector3 idlePosition, BookInfo bookInfo)
    {
        this.belt = belt;
        this.radius = radius;
        this.idlePosition = idlePosition;
        this.bookInfo = bookInfo;

        itemImage.GetComponent<SpriteRenderer>().sprite = GetItemSprite(bookInfo.FileName);

        transform.position = idlePosition;
    }
Example #45
0
    public List<BookInfo> GetBookListByCommand(string command)
    {
        //the result
        List<BookInfo> res = new List<BookInfo>();

        //init the command
        MySqlCommand dbcmd  = new MySqlCommand( command , connection );

        // execute the command
        // turn the result to the List<BookInfo>
        using(MySqlDataReader reader = dbcmd.ExecuteReader())
        {
            try
            {
                while(reader.Read())
                {
                    BookInfo info = new BookInfo();

                    for ( int i = 0 ; i < reader.FieldCount; ++ i )
                    {
                        info.AddData(i, reader.GetString(i));
                    }

                    res.Add(info);
                }
            }
            catch(Exception e)
            {
                 Debug.LogError(e.Message);
            }
        }

        //Debug.Log("Get " + res.Count + " books in total");

        return res;
    }
Example #46
0
    public void CreateBookInfoBar(RectTransform parent, int index , BookInfo info = null)
    {
        GameObject obj = Instantiate(bookInfoBarPrefab) as GameObject;
        RectTransform recTrans = obj.GetComponent<RectTransform>();
        recTrans.parent = parent;
        Vector3 pos = Vector3.zero;
        pos.y = - index * barHeight;
        recTrans.localPosition = pos;

        Text[] texts = obj.GetComponentsInChildren<Text>();
        foreach(Text t in texts)
        {
            t.DOFade(0, 1f).From().SetDelay(0.2f * index);
            if (info != null)
            {
                if (t.name == "Title")
                    t.text = info.Title;
                if (t.name == "Author")
                    t.text = info.Author;
                if (t.name == "Time")
                    t.text = info.TimeFrom.ToString() + " TO " + info.TimeTo.ToString();
                if (t.name == "Note")
                    t.text = info.Note;
                if (t.name == "Genre")
                    t.text = info.genre;
                if (t.name == "Location")
                    t.text = info.Location;

            }
        }
    }
Example #47
0
 public abstract void visit(BookInfo bookInfo);
Example #48
0
            public PropExt( XParameter Param )
                : base( Param )
            {
                string SType = Param.GetValue( "Type" );
                this.SubProc = new ProcManager();

                XParameter Sub = Param.Parameter( "SubProc" );
                if ( Sub != null ) SubProc.ReadParam( Sub );

                PType = Enum.GetValues( BINF )
                    .Cast<BookInfo>()
                    .FirstOrDefault( x => Enum.GetName(  BINF, x ) == SType );
            }
Example #49
0
 public PropExt( BookInfo PType = BookInfo.Others )
 {
     this.PType = PType;
     this.SubProc = new ProcManager();
     Enabled = true;
 }
Example #50
0
    public List<BookInfo> Search(BookInfo book)
    {
        if (book == null)
            book = new BookInfo();

        return SearchBySubject(book.GetSubjects());

        // string command = "SELECT * FROM `" + tableName + "` WHERE "
         //    	+ " `Name` LIKE '%" +  book.Author + "%' OR"
         //    	+ " ( `Time` <= " + (book.Time + 2).ToString() + " AND `Time` >= " + (book.Time - 2).ToString() + ") OR"
         //    	+ " `Location` LIKE '%" +  book.Location + "%' ";

        // return EvaluateBookByBook( GetBookListByCommand(command) , book );
    }
Example #51
0
 public void Delete(BookInfo book)
 {
     Books.DeleteOnSubmit(book);
     SubmitChanges();
 }
Example #52
0
    // this is only called when database is not connected; creates placeholder data for testing only
    List<WhirlwindBeltInfo> OfflinePlaceHolderSearch(int numBelts)
    {
        string[] filenames = WhirlwindItem.GetAllItemFileNames();
        List<WhirlwindBeltInfo> retVal = new List<WhirlwindBeltInfo>();

        Debug.Assert(filenames.Length > 0);

        string[] columns = {"title", "title_subtitle", "name", "pub_date", "pub_place", "note", "scope_content", "history"};

        for (int i = 0; i < numBelts; i++) {
            int amount = (int)UnityEngine.Random.Range(15f, 30f);
            List<BookInfo> b = new List<BookInfo>();
            for (int j = 0; j < amount; j++) {
                BookInfo bi = new BookInfo();
                string fn = "placeholder";
                while (fn.Equals("placeholder")) {
                    fn = filenames[UnityEngine.Random.Range(0, filenames.Length)];
                }

                bi.AddData("file_name", fn);
                for (int c = 0; c < columns.Length; c++) {
                    bi.AddData(columns[c], "PLACEHOLDER");
                }
                b.Add(bi);
            }
            retVal.Add(new WhirlwindBeltInfo(b, "PLACEHOLDER " + i));
        }

        return retVal;
    }
Example #53
0
 public void Update(BookInfo book)
 {
     var old = Books.Single(item => item.ID == book.ID);
     old.CopyProperties(book);
     this.SubmitChanges(ConflictMode.ContinueOnConflict);
 }
Example #54
0
    // search by single bookinfo, this is for enlarge view
    public List<WhirlwindBeltInfo> Search(BookInfo inputInfo, int numBelts)
    {
        Debug.Assert(inputInfo != null);

        if (connectionSuccess) {
            List<WhirlwindBeltInfo> retVal = new List<WhirlwindBeltInfo>();

            List<BookInfo> b;
            WhirlwindBeltInfo wwbi;

            // search through the columns
            for (int i = 0; i < columns.Length; i++) {
                // make a query
                if (columns[i].Equals("subject")) {
                    b = connector.SearchBySubject(inputInfo.GetSubjects());
                } else {
                    b = connector.Search(inputInfo.GetData(columns[i]), columns[i]);
                }

         				// remove ones that are the same as the search term itself
         				for (int j = 0; j < b.Count; j++) {
         					if (b[j].FileName.Equals(inputInfo.FileName)) {
         						b.Remove(b[j]);
         						break;
         					}
         				}

         				// limits the items count
                b = b.GetRange(0, Mathf.Min(b.Count, maxItemsPerBelt));
                wwbi = new WhirlwindBeltInfo(b, columnTitles[i]);
                retVal.Add(wwbi);
            }

            // sort the search results by popularity
            retVal.Sort(delegate(WhirlwindBeltInfo b1, WhirlwindBeltInfo b2) { return b2.InfosCount.CompareTo(b1.InfosCount); });

            // return the top N results (pad if necessary)
            retVal = retVal.GetRange(0, numBelts);
            return retVal;
        } else {
            return OfflinePlaceHolderSearch(numBelts);
        }
    }
Example #55
0
 public Book CreateBook(BookInfo bookInfo)
 {
     using (var context = _contextManager.GetContext())
     {
         var book = new Book(bookInfo);
         context.Add(book);
         context.SaveChanges();
         return book;
     }
 }
 private void OnAdd()
 {
     //var aBook = new Book
     //    {
     //        Isbn = 1111111111111,
     //        Details = new BookInfo {Publisher = new Publisher(), Author = new Author()},
     //        PurchaseItem = new PurchaseItems()
     //    };
     //_ctx.Books.Add(aBook);
     var aAut = new Author { FirstName = "<Enter First Name>", LastName = "<Enter Last Name>" };
     var aPub = new Publisher {  Name="<Enter Publisher>"};
     var aBookInfo = new BookInfo { Title = "<Enter Title>", Author = aAut, Publisher = aPub, Isbn = 1};
     var aPur = new Purchase { Date = DateTime.Now, Id=Guid.NewGuid()};
     var aPi = new PurchaseItems { Id = aPur.Id, Purchase = aPur };
     //var abi = _ctx.BookInfoes.Find(aBookInfo.Isbn);
     //if (abi == null) _ctx.BookInfoes.Add(aBookInfo);
     //abi = _ctx.BookInfoes.Find(aBookInfo.Isbn);
     var aBook = new Book { Id = Guid.NewGuid(), Details = aBookInfo, Earning = 0, PurchaseItem = aPi };
        _ctx.Books.Add(aBook);
     _books.MoveCurrentTo(aBook);
 }