示例#1
0
    public string GetCoverImage(EBook book)
    {
        HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
        WebRequestHandler            wrh     = new WebRequestHandler();
        WebClientHandler             wch     = new WebClientHandler();
        EmailHandler eh = new EmailHandler();

        //Search URL: https://www.goodreads.com/search?q=
        //Search Result URL: /book/show/77566.Hyperion
        //has the link to the page with the image we want
        string hostSiteSearchPage = "https://www.goodreads.com/search?q=";

        string htmlData = wrh.ProcessWebRequest(hostSiteSearchPage, book.uriBookTitle);

        string coverImageLink = GetCoverImageLink(htmlData, book);

        //Page that has the image we want
        hostSiteSearchPage = "https://www.goodreads.com";

        htmlData = wrh.ProcessWebRequest(hostSiteSearchPage, coverImageLink);
        htmlDoc.LoadHtml(htmlData);
        var link = htmlDoc.DocumentNode.Descendants("img")
                   .First(x => x.Attributes["id"] != null &&
                          x.Attributes["id"].Value == "coverImage");
        string coverImageHref = link.Attributes["src"].Value;

        if (coverImageHref != "")
        {
            var temp = coverImageHref.Split('.');
            book.coverImageLocation += "." + temp[temp.Length - 1];
            return(coverImageHref);
        }
        return("");
    }
示例#2
0
        public IHttpActionResult PutEBook(int id, EBook eBook)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != eBook.EBookId)
            {
                return(BadRequest());
            }

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

            try
            {
                db.SaveChanges();
                LuceneService.UpdateLuceneDoc(eBook);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EBookExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
示例#3
0
    public string GetCoverImageLink(string htmlData, EBook book)
    {
        Regex reg = new Regex(@"(\/book\/show\/[0-9]*." + (book.bookTitle.Replace(' ', '_')) + "?)");
        Match match;

        HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

        //Loads entire page
        htmlDoc.LoadHtml(htmlData);

        //All tables elements in the document
        foreach (HtmlNode table in htmlDoc.DocumentNode.SelectNodes("//table"))
        {
            foreach (HtmlNode row in table.SelectNodes("tr"))
            {
                foreach (HtmlNode cell in row.SelectNodes("th|td"))
                {
                    match = reg.Match(cell.InnerHtml);
                    if (match.Success)
                    {
                        return(match.ToString() + "?");
                    }
                    //var temp = cell.SelectNodes("//*[contains(., 'href=\"/book/show/ ')]"); //download link on next page
                }
            }
        }
        return("No Link Found");
    }
示例#4
0
 public void Download(string downloadPage, string filePath, EBook book)
 {
     try
     {
         WebClient   wc      = new WebClient();
         HTMLScraper scraper = new HTMLScraper();
         wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
         wc.DownloadProgressChanged += (sender, ex) =>
         {
             lblDownloadPercent.Text = "Downloaded " + ex.BytesReceived + "b of " + ex.TotalBytesToReceive + "b " + book.fileType;
         };
         wc.DownloadFileCompleted += (sender, ex) =>
         {
             if (ex.Cancelled)
             {
                 //TODO log error
             }
             else
             {
                 _completed = true;
             }
         };
         wc.DownloadFileAsync(new Uri(downloadPage), filePath);
         Thread.Sleep(10000);
         //while (!_completed)
         //    Thread.Sleep(1000);
     }
     catch (Exception e)
     {
     }
 }
示例#5
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,BookName,Genre,AuthorId")] EBook eBook)
        {
            if (id != eBook.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(eBook);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EBookExists(eBook.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["AuthorId"] = new SelectList(_context.Authors, "ID", "ID", eBook.AuthorId);
            return(View(eBook));
        }
示例#6
0
        private bool InsertBookRecord(ImportObject importerObject)
        {
            try
            {
                ImportObject importerObj = importerObject;
                bool         exists      = _bookRepository.CheckIfBookExistsByNameWriterAndByPublisher(importerObj.BookName, importerObj.AuthorName, importerObj.PublisherName);

                EBook book = new EBook();

                if (!exists)
                {
                    GenerateBookRecord(importerObj, ref book);

                    _bookRepository.CreateEntity(book);
                }
                else
                {
                    book = _bookRepository.GetBookByNameAndByPublisher(importerObj.BookName, importerObj.AuthorName, importerObj.PublisherName);

                    if (!book.Users.Contains(importerObj.User))
                    {
                        book.Users.Add(importerObj.User);
                        _bookRepository.UpdateEntity(book);
                    }
                }

                return(true);
            }
            catch (Exception error)
            {
                _logger.Error("Integration Error while doing InsertBookRecord", error);

                return(false);
            }
        }
示例#7
0
文件: Form1.cs 项目: Krypton091/SE245
        /// <summary>
        /// NEW - Constructor that Receives an EBook ID....this means we need to look up the data and populate fields (View/Edit/Del)
        /// </summary>
        /// <param name="intEBook_ID"></param>
        public Form1(int intEBook_ID)
        {
            InitializeComponent();  //Creates and init's all form objects

            //Gather info about this one person and store it in a datareader
            EBook         temp = new EBook();
            SqlDataReader dr   = temp.FindOneEBook(intEBook_ID);

            //Use that info to fill out the form
            //Loop thru the records stored in the reader 1 record at a time
            // Note that since this is based on one person's ID, then we
            //  should only have one record
            while (dr.Read())
            {
                //Take the Name(s) from the datareader and copy them
                // into the appropriate text fields
                txtTitle.Text        = dr["Title"].ToString();
                txtAuthorFirst.Text  = dr["AuthorFirst"].ToString();
                txtAuthorLast.Text   = dr["AuthorLast"].ToString();
                txtEmail.Text        = dr["Email"].ToString();
                txtPages.Text        = dr["Pages"].ToString();
                txtBookmarkPage.Text = dr["BookmarkPage"].ToString();
                lblEBook_ID.Text     = dr["EBook_ID"].ToString();

                dtpDatePublished.Value     = DateTime.Parse(dr["DatePublished"].ToString());
                dtpDateRentalExpires.Value = DateTime.Parse(dr["DateRentalExpires"].ToString());

                //We added this one to store the ID in a new label
                lblEBook_ID.Text = dr["EBook_ID"].ToString();
            }
        }
        static void Main(string[] args)
        {
            //Book newBook = new Book();
            //User damjan = new User();
            //BookService bookService = new BookService();
            //EBook electronicBook = new EBook();
            //We are creating regular book
            Book bookWithId = new Book("title", "author", BookGenre.Adventure, 10.5, DateTime.Now, 200);
            //Calling the regular book GetBookInfo method
            string regularBookInfo = bookWithId.GetBookInfo();

            Console.WriteLine(regularBookInfo);
            //Creating e-book
            EBook electronicBook = new EBook()
            {
                Author        = "electronic book author",
                Genre         = BookGenre.Comedy,
                NumberOfPages = 300,
                Title         = "Some e book",
                Price         = 17.3,
                PublishedDate = new DateTime(1996, 04, 03),
                MemorySize    = 50
            };
            //Calling the overriden GetBookInfo method
            string electornicBookInfo = electronicBook.GetBookInfo();

            Console.WriteLine(electornicBookInfo);
            EBook  eBook2     = new EBook("Kindle book", "Stephen King", BookGenre.Adventure, 13.7, new DateTime(1994, 10, 11), 400, 80);
            string ebook2Info = eBook2.GetBookInfo();

            Console.WriteLine(ebook2Info);
            KindleEbook kindleEBookObj = new KindleEbook();

            Console.ReadLine();
        }
示例#9
0
    private void LoadEBooks()
    {
        List <EBook> AvailableEBookList = EBook.GetAllActiveEBooks();

        if (AvailableEBookList.Count == 0)
        {
            NoEBooksPanelWrapper.Visible = true;
            NoEBookspanel.Visible        = true;
            NoEBookspanel.Text           = U6004.NOEBOOKS;
        }
        else
        {
            try
            {
                foreach (EBook eBook in AvailableEBookList)
                {
                    EBooksLiteral.Controls.Add(GetAdHTML(eBook));
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
                throw ex;
            }
        }
    }
示例#10
0
文件: Form1.cs 项目: Krypton091/SE245
        /// <summary>
        /// Form code to create an oject and call it's update method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            EBook temp = new EBook();

            //Getting the strings from the form and setting them in object
            temp.Title       = txtTitle.Text;
            temp.AuthorFirst = txtAuthorFirst.Text;
            temp.AuthorLast  = txtAuthorLast.Text;
            temp.Email       = txtEmail.Text;
            temp.EBook_ID    = Convert.ToInt32(lblEBook_ID.Text);


            //Getting te dates from the datetime pickers
            temp.DatePublished     = dtpDatePublished.Value;
            temp.DateRentalExpires = dtpDateRentalExpires.Value;

            //**************************************************************************
            //get the string from page # textboxes,convert to ints, set their values
            //**************************************************************************
            int  intTempPages;
            bool blnResult = Int32.TryParse(Console.ReadLine(), out intTempPages);

            if (blnResult == false)
            {
                lblFeedback.Text += "Sorry incorrect page #.  Please try again. (Ex: 214) ";
            }
            else
            {
                temp.Pages = intTempPages;
            }
            //**************************************************************************


            //**************************************************************************
            //get the string from Bookmark page # textboxes,convert to ints, set their values
            //**************************************************************************
            int intBMPage;

            blnResult = Int32.TryParse(Console.ReadLine(), out intBMPage);

            if (blnResult == false)
            {
                lblFeedback.Text += "Sorry incorrect Bookmark page #.  Please try again. (Ex: 214) ";
            }
            else
            {
                temp.BookmarkPage = intBMPage;
            }
            //**************************************************************************


            if (!temp.Feedback.Contains("ERROR:"))
            {
                lblFeedback.Text = temp.UpdateARecord();   //if no errors weh setting values, then perform the insertion into db
            }
            else
            {
                lblFeedback.Text = temp.Feedback;       //else...dispay the error msg
            }
        }
示例#11
0
        static void InitializeEBook(string path)
        {
            System.Console.Clear();
            var eBook = new EBook(path);

            eBook.TableOfContents = eBook.GetTableOfContents();
            System.Console.WriteLine($"Mimetype is {(!eBook.IsMimetypeValid() ? "not " : "")}valid.");
            System.Console.WriteLine($"Content location is {eBook.ContentLocation}.");
            System.Console.WriteLine($"Cover location is is {eBook.CoverLocation}.");
            System.Console.WriteLine($"Alternative Title: {eBook.Metadata.AlternativeTitle}");
            System.Console.WriteLine($"Audience: {eBook.Metadata.Audience}");
            System.Console.WriteLine($"Available: {eBook.Metadata.Available}");
            System.Console.WriteLine($"Contributor: {eBook.Metadata.Contributor}");
            System.Console.WriteLine($"Created: {eBook.Metadata.Created}");
            System.Console.WriteLine($"Creator: {eBook.Metadata.Creator}");
            System.Console.WriteLine($"Date: {eBook.Metadata.Date}");
            System.Console.WriteLine($"Description: {eBook.Metadata.Description}");
            System.Console.WriteLine($"Language: {eBook.Metadata.Language}");
            System.Console.WriteLine($"Title: {eBook.Metadata.Title}");
            System.Console.WriteLine();
            System.Console.WriteLine("Table of Contents:");

            foreach (var navPoint in eBook.TableOfContents.FlatItems)
            {
                System.Console.WriteLine(navPoint.Text);
            }

            System.Console.Write(eBook.GetContents(eBook.Spine.Last(), true));
            System.Console.ReadKey();
        }
示例#12
0
        public void WhenUpdateBook_ReturnSuccess(BookDto input)
        {
            EBook book = new EBook
            {
                Name        = "DEMO",
                AuthorId    = 1,
                PublisherId = 1,
                SeriesId    = 1,
                PublishDate = 1,
                GenreId     = 1,
                ShelfId     = 1,
                RackId      = 1,
            };


            _bookRepository.Setup(m => m.GetOne(input.Id)).Returns(book);

            _bookRepository.Setup(m => m.UpdateEntity(book)).Returns(true);


            _bookServiceApplication = new BookServiceApplication(_bookRepository.Object, _userRepository.Object);

            bool result = _bookServiceApplication.UpdateBook(input);

            Assert.True(result);
        }
        public async Task <IActionResult> Edit(int id, [Bind("BookName,Picture,Path,Datetime,ID,Author")] EBook eBook)
        {
            if (id != eBook.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(eBook);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EBookExists(eBook.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(eBook));
        }
 public vSearchResultModel(EBook model)
 {
     this.ID = model.ID;
     this.Title = model.Title;
     this.URL = "/EBook/Show/" + model.ID;
     this.Sumamry = Helpers.String.SubString(model.Description, 50, "...");
     this.Time = model.Time;
 }
示例#15
0
        public static void UpdateLuceneDoc(EBook eBook)
        {
            DeleteLuceneDoc(eBook);

            var doc = new Document();

            doc = SetDocumentFields(eBook);
            writer.AddDocument(doc);
            writer.Commit();
        }
示例#16
0
        public IHttpActionResult GetEBook(int id)
        {
            EBook eBook = db.EBooks.Find(id);

            if (eBook == null)
            {
                return(NotFound());
            }

            return(Ok(eBook));
        }
示例#17
0
文件: Form1.cs 项目: Krypton091/SE245
        /// <summary>
        /// Form code to delete a record based on its ID
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            Int32 intEBook_ID = Convert.ToInt32(lblEBook_ID.Text);  //Get the ID from the Label

            //Create a EBook so we can use the delete method
            EBook temp = new EBook();

            //Use the EBook ID and pass it to the delete function
            // and get the number of records deleted
            lblFeedback.Text = temp.DeleteOneEBook(intEBook_ID);
        }
示例#18
0
        public override int GetHashCode()
        {
            int       hashcode = 1;
            const int prime    = 31;

            hashcode = hashcode * prime + Name.GetHashCode();
            hashcode = hashcode * prime + Grade;
            hashcode = hashcode * prime + EBook.GetHashCode();

            return(hashcode);
        }
示例#19
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            //Get Data
            EBook temp = new EBook();
            //Perform the search we created in EBook class and store the returned dataset
            DataSet ds = temp.SearchEBooks(txtTitle.Text, txtAuthorLast.Text);

            //Display data (dataset)
            dgvResults.DataSource = ds;                                  //point datagrid to dataset
            dgvResults.DataMember = ds.Tables["Ebooks_Temp"].ToString(); // What table in the dataset?
        }
示例#20
0
    protected UserControl GetAdHTML(EBook eBook)
    {
        UserControl objControl    = (UserControl)Page.LoadControl("~/Controls/Misc/EBook.ascx");
        var         parsedControl = objControl as IEBookObjectControl;

        parsedControl.Object = eBook;

        parsedControl.DataBind();

        return((UserControl)parsedControl);
    }
示例#21
0
        public static void RegisterNewLuceneDoc(EBook eBook)
        {
            var doc = new Document();

            doc = SetDocumentFields(eBook);
            writer.AddDocument(doc);

            writer.Optimize();
            writer.Flush(true, true, true);
            writer.Commit();
        }
        public async Task <IActionResult> Create([Bind("BookName,Picture,Path,Datetime,ID,Author")] EBook eBook)
        {
            if (ModelState.IsValid)
            {
                _context.Add(eBook);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(eBook));
        }
示例#23
0
        protected override void OnFileActivated(FileActivatedEventArgs args)
        {
            // Create a Frame to act as the navigation context and associate it with
            // a SuspensionManager key
            Frame rootFrame = null;

            // Do not repeat app initialization when already running, just ensure that
            // the window is active
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Frame currentFrame = (Frame)Window.Current.Content;
                if (currentFrame.CurrentSourcePageType == typeof(OpenFilePage))
                {
                    if (currentFrame.CanGoBack)
                    {
                        currentFrame.GoBack();
                    }
                    else
                    {
                        currentFrame = new Frame();
                    }
                }

                rootFrame = currentFrame;
            }

            // Ensure we have a root frame.
            if (rootFrame == null)
            {
                rootFrame = new Frame();
            }

            Task <EBook> task = EBook.CreateEBook(args);

            task.GetAwaiter().OnCompleted(() => {
                EBook book = task.Result;
                EReaderModel.CurrentBook = book;
                if (EReaderModel.Library.Contains(book))
                {
                }

                // Ensure we have content.
                if (!rootFrame.Navigate(typeof(OpenFilePage)))
                {
                    throw new Exception("Failed to create open file page!");
                }

                // Place the frame in the current Window and ensure that it is active
                Window.Current.Content = rootFrame;
                Window.Current.Activate();
            });

            base.OnFileActivated(args);
        }
示例#24
0
 Book Book(EBook eBook)
 {
     return(new Book(
                eBook.Id,
                eBook.Isbn,
                eBook.Title,
                eBook.PublishedAt,
                eBook.Price,
                eBook.Authors.Select(a => a.Name)
                ));
 }
示例#25
0
        public async Task <IActionResult> Create([Bind("ID,BookName,Genre,AuthorId,Author.Name")] EBook eBook)
        {
            if (ModelState.IsValid)
            {
                _context.Add(eBook);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            //ViewData["AuthorId"] = new SelectList(_context.Authors, "ID", "ID", eBook.AuthorId);
            ViewData["AuthorId"] = new SelectList(_context.Authors, "ID", "ID", eBook.Author.Name);
            return(View(eBook));
        }
示例#26
0
 public HttpResponseMessage Post(EBook NewBook)
 {
     string Validation = HttpContext.Current.Request.Headers["Validation"];
     if (Validation == ConfigurationManager.AppSettings["API_KEY"].ToString())
     {
         BooksRepository.AddBook(NewBook);
         return new HttpResponseMessage(HttpStatusCode.Created);
     }
     else
     {
         return new HttpResponseMessage(HttpStatusCode.Forbidden);
     }
 }
示例#27
0
        public IHttpActionResult PostEBook(EBook eBook)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.EBooks.Add(eBook);
            db.SaveChanges();

            LuceneService.RegisterNewLuceneDoc(eBook);

            return(CreatedAtRoute("DefaultApi", new { id = eBook.EBookId }, eBook));
        }
示例#28
0
        EBook EBook(StoreContext context, Book book)
        {
            var eBook = EBooks.FirstOrDefault(b => b.Id == book.Id);

            if (eBook != null)
            {
                return(eBook);
            }

            eBook = new EBook {
                RegisteredAt = Clock.GetTime()
            };
            context.Books.Add(eBook);
            return(eBook);
        }
示例#29
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            EBooks.Clear();

            var epubFolders = await ApplicationData.Current.LocalFolder.GetFoldersAsync();

            foreach (var epubFolder in epubFolders)
            {
                var eBook = new EBook(epubFolder.Path);
                eBook.Initialize();
                EBooks.Add(eBook);
            }
        }
示例#30
0
        private void GenerateBookRecord(ImportObject importerObj, ref EBook book)
        {
            book.Author    = _authorRepository.CreateIfAuthorIsNotExists(importerObj.AuthorName);
            book.Publisher = _publisherRepository.CreatePublisherIfNotExists(importerObj.PublisherName);
            book.Genre     = _genreRepository.CreateGenreIfNotExists(importerObj.GenreName);
            book.Serie     = _seriesRepository.CreateSeriesIfNotExists(importerObj.SerieName, book.Publisher);
            book.Rack      = _rackRepository.GetRackByRackNumber(int.Parse(importerObj.RackId));
            book.Shelf     = _shelfRepository.GetShelfById(int.Parse(importerObj.ShelfId));

            book.Name            = importerObj.BookName;
            book.PublishDate     = int.Parse(importerObj.Publishdate);
            book.No              = ConvertToRomanIntegers(importerObj.No);
            book.SkinType        = importerObj.Skintype.Equals("ciltli", StringComparison.InvariantCulture) ? SkinType.Ciltli : SkinType.Ciltsiz;
            book.CreatedDateTime = DateTime.Now;
            book.Users.Add(importerObj.User);
        }
示例#31
0
        public IHttpActionResult DeleteEBook(int id)
        {
            EBook eBook = db.EBooks.Find(id);

            if (eBook == null)
            {
                return(NotFound());
            }

            db.EBooks.Remove(eBook);
            db.SaveChanges();

            LuceneService.DeleteLuceneDoc(eBook);

            return(Ok(eBook));
        }
示例#32
0
        public void WhenGetBookListMethodCall_ReturnsSuccess()
        {
            EBook demo = new EBook()
            {
                Id     = 1,
                Name   = "demo",
                Author = new EAuthor {
                    Name = ""
                },
                Publisher = new EPublisher {
                    Name = ""
                },
                Serie = new ESeries {
                    Name = ""
                },
                PublishDate = It.IsAny <int>(),
                Genre       = new EGenre {
                    Genre = ""
                },
                No       = 1,
                SkinType = Data.Entities.Enums.SkinType.Ciltli,
                Shelf    = new EShelf {
                    Name = ""
                },
                Rack = new ERack {
                    RackNumber = 1
                },
                CreatedDateTime = DateTime.Now,
                SeriesId        = 0
            };

            _bookRepository.Setup(r => r.GetAll()).Returns(
                new List <EBook>()
            {
                demo
            });



            _bookServiceApplication = new BookServiceApplication(_bookRepository.Object, _userRepository.Object);


            BookOutputDto output = _bookServiceApplication.GetBookList();

            Assert.Collection <BookDto>(output.Books, t => Assert.Contains("demo", t.Name));
        }
示例#33
0
 public vEBook(EBook model)
 {
     DB db = new DB();
     this.ID = model.ID;
     this.Title = model.Title;
     this.Description = model.Description;
     this.EBookTypeID = model.EBookTypeID;
     this.TypeDictionary = model.TypeDictionary;
     this.FatherType = db.TypeDictionaries.Find(model.TypeDictionary.FatherID);
     this.Time = model.Time;
     this.UserID = model.UserID;
     this.Username = model.User.Username;
     this.FileID = model.FileID;
     this.File = model.File;
     this.Browses = model.Browses;
     this.Sumamry = Helpers.String.SubString(QqhrCitizen.Helpers.HtmlFilter.Instance.SanitizeHtml(model.Description), 50, "...");
 }