public async Task <ActionResult <BookTemplate> > PostBookTemplate(BookTemplate bookTemplate)
        {
            _context.BookTemplates.Add(bookTemplate);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBookTemplate", new { id = bookTemplate.Id }, bookTemplate));
        }
Exemple #2
0
        public async Task <ActionResult <string> > GenerateHtmlFileEpubFactory(int id)
        {
            Book           book         = _context.Books.First(a => a.Id == id);
            List <Chapter> chapters     = _context.Chapters.Where(a => a.Book == book).OrderBy(a => a.ChapterNumber).ToList();
            BookTemplate   bookTemplate = _context.BookTemplates.First(a => a.Book == book);
            var            stream       = System.IO.File.Create(@"output/file.epub");
            var            epubWriter   = await Helper.EPubWriter.CreateWriterAsync(stream, book.Name, "-", "-", CultureInfo.CurrentCulture, true);

            epubWriter.Publisher    = "WebToKindle";
            epubWriter.CreationDate = DateTime.Now;

            foreach (var chapter in chapters)
            {
                await epubWriter.AddChapterAsync(chapter.ChapterNumber.ToString() + ".xhtml", chapter.Title, chapter.Body);

                //var chapterStream = epubWriter.GetChapterStream(chapter.ChapterNumber.ToString() + ".xhtml", chapter.Title);
            }

            await epubWriter.WriteEndOfPackageAsync();

            await stream.FlushAsync();

            stream.Close();

            return("!");
        }
Exemple #3
0
        // GET: BookUnits
        public ActionResult Index(int?id)
        {
            if (TempData["Error"] != null)
            {
                ViewBag.Error = TempData["Error"];
            }
            if (TempData["Message"] != null)
            {
                ViewBag.Message = TempData["Message"];
            }

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            BookTemplate book = db.BookTemplates.FirstOrDefault(b => b.BookTemplateId == id);

            if (book == null)
            {
                return(HttpNotFound());
            }
            else
            {
                return(View("Index", book));
            }
        }
        public async Task <IActionResult> PutBookTemplate(int id, BookTemplate bookTemplate)
        {
            if (id != bookTemplate.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
        public ActionResult DeleteConfirmed(int id)
        {
            BookTemplate bookTemplate = db.BookTemplates.Find(id);

            db.BookTemplates.Remove(bookTemplate);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemple #6
0
 public BookBusiness(BookTemplate bookTemplate, Organization organization, ICollection <Reservation> reservations = null)
 {
     Debug.Assert(bookTemplate != null, "bookTemplate != null");
     Debug.Assert(organization != null, "organization != null");
     BookTemplate      = bookTemplate;
     this.organization = organization;
     this.reservations = reservations ?? new Collection <Reservation>();
 }
        public ActionResult AddReview(int LoanId, int Review, string ReviewDescription)
        {
            Loan loan = db.Loans.Find(LoanId);

            if (loan == null)
            {
                TempData["Error"]   = "1";
                TempData["Message"] = "<strong>Failed to submit review.</strong> Loan ID not found.";
                return(RedirectToAction("MyLoans"));
            }

            loan.Review            = (short)Review;
            loan.ReviewDescription = ReviewDescription;

            string userId = loan.UserId;

            db.PointHistories.Add(new PointHistory
            {
                DateCreated = DateTime.UtcNow.AddHours(8),
                Points      = 15,
                Type        = PointTypeConstant.ADD,
                UserId      = userId
            });

            db.SaveChanges();

            BookTemplate bt      = db.BookTemplates.Find(loan.Book.BookTemplateId);
            double?      average = bt.Stocks.Average(s => s.LoanHistory.Average(h => h.Review));

            if (average != null)
            {
                bt.ReviewAverage = (float)Math.Round(average.Value, 2);
                db.SaveChanges();
            }

            #region Send SMS
            try
            {
                var user =
                    Task.Run(() =>
                {
                    new SMSController().SendSMS(userId, "Hello, thank you for reviewing " + loan.Book.BookTemplate.Title + ". You have earned 15 points!");
                });
            }
            catch (Exception e)
            {
                Trace.TraceInformation("SMS Send Failed for " + loan.Book.BookTemplate.Title + ", Loan ID:" + loan.LoanId + ": " + e.Message);
            }
            #endregion

            TempData["Message"] = "<strong>Successfully submitted review.</strong> You have earned 15 points.";
            return(RedirectToAction("MyLoans"));
        }
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            BookTemplate bookTemplate = db.BookTemplates.Find(id);

            if (bookTemplate == null)
            {
                return(HttpNotFound());
            }
            return(View(bookTemplate));
        }
Exemple #9
0
        public void EditorLoadTemplate()
        {
            if (!Manager.IsAwake <Books> ())
            {
                Manager.WakeUp <Books> ("Frontiers_ObjectManagers");
            }

            for (int i = 0; i < Books.Get.Templates.Count; i++)
            {
                if (Books.Get.Templates [i].Name == State.TemplateName)
                {
                    Template = ObjectClone.Clone <BookTemplate> (Books.Get.Templates [i]);
                }
            }
        }
        public ActionResult RemoveFeatured(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            BookTemplate bookTemplate = db.BookTemplates.Find(id);

            if (bookTemplate == null)
            {
                return(HttpNotFound());
            }

            bookTemplate.IsFeatured = false;
            db.SaveChanges();
            TempData["Message"] = "Successfully updated info. <strong>" + bookTemplate.Title + "</strong> Featured attribute has been removed.";
            return(RedirectToAction("Index"));
        }
Exemple #11
0
        public async Task <ActionResult <string> > GenerateHtmlFileEpub4Net(int id)
        {
            System.IO.Directory.CreateDirectory("output/chapters");
            System.IO.Directory.CreateDirectory("output/final");
            System.IO.Directory.CreateDirectory("output/build");
            System.IO.Directory.CreateDirectory("output/books");
            Book           book         = _context.Books.First(a => a.Id == id);
            List <Chapter> chapters     = _context.Chapters.Where(a => a.Book == book).OrderBy(a => a.ChapterNumber).ToList();
            BookTemplate   bookTemplate = _context.BookTemplates.First(a => a.Book == book);

            List <Epub4Net.Chapter> epubChapters = new List <Epub4Net.Chapter>();

            foreach (Chapter chapter in chapters)
            {
                using (var writer = System.IO.File.CreateText("output/chapters/" + chapter.ChapterNumber + ".html"))
                {
                    await writer.WriteAsync(String.Format(bookTemplate.Chapter, chapter.Body));
                }
                epubChapters.Add(
                    new Epub4Net.Chapter(
                        "chapters/" + chapter.ChapterNumber + ".html",
                        chapter.ChapterNumber + ".html",
                        chapter.Title
                        )
                    );
            }

            var workingDir = System.IO.Directory.GetCurrentDirectory();

            System.IO.Directory.SetCurrentDirectory("output");

            Epub4Net.Epub epub = new Epub4Net.Epub(book.Name, " - ", epubChapters);
            epub.Language = "en";
            Epub4Net.EPubBuilder ePubBuilder = new Epub4Net.EPubBuilder(new Epub4Net.FileSystemManager("final"), "build");

            var result = ePubBuilder.Build(epub);

            System.IO.Directory.SetCurrentDirectory(workingDir);

            return(result);
        }
Exemple #12
0
        public override void PopulateOptionsList(List <WIListOption> options, List <string> message)
        {
            bool canRead = false;

            if (WorldItems.IsOwnedByPlayer(worlditem))
            {
                canRead = true;
            }
            else
            {
                BookTemplate template = null;
                if (Books.Get.BookTemplateByName(State.TemplateName, out template))
                {
                    if (template.CanBeReadWithoutAquiring)
                    {
                        canRead = true;
                    }
                }
            }
            if (canRead)
            {
                options.Add(new WIListOption("Read"));
            }
        }
Exemple #13
0
        public async Task <ActionResult <Book> > CreateBook()
        {
            var book = new Book()
            {
                ChapterCount = 1,
                LastUpdate   = DateTime.Now,
                Name         = "HPMOR",
                IndexURL     = "https://m.fanfiction.net/s/5782108/1/Harry-Potter-and-the-Methods-of-Rationality",
                ChapterURL   = "https://m.fanfiction.net/s/5782108/{0}/Harry-Potter-and-the-Methods-of-Rationality"
            };

            _context.Books.Add(book);
            _context.SaveChanges();

            var bookTemplate = new BookTemplate()
            {
                Book    = book,
                Header  = "{0}",
                Chapter = "<html><head><title>Chapter!</title></head><body>{0}</body></html>",
                Footer  = "{0}"
            };

            _context.BookTemplates.Add(bookTemplate);
            _context.SaveChanges();

            var CountType = new RegexType()
            {
                Name        = RegexTypes.ChapterCount.ToString(),
                Description = ""
            };

            _context.RegexTypes.Add(CountType);
            _context.SaveChanges();

            var TitleType = new RegexType()
            {
                Name        = RegexTypes.ChapterTitle.ToString(),
                Description = ""
            };

            _context.RegexTypes.Add(TitleType);
            _context.SaveChanges();

            var ContentType = new RegexType()
            {
                Name        = RegexTypes.ChapterContent.ToString(),
                Description = ""
            };

            _context.RegexTypes.Add(ContentType);
            _context.SaveChanges();

            var regex = new Database.Tables.Regex()
            {
                Book        = book,
                RegexString = "Ch 1 of <a href=\'/s/5782108/[0-9]+/\'>([0-9]+)</a",
                Type        = CountType,
            };

            _context.Regexes.Add(regex);

            var regex2 = new Database.Tables.Regex()
            {
                Book        = book,
                RegexString = "(Chapter .+?)<br></div>",
                Type        = TitleType,
            };

            _context.Regexes.Add(regex2);

            var regex3 = new Database.Tables.Regex()
            {
                Book        = book,
                RegexString = "<div style='.+?' class='storycontent nocopy' id='storycontent' >(.+?)<div align=center>",
                Type        = ContentType,
            };

            _context.Regexes.Add(regex3);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBook", new { id = book.Id }, book));
        }
Exemple #14
0
        public static bool WriteBook(string fname)
        {
            string filename = "Data/Books/" + fname + ".cs";
            string line     = "";
            string output   = "";
            bool   write    = true;

            FileStream    fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
            StreamWriter  sw = new StreamWriter(fs);
            StringBuilder sb = new StringBuilder("");

            int pages = m_Lines.Count / 8;
            int left  = m_Lines.Count % 8;
            int count = 0;

            try
            {
                for (int x = 0; x < pages; x++)
                {
                    line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                         m_Lines[count++], m_Lines[count++], m_Lines[count++], m_Lines[count++],
                                         m_Lines[count++], m_Lines[count++], m_Lines[count++]);
                    sb.Append(line);
                    if (x < pages - 1 || left > 0)
                    {
                        sb.Append(",");
                    }
                }
                switch (left)
                {
                case 7: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             m_Lines[count++], m_Lines[count++], m_Lines[count++], m_Lines[count++],
                                             m_Lines[count++], m_Lines[count++], "");
                    sb.Append(line);
                    break;

                case 6: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             m_Lines[count++], m_Lines[count++], m_Lines[count++], m_Lines[count++],
                                             m_Lines[count++], "", "");
                    sb.Append(line);
                    break;

                case 5: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             m_Lines[count++], m_Lines[count++], m_Lines[count++], m_Lines[count++],
                                             "", "", "");
                    sb.Append(line);
                    break;

                case 4: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             m_Lines[count++], m_Lines[count++], m_Lines[count++],
                                             "\"\"", "\"\"", "\"\"", "\"\"");
                    sb.Append(line);
                    break;

                case 3: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             m_Lines[count++], m_Lines[count++], "", "", "", "", "");
                    sb.Append(line);
                    break;

                case 2: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             m_Lines[count++], "", "", "", "", "", "");
                    sb.Append(line);
                    break;

                case 1: line = string.Format(NewBookPageTemplate, m_Lines[count++],
                                             "", "", "", "", "", "", "");
                    sb.Append(line);
                    break;

                default: break;
                }

                output = BookTemplate.Replace("{name}", fname);
                output = output.Replace("{title}", m_Title);
                output = output.Replace("{author}", m_Author);
                output = output.Replace("{pages}", sb.ToString());
            }
            catch (Exception e) { Console.Write(e.ToString()); write = false; }
            finally
            {
                try
                {
                    sw.Write(output);
                }
                catch (Exception e) { Console.Write(e.ToString()); write = false; }
            }
            sw.Close();
            fs.Close();
            return(write);
        }
        public async Task <ActionResult> Loan(ViewModels.LoanSubmitModel submitModel)
        {
            string userId = User.Identity.GetUserId();

            TempData["Error"]   = "1";
            TempData["Message"] = "<strong>Failed to process reservation.</strong> Please fill out all fields.";

            Setting maxLoanLimitSetting = db.Settings.FirstOrDefault(s => s.Code == "NUMBER_OF_ACTIVE_BOOK_LOANS");
            int     maxLoanLimit        = (maxLoanLimitSetting != null) ? Convert.ToInt16(maxLoanLimitSetting.Value) : 2;

            if (ModelState.IsValid)
            {
                BookTemplate bt = db.BookTemplates.Find(submitModel.BookTemplateId);

                if (bt != null)
                {
                    List <Loan> existingBookLoans = await db.Loans.Where(l => l.UserId == userId).ToListAsync();

                    if (existingBookLoans.Any(l => (l.Book.BookTemplateId == submitModel.BookTemplateId && l.ReturnDate == null && l.LostConfirmed == null)))
                    {
                        TempData["Message"] = "<strong>Failed to process reservation.</strong> You currently have an active loan or reservation with this book.";
                    }
                    else if (existingBookLoans.Count(l => l.ReturnDate == null) == maxLoanLimit)
                    {
                        TempData["Message"] = "<strong>Failed to process reservation.</strong> You currently have " + maxLoanLimit.ToString() + " active loans / books not returned yet.";
                    }
                    else
                    {
                        Book availableBook = db.Books.FirstOrDefault(b => b.BookTemplateId == submitModel.BookTemplateId &&
                                                                     b.BookStatus == BookStatusConstant.AVAILABLE);

                        if (availableBook != null)
                        {
                            Loan newLoan = new Loan
                            {
                                BookId      = availableBook.BookId,
                                DateCreated = DateTime.UtcNow.AddHours(8),
                                EndDate     = submitModel.StartDate.AddDays(submitModel.LoanPeriod),
                                StartDate   = submitModel.StartDate,
                                UserId      = userId
                            };

                            try
                            {
                                db.Loans.Add(newLoan);
                                availableBook.BookStatus = BookStatusConstant.LOANED;
                                await db.SaveChangesAsync();

                                TempData["Error"] = null;

                                if (availableBook.Branch != null)
                                {
                                    TempData["Message"] = "<strong>Successfully submitted reservation.</strong> Please pick up your book at " + availableBook.Branch.Name + ".";
                                }
                                else
                                {
                                    TempData["Message"] = "<strong>Successfully submitted reservation.</strong>";
                                }

                                #region Send SMS
                                try
                                {
                                    var user =
                                        Task.Run(() =>
                                    {
                                        new SMSController().SendSMS(userId, "Hello, we have receved your reservation for " + availableBook.BookTemplate.Title + ". Please pick up the book on " + newLoan.StartDate.ToString("MM-dd-yyyy") + ". Present your ID during claiming. Thank you!");
                                    });
                                }
                                catch (Exception e)
                                {
                                    Trace.TraceInformation("SMS Send Failed for " + availableBook.BookTemplate.Title + ", Loan ID:" + newLoan.LoanId + ": " + e.Message);
                                }
                                #endregion

                                return(RedirectToAction("Loan", new { id = submitModel.BookTemplateId }));
                            }
                            catch (Exception ex)
                            {
                                TempData["Message"] = "<strong>Failed to process reservation.</strong> Error: " + ex.Message + ".";
                            }
                        }
                        else
                        {
                            TempData["Message"] = "<strong>Failed to process reservation.</strong> There is no available stock for this book.";
                        }
                    }
                }
            }

            return(RedirectToAction("Loan", new { id = submitModel.BookTemplateId }));
        }
        public ActionResult Create([Bind(Include = "NewEditionBookTemplateId,BookTemplateId,Title,Type,Description,ImageLocation,LoanPeriod,ISBN,OLKey,PublishYear,InitialQuantity,Genres,Authors")] BookTemplate bookTemplate)
        {
            // store value, use new BookTemplateId and store it to NewEditionBookTemplateId/Old Edition Book
            int?newEditionBookTemplateId = bookTemplate.NewEditionBookTemplateId;

            bookTemplate.NewEditionBookTemplateId = null;

            int?            branchId = null;
            ApplicationUser currentUser;

            bookTemplate.IsFeatured     = false;
            bookTemplate.ActualQuantity = bookTemplate.InitialQuantity;
            bookTemplate.DateCreated    = DateTime.UtcNow.AddHours(8);

            string[] genres  = { "" };
            string[] authors = { "" };

            if (bookTemplate.Genres != null)
            {
                genres = bookTemplate.Genres.Split(',');
            }

            if (bookTemplate.Authors != null)
            {
                authors = bookTemplate.Authors.Split(',');
            }

            if (ModelState.IsValid)
            {
                db.BookTemplates.Add(bookTemplate);
                db.SaveChanges();

                List <Genre>     genresToAdd  = new List <Genre>();
                List <BookGenre> genresToSave = new List <BookGenre>();

                List <Author>     authorsToAdd  = new List <Author>();
                List <BookAuthor> authorsToSave = new List <BookAuthor>();

                #region Genres
                foreach (string genre in genres.Where(g => g != ""))
                {
                    Genre findGenre = db.Genres.FirstOrDefault(g => g.Name == genre);

                    if (findGenre != null)
                    {
                        genresToSave.Add(new BookGenre
                        {
                            BookTemplateId = bookTemplate.BookTemplateId,
                            GenreId        = findGenre.GenreId,
                            DateCreated    = DateTime.UtcNow.AddHours(8)
                        });
                    }
                    else
                    {
                        Genre newGenre = new Genre
                        {
                            DateCreated = DateTime.UtcNow.AddHours(8),
                            Name        = genre
                        };

                        genresToAdd.Add(newGenre);
                    }
                }

                db.Genres.AddRange(genresToAdd);
                db.SaveChanges();

                foreach (Genre newGenre in genresToAdd)
                {
                    genresToSave.Add(new BookGenre
                    {
                        BookTemplateId = bookTemplate.BookTemplateId,
                        GenreId        = newGenre.GenreId,
                        DateCreated    = DateTime.UtcNow.AddHours(8)
                    });
                }

                db.BookGenres.AddRange(genresToSave);
                db.SaveChanges();
                #endregion

                #region Authors
                foreach (string author in authors.Where(a => a != ""))
                {
                    Author findAuthor = db.Authors.FirstOrDefault(a => a.Name == author);

                    if (findAuthor != null)
                    {
                        authorsToSave.Add(new BookAuthor
                        {
                            BookTemplateId = bookTemplate.BookTemplateId,
                            AuthorId       = findAuthor.AuthorId,
                            DateCreated    = DateTime.UtcNow.AddHours(8)
                        });
                    }
                    else
                    {
                        Author newAuthor = new Author
                        {
                            DateCreated = DateTime.UtcNow.AddHours(8),
                            Name        = author
                        };

                        authorsToAdd.Add(newAuthor);
                    }
                }

                db.Authors.AddRange(authorsToAdd);
                db.SaveChanges();

                foreach (Author newAuthor in authorsToAdd)
                {
                    authorsToSave.Add(new BookAuthor
                    {
                        BookTemplateId = bookTemplate.BookTemplateId,
                        AuthorId       = newAuthor.AuthorId,
                        DateCreated    = DateTime.UtcNow.AddHours(8)
                    });
                }

                db.BookAuthors.AddRange(authorsToSave);
                db.SaveChanges();
                #endregion

                string userId = User.Identity.GetUserId();
                if (!string.IsNullOrEmpty(userId))
                {
                    currentUser = db.Users.FirstOrDefault(u => u.Id == userId);

                    if (currentUser != null)
                    {
                        branchId = currentUser.BranchId;
                    }
                }

                List <Book> bookUnits = new List <Book>();
                for (int count = 0; count < bookTemplate.InitialQuantity; count++)
                {
                    var bookToAdd = new Book {
                        BookStatus     = BookStatusConstant.AVAILABLE,
                        BookTemplateId = bookTemplate.BookTemplateId,
                        BranchId       = branchId
                    };

                    bookUnits.Add(bookToAdd);
                }

                db.Books.AddRange(bookUnits);
                db.SaveChanges();

                TempData["Message"] = "<strong>Book has been added successfully. The books are set to have the Branch ID assigned to you. You can manually update Branch ID per stock in Manage Stock.</strong>";

                if (newEditionBookTemplateId != null)
                {
                    var oldBook = db.BookTemplates.Find(newEditionBookTemplateId.Value);
                    if (oldBook != null)
                    {
                        oldBook.NewEditionBookTemplateId = bookTemplate.BookTemplateId;
                        db.SaveChanges();
                        TempData["Message"] = "<strong>New Edition Book has been added successfully. The books are set to have the Branch ID assigned to you. You can manually update Branch ID per stock in Manage Stock.</strong>";
                    }
                }

                return(RedirectToAction("Index"));
            }

            return(View(bookTemplate));
        }