Пример #1
0
        private bool TryParseBook(string scriptureString,
                                  string language,
                                  out BibleBook book,
                                  out string chapterVerse,
                                  out VerseParseResult result)
        {
            //TODO: Check for language validity so we don't end up with a vague null exception
            book         = null;
            chapterVerse = null;
            result       = VerseParseResult.InvalidVerse;

            // attempt to extract the book from the start of the string
            foreach (var bibleBook in _bibleBookProvider.BibleBooks)
            {
                foreach (var name in bibleBook.GetAllIdentifiersForLanguage(language))
                {
                    if (scriptureString.StartsWith(name.ToLowerInvariant() + " "))
                    {
                        book         = bibleBook;
                        chapterVerse = scriptureString.Substring(name.Length).Trim();
                        result       = VerseParseResult.Success;
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #2
0
        public DbVerse(BibleBook book, ChapterVerse from, ChapterVerse to,
            string title, string body, DateTime date, DbTranslation translation)
        {
            if (to == null)
                throw new ArgumentNullException("to", "to cannot be null.");
            if (from == null)
                throw new ArgumentNullException("from", "from cannot be null.");
            if (book == null)
                throw new ArgumentNullException("book", "book cannot be null.");
            if (from.CompareTo(to) > 0)
                throw new ArgumentException("The To reference should be after the From reference.");
            if (title == null)
                throw new ArgumentNullException("title", "title cannot be null.");
            if (body == null)
                throw new ArgumentNullException("body", "body cannot be null.");

            Id = -1;
            Book = book;
            From = from;
            To = to;
            Title = title;
            Body = body;
            Date = date;

            if (translation == null)
                Translation = DbTranslation.Default;
            else
                Translation = translation;
        }
Пример #3
0
        private List <BookChapter> GetBookChaptersNewStyle(XNamespace ns, BibleBook book, XElement body)
        {
            var result = new List <BookChapter>();

            if (_epubStyle == EpubStyle.New)
            {
                var chapters = body.Descendants(ns + "a").Where(n => n.Attribute("href") != null);

                foreach (var chapter in chapters)
                {
                    var href = chapter.Attribute("href")?.Value;

                    if (NumberParser.TryParseNumber(chapter.Value, out var chapterNumber))
                    {
                        var bc = new BookChapter
                        {
                            FullPath = GetFullPathInArchive(href),
                            Book     = book,
                            Chapter  = chapterNumber
                        };

                        bc.VerseRange = GetVerseNumbers(bc.FullPath);

                        Log.Logger.Debug($"Chapter = {bc.Chapter}, {bc.FullPath}");
                        result.Add(bc);
                    }
                }
            }

            return(result);
        }
Пример #4
0
        private void BookSelectedIndexChanged(object sender, EventArgs e)
        {
            Picker    pkr  = (Picker)sender;
            BibleBook book = (BibleBook)pkr.SelectedItem;

            MessagingCenter.Send(this, "SelectedBookChanged", book);
        }
        public async Task <ActionResult <MinQuestion> > GetFitBQuestion(string BibleId, string BookName, int Chapter, int Verse)
        {
            BibleId = await QuizQuestion.GetValidBibleIdAsync(_context, BibleId);

            BibleBook Book = await BibleBook.GetBookAndChapterByNameAsync(_context, BibleId, BookName, Chapter);

            if (Book == null)
            {
                return(NotFound());
            }
            BibleVerse verse = new BibleVerse();

            try
            {
                verse = await _context.BibleVerses.Where(v => v.BibleId == BibleId &&
                                                         v.BookNumber == Book.BookNumber &&
                                                         v.Chapter == Chapter &&
                                                         v.Verse == Verse)
                        .SingleAsync();
            }
            catch
            {
                return(NotFound());
            }

            QuizQuestion Question = new QuizQuestion();

            Question = await Question.BuildQuestionForVerseAsync(_context, verse, 8, BibleId);

            Question.PopulatePBEQuestionInfo(Book);
            MinQuestion minQuestion = new MinQuestion(Question);

            return(minQuestion);
        }
        public async Task <ActionResult <IEnumerable <MinChapter> > > GetBibleChapters(string BibleId, string BookName)
        {
            BibleId = await QuizQuestion.GetValidBibleIdAsync(_context, BibleId);

            BibleBook Book = await BibleBook.GetBookByNameAsync(_context, BibleId, BookName);

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

            try
            {
                List <BibleChapter> ChapterList = Book.BibleChapters.ToList();
                List <MinChapter>   MinChapters = new List <MinChapter>();
                foreach (BibleChapter Chapter in ChapterList)
                {
                    MinChapter MinChapter = new MinChapter(Chapter);
                    MinChapters.Add(MinChapter);
                }
                return(MinChapters);
            }
            catch { }
            return(null);
        }
Пример #7
0
        public bool ListChapters(BibleSearchMatch sm)
        {
            this.CChapters.Items.Clear();
            if (sm == null)
            {
                return(false);
            }
            BibleBook bk = null;

            if (!BibleStore.BibleStore.EngBible.Books.TryGetValue(sm.BookId.ToLower(), out bk))
            {
                return(false);
            }
            for (var cn = 0; cn < bk.Chapters.Count; cn++)
            {
                var res = BibleStore.BibleStore.FindEn(string.Format($"{sm.BookName} {(cn+1).ToString()}"));
                if (res.Matches.Length < 1)
                {
                    continue;
                }
                var match = res.Matches[0];
                this.CChapters.Items.Add(CreateItem(match, match.Verses.First()));
            }
            this.CChapters.SelectedItem = null;
            return(false);
        }
        public async Task <IActionResult> OnGetAsync(string BibleId, int Id)
        {
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email); // Static method not requiring an instance

            if (!PBEUser.IsQuizModerator())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to edit a PBE BookList" }));
            }

            BookList = await _context.QuizBookLists.FindAsync(Id);

            if (BookList == null)
            {
                return(RedirectToPage("/error", new { errorMessage = "That's Odd! We weren't able to find this Book List" }));
            }

            this.BibleId = await Bible.GetValidPBEBibleIdAsync(_context, BibleId);

            //Initialize Books
            await _context.Entry(BookList).Collection(L => L.QuizBookListBookMaps).LoadAsync();

            BookList.PadBookListBookMapsForEdit();
            Books = BookList.QuizBookListBookMaps.ToList();
            Name  = BookList.BookListName;
            ViewData["BookSelectList"] = await BibleBook.GetBookSelectListAsync(_context, BibleId);

            return(Page());
        }
Пример #9
0
        public async Task <ActionResult <IEnumerable <MinQuestion> > > GetQuizQuestions(string BibleId, string BookName, int Chapter)
        {
            BibleId = await QuizQuestion.GetValidBibleIdAsync(_context, BibleId);

            BibleBook Book = await BibleBook.GetBookAndChapterByNameAsync(_context, BibleId, BookName, Chapter);

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

            List <MinQuestion>  minQuestions = new List <MinQuestion>();
            List <QuizQuestion> Questions    = await _context.QuizQuestions
                                               .Include(Q => Q.QuizAnswers)
                                               .Where(Q => (Q.BibleId == BibleId || Q.BibleId == null) &&
                                                      Q.BookNumber == Book.BookNumber &&
                                                      Q.Chapter == Chapter &&
                                                      Q.IsDeleted == false &&
                                                      Q.IsAnswered == true).ToListAsync();

            foreach (QuizQuestion Question in Questions)
            {
                Question.PopulatePBEQuestionInfo(Book);
                MinQuestion minQuestion = new MinQuestion(Question);
                minQuestions.Add(minQuestion);
            }
            return(minQuestions);
        }
        public async Task <IViewComponentResult> InvokeAsync(string BibleId)
        {
            BibleId = await QuizQuestion.GetValidBibleIdAsync(_context, BibleId);

            List <BibleBook> ReturnBooks = await BibleBook.GetPBEBooksWithQuestionsAsync(_context, BibleId);

            return(View(ReturnBooks));
        }
Пример #11
0
        public async Task <IActionResult> OnGetAsync(int QuestionId, string Caller)
        {
            ReturnPath = Caller;
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email);

            if (!PBEUser.IsValidPBEQuestionBuilder())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to edit a PBE question" }));
            }

            Question = await _context.QuizQuestions.FindAsync(QuestionId);

            if (Question == null)
            {
                return(RedirectToPage("/error", new { errorMessage = "That's Odd! We weren't able to find this Question" }));
            }

            // Setup our PBEBook Object
            Question.BibleId = await QuizQuestion.GetValidBibleIdAsync(_context, Question.BibleId);

            BibleBook PBEBook = await BibleBook.GetPBEBookAndChapterAsync(_context, Question.BibleId, Question.BookNumber, Question.Chapter);

            if (PBEBook == null)
            {
                return(RedirectToPage("/error", new { errorMessage = "That's Odd! We weren't able to find the PBE Book." }));
            }

            Question.PopulatePBEQuestionInfo(PBEBook);
            Question.Verses = await Question.GetBibleVersesAsync(_context, false);

            // We need an answer text, and while techincally we support multiple Answers
            // we are only going to allow operating on the first one in this basic edit experience.
            await _context.Entry(Question).Collection(Q => Q.QuizAnswers).LoadAsync();

            if (Question.QuizAnswers.Count > 0)
            {
                AnswerText = Question.QuizAnswers.OrderBy(A => A.Id).First().Answer;
            }
            else
            {
                AnswerText = "";
            }

            IsCommentary = (Question.Chapter == Bible.CommentaryChapter);
            if (IsCommentary == false)
            {
                ChapterQuestionCount = PBEBook.BibleChapters.Where(c => c.ChapterNumber == Question.Chapter).First().QuestionCount;
            }
            CommentaryQuestionCount = PBEBook.CommentaryQuestionCount;

            // and now we need a Verse Select List
            ViewData["VerseSelectList"]  = new SelectList(Question.Verses, "Verse", "Verse");
            ViewData["PointsSelectList"] = Question.GetPointsSelectList();
            return(Page());
        }
 /// <summary>
 /// Sets the `LoadedChapter` object with the given values
 /// </summary>
 /// <param name="book">BibleBook to load</param>
 /// <param name="chapter">Selected chapter</param>
 public void LoadChapter(BibleBook book, byte chapter)
 {
     if (!LoadedBible.Value.Books.ContainsKey(book))
     {
         throw new ArgumentException("This book does not exist in this Bible", nameof(book));
     }
     _currentBookIndex = (byte)Array.IndexOf(CurrentAllBooks, book);
     CurrentChapter    = chapter;
     LoadedChapter     = LoadedBible.Value.Books[CurrentBook].Chapter[CurrentChapter];
 }
Пример #13
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (await QuizBookList.ListNameAlreadyExistsStaticAsync(_context, Name))
            {
                ModelState.AddModelError("Name", "Sorry, this Name is already in use.");
            }
            if (!ModelState.IsValid)
            {
                ViewData["BookSelectList"] = await BibleBook.GetBookSelectListAsync(_context, BibleId);

                return(Page());
            }

            // confirm our user is a valid PBE User.
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email);

            if (!PBEUser.IsQuizModerator())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to add a PBE BookList" }));
            }

            // Now let's create an empty BookList
            var emptyBookList = new QuizBookList
            {
                Created  = DateTime.Now,
                Modified = DateTime.Now
            };

            emptyBookList.BookListName = Name;
            emptyBookList.IsDeleted    = false;
            _context.QuizBookLists.Add(emptyBookList);

            // now we need to add the Books
            foreach (int BookNum in Books)
            {
                if (BookNum > 0)
                {
                    QuizBookListBookMap BookMap = new QuizBookListBookMap();
                    BookMap.BookList   = emptyBookList;
                    BookMap.BookNumber = BookNum;
                    BookMap.IsDeleted  = false;
                    BookMap.Created    = DateTime.Now;
                    BookMap.Modified   = DateTime.Now;
                    _context.QuizBookListBookMaps.Add(BookMap);
                    await _context.SaveChangesAsync();
                }
            }
            await _context.SaveChangesAsync();

            return(RedirectToPage("BookLists", new { BibleId = this.BibleId, Message = String.Format("Book List {0} successfully created...", emptyBookList.BookListName) }));
        }
Пример #14
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (Quiz.BookNumber == 0 && Quiz.PredefinedQuiz == 0)
            {
                ModelState.AddModelError("Quiz.BookNumber", "You must select either a Book/BookList or a Template.");
                ModelState.AddModelError("Quiz.PredefinedQuiz", "You must select either a Book/BookList or a Template.");
            }
            if (!ModelState.IsValid)
            {
                //Initialize Select Lists
                ViewData["BookSelectList"] = await BibleBook.GetBookAndBookListSelectListAsync(_context, BibleId);

                ViewData["TemplateSelectList"] = await PredefinedQuiz.GetTemplateSelectListAsync(_context, PBEUser);

                return(Page());
            }

            // confirm our user is a valid PBE User.
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email);

            if (!PBEUser.IsValidPBEQuizHost())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to add a PBE Quiz" }));
            }

            // Now let's create an empty Quiz
            var emptyQuiz = new QuizGroupStat
            {
                Created   = DateTime.Now,
                Modified  = DateTime.Now,
                QuizUser  = PBEUser,
                IsDeleted = false
            };

            if (await TryUpdateModelAsync <QuizGroupStat>(
                    emptyQuiz,
                    "Quiz", // Prefix for form value.
                    q => q.GroupName, q => q.BookNumber, q => q.PredefinedQuiz))
            {
                if (emptyQuiz.PredefinedQuiz > 0)
                {
                    // Template trumps Book/BookList so we set BookNumber 0
                    emptyQuiz.BookNumber = 0;
                }
                _context.QuizGroupStats.Add(emptyQuiz);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Quizzes", new { BibleId = this.BibleId, Message = String.Format("Quiz {0} successfully created...", emptyQuiz.GroupName) }));
        }
Пример #15
0
        public static DynamicTableEntity ToStorage(this BibleBook book)
        {
            var entry = new DynamicTableEntity
            {
                PartitionKey = book.Culture,
                RowKey       = book.Order.ToString(),
            };

            entry.Properties["Name"]      = EntityProperty.CreateEntityPropertyFromObject(book.Name);
            entry.Properties["Shorthand"] = EntityProperty.CreateEntityPropertyFromObject(book.Shorthand);

            return(entry);
        }
Пример #16
0
        private List <BookChapter> GetBookChapters(XNamespace ns, BibleBook book, XElement body)
        {
            switch (_epubStyle)
            {
            case EpubStyle.New:
                return(GetBookChaptersNewStyle(ns, book, body));

            case EpubStyle.Old:
                return(GetBookChaptersOldStyle(ns, book, body));
            }

            return(null);
        }
Пример #17
0
        /// <summary>
        /// Reads text file containing all CRs
        /// </summary>
        /// <param name="treshold">The minimum number of votes to be considered added in list</param>
        public void ReadFromFile(int treshold)
        {
            using (StreamReader stream = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Aionian.cross_references.cross_references.txt")))
            {
                AllCrossReferences = new SortedSet <CrossReference>();
                _ = stream.ReadLine();                //Ignore the first header line
                List <BibleRegion> AllVerses  = new List <BibleRegion>();
                BibleReference     prevSource = new BibleReference()
                {
                    Book = BibleBook.NULL, Chapter = 0, Verse = 0
                };
                while (!stream.EndOfStream)
                {
                    string[] row = stream.ReadLine().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (int.Parse(row[2]) >= treshold)
                    {
                        BibleReference currentSource = ParseReference(row[0]);
                        if (currentSource != prevSource)
                        {
                            if (AllVerses.Count > 0)
                            {
                                _ = AllCrossReferences.Add(new CrossReference(prevSource, AllVerses.ToArray()));
                                AllVerses.Clear();
                            }
                            prevSource = currentSource;
                        }
                        if (row[1].Contains("-"))
                        {
                            string[] region = row[1].Split('-');
                            AllVerses.Add(new BibleRegion(ParseReference(region[0]), ParseReference(region[1])));
                        }
                        else
                        {
                            BibleReference referece = ParseReference(row[1]);
                            AllVerses.Add(new BibleRegion(referece, referece));
                        }
                    }
                }
                _ = AllCrossReferences.Add(new CrossReference(prevSource, AllVerses.ToArray()));
            }
            BibleReference ParseReference(string s)
            {
                string[]  parts = s.Split('.');
                BibleBook bk    = (BibleBook)(byte)Array.FindIndex(BookNames, x => x == parts[0]);

                return(new BibleReference()
                {
                    Book = bk, Chapter = byte.Parse(parts[1]), Verse = byte.Parse(parts[2])
                });
            }
        }
        public async Task <IActionResult> OnGetAsync(string BibleId, int BookNumber, int Chapter, int?Verse)
        {
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email); // Static method not requiring an instance

            this.BookNumber = BookNumber;
            this.Chapter    = Chapter;
            this.Verse      = Verse ?? 0; // set to 0 if Verse is null
            this.BibleId    = await QuizQuestion.GetValidBibleIdAsync(_context, BibleId);

            BibleBook PBEBook = await BibleBook.GetPBEBookAndChapterAsync(_context, this.BibleId, this.BookNumber, this.Chapter);

            if (PBEBook == null)
            {
                return(RedirectToPage("/error", new { errorMessage = "That's Odd! We weren't able to find the PBE Book." }));
            }

            // Handle the possibility that we want only one verse.
            var questions = from q in _context.QuizQuestions select q;

            if (!Verse.HasValue)
            {
                questions = questions.Where(Q => (Q.BibleId == this.BibleId || Q.BibleId == null) && Q.BookNumber == BookNumber && Q.Chapter == Chapter && Q.IsDeleted == false);
            }
            else
            {
                questions = questions.Where(Q => (Q.BibleId == this.BibleId || Q.BibleId == null) && Q.BookNumber == BookNumber && Q.Chapter == Chapter && Q.EndVerse == Verse && Q.IsDeleted == false);
            }

            Questions = await questions.Include(Q => Q.QuizAnswers)
                        .OrderBy(Q => Q.EndVerse)
                        .ToListAsync();

            foreach (QuizQuestion Question in Questions)
            {
                Question.PopulatePBEQuestionInfo(PBEBook);
                Question.CheckUserCanEdit(PBEUser);
            }
            IsCommentary = (this.Chapter == Bible.CommentaryChapter);
            if (IsCommentary)
            {
                this.BookName = PBEBook.CommentaryTitle;
            }
            else
            {
                this.BookName = PBEBook.Name;
            }

            return(Page());
        }
Пример #19
0
        public async Task <IActionResult> OnGetAsync(string BibleId)
        {
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email);

            if (!PBEUser.IsValidPBEQuestionBuilder())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to add a PBE Quiz Template" }));
            }

            this.BibleId = await Bible.GetValidPBEBibleIdAsync(_context, BibleId);

            ViewData["BookSelectList"] = await BibleBook.GetBookAndBookListSelectListAsync(_context, BibleId);

            ViewData["CountSelectList"] = PredefinedQuiz.GetCountSelectList();
            return(Page());
        }
Пример #20
0
        public async Task <ActionResult <MinQuestion> > GetQuizQuestion(int id)
        {
            var quizQuestion = await _context.QuizQuestions.FindAsync(id);

            if (quizQuestion == null)
            {
                return(NotFound());
            }
            // Explicit load our answers.
            await _context.Entry(quizQuestion).Collection(q => q.QuizAnswers).LoadAsync();

            BibleBook PBEBook = await BibleBook.GetPBEBookAndChapterAsync(_context, quizQuestion.BibleId, quizQuestion.BookNumber, quizQuestion.Chapter);

            quizQuestion.PopulatePBEQuestionInfo(PBEBook);
            MinQuestion minQuestion = new MinQuestion(quizQuestion);


            return(minQuestion);
        }
Пример #21
0
        public async Task <IActionResult> OnGetAsync(string BibleId)
        {
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email); // Static method not requiring an instance

            if (!PBEUser.IsQuizModerator())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to add a PBE BookList" }));
            }

            this.BibleId = await Bible.GetValidPBEBibleIdAsync(_context, BibleId);

            //Initialize Books
            Books = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            ViewData["BookSelectList"] = await BibleBook.GetBookSelectListAsync(_context, BibleId);

            return(Page());
        }
Пример #22
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                ViewData["BookSelectList"] = await BibleBook.GetBookAndBookListSelectListAsync(_context, BibleId);

                return(Page());
            }

            // confirm our user is a valid PBE User.
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email);

            if (!PBEUser.IsValidPBEQuestionBuilder())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to add a PBE Quiz Template" }));
            }

            // Now let's create an empty template
            var emptyTemplate = new PredefinedQuiz
            {
                Created  = DateTime.Now,
                Modified = DateTime.Now,
                QuizUser = PBEUser
            };

            if (await TryUpdateModelAsync <PredefinedQuiz>(
                    emptyTemplate,
                    "Template", // Prefix for form value.
                    t => t.QuizName, t => t.BookNumber, t => t.NumQuestions))
            {
                emptyTemplate.QuizName  = Name; // Name is handled seperately for remote validation to work.
                emptyTemplate.IsDeleted = false;
                _context.PredefinedQuizzes.Add(emptyTemplate);
                await _context.SaveChangesAsync();

                return(RedirectToPage("./ConfigureTemplate", new { Id = emptyTemplate.Id, BibleId = this.BibleId }));
            }

            return(RedirectToPage("./Templates", new { Message = String.Format("Quiz Template {0} successfully created...", emptyTemplate.QuizName) }));
        }
Пример #23
0
        public async Task <IActionResult> OnGetAsync(string BibleId)
        {
            IdentityUser user = await _userManager.GetUserAsync(User);

            PBEUser = await QuizUser.GetOrAddPBEUserAsync(_context, user.Email); // Static method not requiring an instance

            if (!PBEUser.IsValidPBEQuizHost())
            {
                return(RedirectToPage("/error", new { errorMessage = "Sorry! You do not have sufficient rights to add a PBE Quiz" }));
            }

            this.BibleId = await Bible.GetValidPBEBibleIdAsync(_context, BibleId);

            //Initialize Select Lists
            ViewData["BookSelectList"] = await BibleBook.GetBookAndBookListSelectListAsync(_context, BibleId);

            ViewData["TemplateSelectList"] = await PredefinedQuiz.GetTemplateSelectListAsync(_context, PBEUser);

            return(Page());
        }
Пример #24
0
        private bool TryParseChapter(string chapterVerse,
                                     BibleBook book,
                                     out BibleChapter chapter,
                                     out string verseString,
                                     out VerseParseResult result)
        {
            chapter     = null;
            verseString = null;
            result      = VerseParseResult.InvalidSyntax;

            if (book.IsSingleChapter)
            {
                chapter     = book.Chapters.FirstOrDefault();
                verseString = chapterVerse;
                result      = VerseParseResult.Success;
            }
            else
            {
                var chapterStr = Regex.Match(chapterVerse, @"\d+:").Value;

                if (!string.IsNullOrEmpty(chapterStr))
                {
                    var chapterNum = int.Parse(chapterStr.Replace(":", "").Trim());

                    if (chapterNum > 0 && chapterNum <= book.Chapters.Count)
                    {
                        chapter     = book.SortedChapters[chapterNum - 1];
                        verseString = chapterVerse.Substring(chapterVerse.IndexOf(":") + 1).Trim();
                        result      = VerseParseResult.Success;
                    }
                    else
                    {
                        result = VerseParseResult.InvalidVerse;
                    }
                }
            }

            return(result == VerseParseResult.Success);
        }
Пример #25
0
        public BibleBook RetrieveBibleBookDetails(int bookId, string bookName)
        {
            var book = new BibleBook
            {
                BibleBookId = bookId,
                Name        = bookName,
            };

            var chapterCount = _verseCountByChapter[bookId].Length - 1;

            book.TotalChapters = chapterCount;

            for (int i = 1; i <= chapterCount; i++)
            {
                var chapter = RetrieveChapterDetails(bookId, i);

                chapter.Book = book;

                book.Chapters.Add(chapter);
            }

            return(book);
        }
Пример #26
0
        public Bible LoadContent(string fileName, Bible b)
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(fileName);
            var xmlRoot = xmlDoc.DocumentElement;

            if (xmlRoot.Name == "XMLBIBLE")
            {
                b.Books = new List <BibleBook>();
                foreach (XmlNode bookNode in xmlRoot.ChildNodes)
                {
                    if (bookNode.Name.ToLower() == "biblebook")
                    {
                        var bo = new BibleBook
                        {
                            Bible  = b,
                            Number = int.Parse(bookNode.Attributes["bnumber"].InnerText)
                        };
                        bo.Name = bookNode.Attributes["bname"] != null
                            ? bookNode.Attributes["bname"].InnerText
                            : Bible.BookMap[bo.Number - 1];
                        bo.ShortName = bookNode.Attributes["bsname"] != null
                            ? bookNode.Attributes["bsname"].InnerText
                            : bo.Name;
                        bo.Chapters = new List <BibleChapter>();
                        foreach (XmlNode chapNode in bookNode.ChildNodes)
                        {
                            if (chapNode.Name.ToLower() == "chapter")
                            {
                                var ch = new BibleChapter
                                {
                                    Book   = bo,
                                    Number = int.Parse(chapNode.Attributes["cnumber"].InnerText),
                                    Verses = new List <BibleVerse>()
                                };
                                foreach (XmlNode verseNode in chapNode.ChildNodes)
                                {
                                    if (verseNode.Name.ToLower() == "vers")
                                    {
                                        string text = string.Empty;
                                        foreach (XmlNode textNode in verseNode.ChildNodes)
                                        {
                                            if (textNode.NodeType == XmlNodeType.Text)
                                            {
                                                text += textNode.InnerText;
                                            }
                                        }
                                        var v = new BibleVerse
                                        {
                                            Chapter = ch,
                                            Number  = int.Parse(verseNode.Attributes["vnumber"].InnerText),
                                            Text    = text
                                        };
                                        ch.Verses.Add(v);
                                    }
                                }
                                bo.Chapters.Add(ch);
                            }
                        }
                        b.Books.Add(bo);
                    }
                }
            }
            return(b);
        }
Пример #27
0
        /// <summary>
        /// Creates a bible from the inputted stream of a Aionian bible noia Database
        /// </summary>
        /// <param name="stream">The Stream to the *.noia Database</param>
        /// <returns>The initiated Bible from the stream is returned</returns>
        public static Bible ExtractBible(StreamReader stream)
        {
            string    line;
            byte      CurrentChapter = 255;
            BibleBook CurrentBook    = BibleBook.NULL;
            Dictionary <byte, Dictionary <byte, string> > CurrentBookData = null;
            Dictionary <byte, string> CurrentChapterData = null;

            line = stream.ReadLine();            //Read the first line containing file name
            bool aionianEdition = line.EndsWith("Aionian-Edition.noia");

            string[] tl       = line.Replace("---", "|").Split('|');
            string   language = tl[1];
            string   title    = tl[2];
            Dictionary <BibleBook, string> RegionalName = new Dictionary <BibleBook, string>();

            while ((_ = stream.ReadLine())[0] == '#')
            {
                ;                                                  //Keep reading till you reach the header, which is also skipped
            }
            Dictionary <BibleBook, Book> books = new Dictionary <BibleBook, Book>();

            while ((line = stream.ReadLine()) != null)
            {
                if (line[0] == '0')                                                              //The valid lines of the database begin with 0, not with # or INDEX (header row)
                {
                    string[]  rows    = line.Split('\t');                                        //Returns the line after splitting into multiple rows
                    BibleBook book    = (BibleBook)(byte)Array.IndexOf(ShortBookNames, rows[1]); //Get the BibleBook from BookName
                    byte      chapter = byte.Parse(rows[2]);                                     //Get the Chapter number
                    byte      verseno = byte.Parse(rows[3]);                                     //Get the Verse number
                    string    verse   = rows[4];                                                 //Get the verse content
                    if (book != CurrentBook)
                    {
                        if (CurrentBookData != null)
                        {
                            CurrentBookData[CurrentChapter] = CurrentChapterData;
                            books[CurrentBook] = new Book((byte)CurrentBook, CurrentBookData, RegionalName[CurrentBook]);
                        }
                        CurrentBookData    = new Dictionary <byte, Dictionary <byte, string> >();
                        CurrentBook        = book;
                        CurrentChapterData = new Dictionary <byte, string>();
                        CurrentChapter     = chapter;
                    }
                    else if (chapter != CurrentChapter)
                    {
                        CurrentBookData[CurrentChapter] = CurrentChapterData;
                        CurrentChapterData = new Dictionary <byte, string>();
                        CurrentChapter     = chapter;
                    }
                    CurrentChapterData[verseno] = verse;
                }
                else if (line.Contains("# BOOK"))
                {
                    string[] parts = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    RegionalName.Add((BibleBook)byte.Parse(parts[1]), parts[4]);
                }
            }
            CurrentBookData[CurrentChapter] = CurrentChapterData;
            books[CurrentBook] = new Book((byte)CurrentBook, CurrentBookData, RegionalName[CurrentBook]);
            return(new Bible(title, language, aionianEdition, books));
        }
Пример #28
0
 /// <summary>
 /// Indexer to return the verse(as a string) given any book,chapter number and verse index
 /// </summary>
 public string this[BibleBook b, byte c, byte v] => Books[b].Chapter[c][v];
Пример #29
0
        private List <BookChapter> GetBookChaptersOldStyle(XNamespace ns, BibleBook book, XElement body)
        {
            var result = new List <BookChapter>();

            const string linkToken = "link";

            var chapters = body.Descendants(ns + "a").Where(n =>
            {
                if (n.Parent != null)
                {
                    var idAttr = n.Attribute("id");
                    if (idAttr != null)
                    {
                        var parentClassAttr = n.Parent.Attribute("class");
                        if (parentClassAttr != null)
                        {
                            return(idAttr.Value.StartsWith(linkToken) &&
                                   n.Parent.Name.Equals(ns + "p") &&
                                   parentClassAttr.Value.Equals("se"));
                        }
                    }
                }

                return(false);
            });

            foreach (var chapter in chapters)
            {
                var chapterNumStr = chapter.Attribute("id")?.Value.Substring(linkToken.Length);
                if (!string.IsNullOrEmpty(chapterNumStr))
                {
                    if (int.TryParse(chapterNumStr, out var chapterNum))
                    {
                        ++chapterNum;
                        var nextNode = chapter.NextNode;
                        if (nextNode != null && nextNode.NodeType == XmlNodeType.Element)
                        {
                            var nodeElem   = (XElement)nextNode;
                            var xAttribute = nodeElem.Attribute("href");
                            if (xAttribute != null)
                            {
                                var pos = xAttribute.Value.IndexOf("#", StringComparison.Ordinal);
                                if (pos > 0)
                                {
                                    var href = xAttribute.Value.Substring(0, pos);

                                    var bc = new BookChapter
                                    {
                                        FullPath = GetFullPathInArchive(href),
                                        Book     = book,
                                        Chapter  = chapterNum
                                    };

                                    bc.VerseRange = GetVerseNumbers(bc.FullPath);

                                    Log.Logger.Debug($"Chapter = {bc.Chapter}, {bc.FullPath}");
                                    result.Add(bc);
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
Пример #30
0
        public IReadOnlyList <BibleBook> GenerateBibleBooksList()
        {
            var cachedResult = BibleBooksCache.Get(_epubPath, _epubCreationStampUtc);

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

            Log.Logger.Information("Initialising books");

            var nav = _navigationDocument.Value;

            var result = new List <BibleBook>();

            var attr = nav.Root?.Attribute("xmlns");

            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var body = nav.Root.Descendants(ns + "body").SingleOrDefault();
                if (body != null)
                {
                    var books   = body.Descendants(ns + "a").Where(n => n.Attribute("href") != null);
                    int bookNum = 1;

                    foreach (var book in books)
                    {
                        string href = book.Attribute("href")?.Value;
                        if (href != null && href.EndsWith(".xhtml"))
                        {
                            var fullPath = GetFullPathInArchive(href);

                            var bb = new BibleBook
                            {
                                FullPath            = fullPath,
                                BookAbbreviatedName = book.Value.Trim(),
                                BookFullName        = GetFullNameOfBook(fullPath),
                                BookNumber          = bookNum++
                            };

                            if (bb.HasSingleChapter)
                            {
                                var scp = GetSingleChapterPath(bb.FullPath);
                                if (!string.IsNullOrEmpty(scp))
                                {
                                    // older formats...
                                    bb.FullPath = GetFullPathInArchive(GetSingleChapterPath(bb.FullPath));
                                }
                            }

                            Log.Logger.Debug($"Book = {bb.BookNumber}, {bb.BookAbbreviatedName}, {bb.FullPath}");

                            result.Add(bb);
                        }
                    }

                    if (result.Count == BibleBooksMetaData.NumBibleBooksGreek)
                    {
                        // renumber...
                        foreach (var book in result)
                        {
                            book.BookNumber = book.BookNumber + BibleBooksMetaData.NumBibleBooksHebrew;
                        }
                    }
                }
            }

            BibleBooksCache.Add(_epubPath, _epubCreationStampUtc, result);

            return(result);
        }
Пример #31
0
 public void Reset()
 {
     BeginChapter = 1;
     EndChapter = 1;
     BeginVerse = 1;
     EndVerse = 1;
     _book = null;
 }
Пример #32
0
        private void ChapterDisplay()
        {
            Console.WriteLine("Loading Available Bibles. Please Wait...");
            DisplayAvailableBibles();
            Console.WriteLine("\nEnter the bible to load: ");
            if (int.TryParse(Console.ReadLine(), out int bible) && bible >= 1 && bible <= AvailableBibles.Count)
            {
                ChapterwiseBible chapterwiseBible = new ChapterwiseBible(LoadFileAsJson <Bible>(AssetFileName(AvailableBibles[--bible])));
                List <string>    allBookNames = new List <string>();
                int maxlength = 0, sno = 0;
                var bookCopy = chapterwiseBible.LoadedBible.Value.Books;
                foreach (BibleBook bk in chapterwiseBible.CurrentAllBooks)
                {
                    ++sno;
                    string str = $"{sno}. {bookCopy[bk].RegionalBookName}";
                    allBookNames.Add(str);
                    maxlength = maxlength > str.Length + 2 ? maxlength : str.Length + 2;
                }                // Console.WriteLine($"{bk.BookIndex}. {bk.RegionalBookName}");
                int columns = Console.WindowWidth / maxlength;
                bk :;
                PrintSep();
                if (columns < 2)
                {
                    foreach (string val in allBookNames)
                    {
                        Console.WriteLine(val);
                    }
                }
                else
                {
                    int j = 0;
                    while (sno > j)
                    {
                        for (int i = 0; i < columns && sno > j; i++)
                        {
                            Console.Write(allBookNames[j++].PadRight(maxlength));
                        }
                        Console.WriteLine();
                    }
                }
                Console.WriteLine("Enter ID of the Book to read: ");
                if (byte.TryParse(Console.ReadLine(), out byte bookid) && bookid >= 1 && bookid <= 66 && bookCopy.ContainsKey((BibleBook)bookid))
                {
                    byte      chapter;
                    BibleBook id  = (BibleBook)bookid;
                    int       len = bookCopy[id].Chapter.Count;
                    if (len == 1)
                    {
                        chapter = 1;
                    }
                    else
                    {
                        akag : Console.Write($"This book contains {len} chapters. \nEnter Chapter number to read: ");
                        if (!byte.TryParse(Console.ReadLine(), out chapter) || chapter < 1 || chapter > len)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Invalid Chapter! Try again...");
                            Console.ResetColor();
                            goto akag;
                        }
                    }
                    sr : chapterwiseBible.LoadChapter(id, chapter);
                    DisplayChapter(chapterwiseBible.LoadedChapter, Bible.ShortBookNames[(byte)chapterwiseBible.CurrentBook], chapterwiseBible.CurrentChapter);
                    PrintSep();
                    Console.WriteLine("1. Read Next Chapter\n2. Read Previous Chapter\n3. Back to book select\n4. Back to main menu");
                    if (byte.TryParse(Console.ReadLine(), out byte rgoption))
                    {
                        switch (rgoption)
                        {
                        case 3:
                            goto bk;

                        case 4:
                            goto skip;

                        case 1:
                            chapterwiseBible.NextChapter();
                            chapter = chapterwiseBible.CurrentChapter;
                            id      = chapterwiseBible.CurrentBook;
                            goto sr;

                        case 2:
                            chapterwiseBible.PreviousChapter();
                            chapter = chapterwiseBible.CurrentChapter;
                            id      = chapterwiseBible.CurrentBook;
                            goto sr;

                        default: break;
                        }
                    }
                }
            }
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Recieved invalid input. Aborting process...");
            Console.ResetColor();
            skip :;
            void DisplayAvailableBibles()
            {
                int          choice = 1;
                ConsoleTable table  = new ConsoleTable("ID", "Title", "Language", "Version");

                foreach (BibleLink link in AvailableBibles)
                {
                    _ = table.AddRow(choice++, link.Title, link.Language, link.AionianEdition ? "Aionian" : "Standard");
                }
                table.Write();
            }

            void DisplayChapter(Dictionary <byte, string> chapter, string shortbookname, byte chapterno)
            {
                foreach (byte verse in chapter.Keys)
                {
                    string vh = $"{shortbookname} {chapterno}:{verse}";
                    Console.WriteLine($"{vh,12}|{chapter[verse]}");
                }
            }
        }