static QuoteSystem() { s_systems = new List <QuoteSystem>(); var doc = new XmlDocument(); doc.LoadXml(Resources.QuoteSystemData); foreach (XmlNode node in doc.SafeSelectNodes("//QuoteSystem")) { s_systems.Add(XmlSerializationHelper.DeserializeFromString <QuoteSystem>(node.OuterXml)); } var systemsWithAllLevels = new List <QuoteSystem>(); foreach (var quoteSystem in s_systems) { foreach (var level2 in QuoteUtils.GetLevel2Possibilities(quoteSystem.FirstLevel)) { var qs = new QuoteSystem(quoteSystem); if (!string.IsNullOrWhiteSpace(quoteSystem.Name)) { qs.Name = String.Format("{0} with levels 2 ({1}/{2}) and 3.", quoteSystem.Name, level2.Open, level2.Close); } qs.AllLevels.Add(level2); qs.AllLevels.Add(QuoteUtils.GenerateLevel3(qs, true)); systemsWithAllLevels.Add(qs); } } s_systems.AddRange(systemsWithAllLevels); }
public void AssignAll_AssignedQuoteBlocksAndAmbiguousInterruptionBlock_NotModified(ScrVersType vers) { var versification = new ScrVers(vers); var bookScript = XmlSerializationHelper.DeserializeFromString <BookScript>(@" <book id=""MRK""> <block style=""p"" chapter=""13"" initialStartVerse=""14"" characterId=""Jesus"" userConfirmed=""false"" multiBlockQuote=""Start""> <verse num=""14"" /> <text>Oona gwine see ‘De Horrible Bad Ting wa mek God place empty’ da stanop een de place weh e ain oughta dey. </text> </block> <block style=""p"" chapter=""13"" initialStartVerse=""14"" characterId=""Ambiguous"" userConfirmed=""false""> <text>(Leh oona wa da read ondastan wa dis mean.) </text> </block> <block style=""p"" chapter=""13"" initialStartVerse=""14"" characterId=""Jesus"" userConfirmed=""false"" multiBlockQuote=""Start""> <text>Wen dat time come, de people een Judea mus ron way quick ta de hill country. </text> </block> </book>" ); bookScript.Initialize(versification); var cvInfo = MockRepository.GenerateMock <ICharacterVerseInfo>(); StubGetCharactersForSingleVerse(cvInfo, kMRKbookNum, 13, 14, versification, new[] { new CharacterSpeakingMode("Jesus", null, null, false, QuoteType.Normal), new CharacterSpeakingMode("narrator-MRK", null, null, false, QuoteType.Interruption) }); Assert.IsFalse(bookScript.GetScriptBlocks().Any(b => b.UserConfirmed)); new CharacterAssigner(cvInfo).AssignAll(new[] { bookScript }, false, false); Assert.AreEqual("Jesus", bookScript[0].CharacterId); Assert.AreEqual(CharacterVerseData.kAmbiguousCharacter, bookScript[1].CharacterId); Assert.AreEqual("Jesus", bookScript[2].CharacterId); Assert.IsFalse(bookScript.GetScriptBlocks().Any(b => b.UserConfirmed)); }
public void KeyTermRules_Initialize_GetsCorrectRules() { string xmlRules = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<KeyTermRules>" + "<KeyTermRule id=\"Ar\" rule=\"MatchForRefOnly\"/>" + "<KeyTermRule id=\"ask; pray\" rule=\"MatchForRefOnly\"/>" + "<KeyTermRule id=\"(pe quot) say\" rule=\"Exclude\"/>" + "<KeyTermRule id=\"bless, praise\">" + " <Alternate name=\"blesses\"/>" + " <Alternate name=\"blessing\"/>" + "</KeyTermRule>" + "<KeyTermRule id=\"(?<term>.+): \\(\\d+\\).+; \" regex=\"true\"/>" + "<KeyTermRule id=\"\\(\\d+\\) (?<term>[^;]+): \\([^;]+\\)\" regex=\"true\"/>" + "</KeyTermRules>"; KeyTermRules rules = XmlSerializationHelper.DeserializeFromString <KeyTermRules>(xmlRules); rules.Initialize(); Assert.AreEqual(2, rules.RegexRules.Count()); Assert.IsTrue(rules.RegexRules.Any(r => r.ToString() == "(?<term>.+): \\(\\d+\\).+; ")); Assert.IsTrue(rules.RegexRules.Any(r => r.ToString() == "\\(\\d+\\) (?<term>[^;]+): \\([^;]+\\)")); Assert.IsTrue(rules.RulesDictionary["ar"].Rule == KeyTermRule.RuleType.MatchForRefOnly); KeyTermRule rule; Assert.IsTrue(rules.RulesDictionary.TryGetValue("ask; pray", out rule)); }
private BookScript GetMultiBlockBookScript() { const string bookScript = @" <book id=""MRK""> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""firstCharacter"" userConfirmed=""true"" multiBlockQuote=""Start""> <verse num=""4"" /> <text>1 </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""secondCharacter"" userConfirmed=""true"" multiBlockQuote=""Continuation""> <text>2</text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""5"" characterId=""firstCharacter"" userConfirmed=""true"" multiBlockQuote=""Start""> <verse num=""5"" /> <text>3 </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""5"" characterId=""firstCharacter"" userConfirmed=""true"" multiBlockQuote=""Continuation""> <text>4</text> </block> </book>"; var newBook = XmlSerializationHelper.DeserializeFromString <BookScript>(bookScript); newBook.Initialize(ScrVers.English); return(newBook); }
public void Deserialize_Serialize_Roundtrip() { const string startingAndExpectedXml = @"<BiblicalAuthors> <Author name=""Peter""> <Books> <Book>1PE</Book> <Book>2PE</Book> </Books> </Author> <Author name=""Obadiah""> <Books> <Book>OBA</Book> </Books> </Author> </BiblicalAuthors>"; var deserializedBiblicalAuthors = XmlSerializationHelper.DeserializeFromString <BiblicalAuthors>(startingAndExpectedXml); Assert.AreEqual(2, deserializedBiblicalAuthors.Count); var peter = deserializedBiblicalAuthors[0]; Assert.AreEqual("Peter", peter.Name); Assert.AreEqual(2, peter.Books.Count); Assert.AreEqual("1PE", peter.Books[0]); Assert.AreEqual("2PE", peter.Books[1]); var obadiah = deserializedBiblicalAuthors[1]; Assert.AreEqual("Obadiah", obadiah.Name); Assert.AreEqual(1, obadiah.Books.Count); Assert.AreEqual("OBA", obadiah.Books[0]); AssertThatXmlIn.String(startingAndExpectedXml).EqualsIgnoreWhitespace(deserializedBiblicalAuthors.GetAsXml()); }
/// ------------------------------------------------------------------------------------ public static MediaFileInfo GetInfo(string mediaFile) { var finfo = new FileInfo(mediaFile); if (!finfo.Exists || finfo.Length == 0) { var emptyMediaFileInfo = new MediaFileInfo(); emptyMediaFileInfo.Audio = new AudioInfo(); // SP-1007 return(emptyMediaFileInfo); } var info = new MediaInfo(); if (info.Open(mediaFile) == 0) { return(null); } info.Option("Inform", s_templateData); string output = info.Inform(); info.Close(); Exception error; var mediaInfo = XmlSerializationHelper.DeserializeFromString <MediaFileInfo>(output, out error); if (mediaInfo == null || mediaInfo.Audio == null) { return(null); } mediaInfo.MediaFilePath = mediaFile; return(mediaInfo); }
/// ------------------------------------------------------------------------------------ private bool LoadFwDataForPa(PaRemoteRequest requestor, string name, string server, bool loadOnlyWs, int timeToWaitForLoadingData, bool newProcessStarted, out bool foundFwProcess) { foundFwProcess = false; Func <string, string, bool> invoker = requestor.ShouldWait; DateTime endTime = DateTime.Now.AddMilliseconds(timeToWaitForLoadingData); // Wait until this process knows which project it is loading. bool shouldWait; do { IAsyncResult ar = invoker.BeginInvoke(name, server, null, null); if (!ar.AsyncWaitHandle.WaitOne(endTime - DateTime.Now, false)) { return(false); } // Get the return value of the ShouldWait method. shouldWait = invoker.EndInvoke(ar); if (shouldWait) { if (timeToWaitForLoadingData > 0 && DateTime.Now > endTime) { return(false); } Thread.Sleep(100); } } while (shouldWait); if (!requestor.IsMyProject(name, server)) { return(false); } string xml = requestor.GetWritingSystems(); m_writingSystems = XmlSerializationHelper.DeserializeFromString <List <PaWritingSystem> >(xml); if (!loadOnlyWs) { xml = requestor.GetLexEntries(); m_lexEntries = XmlSerializationHelper.DeserializeFromString <List <PaLexEntry> >(xml); } if (newProcessStarted) { requestor.ExitProcess(); } foundFwProcess = true; return(true); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates settings oibject based on the values in the given XML string. /// </summary> /// ------------------------------------------------------------------------------------ public static ComprehensionCheckingSettings LoadFromString(string xmlSettings) { try { return(XmlSerializationHelper.DeserializeFromString <ComprehensionCheckingSettings>(xmlSettings, true)); } catch (Exception) { return(null); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates settings oibject based on the values in the given XML string. /// </summary> /// ------------------------------------------------------------------------------------ public static GenerateTemplateSettings LoadFromString(string xmlSettings) { try { return(XmlSerializationHelper.DeserializeFromString <GenerateTemplateSettings>(xmlSettings, true)); } catch (Exception) { return(null); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates a MatchedPairList from the specified XML string. /// </summary> /// <param name="xmlSrc">The XML source string to load.</param> /// <param name="wsName">Name of the writing system (used for error reporting).</param> /// ------------------------------------------------------------------------------------ public static MatchedPairList Load(string xmlSrc, string wsName) { Exception e; MatchedPairList list = XmlSerializationHelper.DeserializeFromString <MatchedPairList>(xmlSrc, out e); if (e != null) { throw new ContinuableErrorException("Invalid MatchedPairs field while loading the " + wsName + " writing system.", e); } return(list ?? new MatchedPairList()); }
public void TestFixtureSetUp() { using (var stylesheetFile = TempFile.WithExtension(".xml")) { File.WriteAllText(stylesheetFile.Path, Resources.styles_xml); Exception e; m_stylesheet = Stylesheet.Load(stylesheetFile.Path, out e); Assert.IsNull(e); } m_stylesheetFromXml = XmlSerializationHelper.DeserializeFromString <Stylesheet>(kXml); }
public void SerializeDeserialize_ObjectIsSound_RoundtripDataRemainsTheSame() { Sound sound = new Sound(); var before = sound.Clone(); var xmlString = XmlSerializationHelper.SerializeToString(sound); AssertThatXmlIn.String(xmlString).HasSpecifiedNumberOfMatchesForXpath("/Sound", 1); var after = XmlSerializationHelper.DeserializeFromString <Sound>(xmlString); Assert.AreEqual(before, after); }
/// ------------------------------------------------------------------------------------ private bool GetGridSettings(SettingsPropertyValue value, XmlNode node) { if (node.Attributes.GetNamedItem("type") != null && node.Attributes["type"].Value == typeof(GridSettings).FullName) { value.PropertyValue = XmlSerializationHelper.DeserializeFromString <GridSettings>(node.InnerXml) ?? new GridSettings(); return(true); } return(false); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates a PuncPatternsList from the specified XML string. /// </summary> /// <param name="xmlSrc">The XML source string to load.</param> /// <param name="wsName">Name of the writing system (used for error reporting).</param> /// ------------------------------------------------------------------------------------ public static PuncPatternsList Load(string xmlSrc, string wsName) { Exception e; PuncPatternsList list = XmlSerializationHelper.DeserializeFromString <PuncPatternsList>(xmlSrc, out e); if (e != null) { throw new ContinuableErrorException("Invalid PunctuationPatterns field while loading the " + wsName + " writing system.", e); } return(list ?? new PuncPatternsList()); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates a QuotationMarksList from the specified XML string. /// </summary> /// <param name="xmlSrc">The XML source string to load.</param> /// <param name="wsName">Name of the writing system (used for error reporting).</param> /// ------------------------------------------------------------------------------------ public static QuotationMarksList Load(string xmlSrc, string wsName) { Exception e; QuotationMarksList list = XmlSerializationHelper.DeserializeFromString <QuotationMarksList>(xmlSrc, out e); if (e != null) { throw new ContinuableErrorException("Invalid QuotationMarks field while loading the " + wsName + " writing system.", e); } return(list == null || list.Levels == 0 ? NewList() : list); }
private void OnBackgroundProcessorWorkCompleted(object s, RunWorkerCompletedEventArgs args) { if (m_passes.Count == 0) { foreach (var newRefTextRow in m_dataGridRefTexts.Rows.OfType <DataGridViewRow>().Where(r => s_createActions.Contains((string)r.Cells[colAction.Index].Value) && !r.Cells[colHeSaidText.Index].ReadOnly && !r.Cells[colIsoCode.Index].ReadOnly)) { // Generate a new metadata file with the above info var languageName = (string)newRefTextRow.Cells[colName.Index].Value; var folder = Data.GetLanguageInfo(languageName).OutputFolder; var projectPath = Path.Combine(folder, languageName + Constants.kProjectFileExtension); if (File.Exists(projectPath)) { HandleMessageRaised($"File {projectPath} already exists! Skipping. Please verify contents.", true); } else { var metadata = XmlSerializationHelper.DeserializeFromString <GlyssenDblTextMetadata>(Resources.refTextMetadata); metadata.Language = new GlyssenDblMetadataLanguage { Name = languageName, HeSaidText = newRefTextRow.Cells[colHeSaidText.Index].Value as string, Iso = newRefTextRow.Cells[colIsoCode.Index].Value as string }; metadata.AvailableBooks = new List <Book>(); ProjectUtilities.ForEachBookFileInProject(folder, (bookId, fileName) => metadata.AvailableBooks.Add(new Book { Code = bookId, IncludeInScript = true })); metadata.LastModified = DateTime.Now; Exception error; XmlSerializationHelper.SerializeToFile(projectPath, metadata, out error); if (error != null) { HandleMessageRaised(error.Message, true); } } } m_btnOk.Enabled = m_btnSkipAll.Enabled = true; } else { BackgroundProcessor.RunWorkerAsync(); } }
private BookScript GetSimpleBookScript() { const string bookScript = @" <book id=""MRK""> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""narrator-MRK"" userConfirmed=""false""> <verse num=""4"" /> <text>Mantsa tama, ka zlagaptá Yuhwana, mnda maga Batem ma mtak, kaʼa mantsa: </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""Made Up Guy"" userConfirmed=""false""> <text>«Mbəɗanafwa mbəɗa ta nzakwa ghuni, ka magaghunafta lu ta batem, ka plighunista Lazglafta ta dmakuha ghuni,» </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""5"" characterId=""Thomas/Andrew/Bartholomew"" userConfirmed=""true""> <text>«Gobbledy-gook» </text> </block> </book>"; return(XmlSerializationHelper.DeserializeFromString <BookScript>(bookScript)); }
private VerseAnnotation CreateVerseAnnotationFromLine(string line) { string[] items = line.Split(new[] { "\t" }, StringSplitOptions.None); ScriptAnnotation annotation; string annotationXml = items[4]; //Enhance: find a way to get serialization to work properly on the base class directly if (annotationXml.StartsWith("<Sound")) { annotation = XmlSerializationHelper.DeserializeFromString <Sound>(annotationXml); } else { annotation = XmlSerializationHelper.DeserializeFromString <Pause>(annotationXml); } if (annotation == null) { throw new InvalidDataException(string.Format("The annotation {0} could not be deserialized", annotationXml)); } return(new VerseAnnotation(new BCVRef(BCVRef.BookToNumber(items[0]), int.Parse(items[1]), int.Parse(items[2])), annotation, int.Parse(items[3]))); }
public void Deserialize() { const string input = @"<QuoteSystem> <Name>Virgolette (with opening and closing 2014 Quotation dash)</Name> <MajorLanguage>Italian</MajorLanguage> <StartQuoteMarker>“</StartQuoteMarker> <EndQuoteMarker>”</EndQuoteMarker> <QuotationDashMarker>—</QuotationDashMarker> <QuotationDashEndMarker>—</QuotationDashEndMarker> </QuoteSystem>" ; var quoteSystem = XmlSerializationHelper.DeserializeFromString <QuoteSystem>(input); Assert.AreEqual("Virgolette (with opening and closing 2014 Quotation dash)", quoteSystem.Name); Assert.AreEqual("Italian", quoteSystem.MajorLanguage); Assert.AreEqual(2, quoteSystem.AllLevels.Count); Assert.AreEqual(1, quoteSystem.NormalLevels.Count); Assert.AreEqual("“", quoteSystem.FirstLevel.Open); Assert.AreEqual("”", quoteSystem.FirstLevel.Close); Assert.AreEqual("“", quoteSystem.FirstLevel.Continue); Assert.AreEqual(1, quoteSystem.FirstLevel.Level); Assert.AreEqual(QuotationMarkingSystemType.Normal, quoteSystem.FirstLevel.Type); Assert.AreEqual("—", quoteSystem.QuotationDashMarker); Assert.AreEqual("—", quoteSystem.QuotationDashEndMarker); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Return true if we have the new style of valid characters information in the /// specified string. Currently this is adequately detected by being able to interpret /// it as XML. /// </summary> /// ------------------------------------------------------------------------------------ public static bool IsNewValidCharsString(string xmlSrc) { return(XmlSerializationHelper.DeserializeFromString <ValidCharacters>(xmlSrc) != null); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Loads the specified XML source to initialize a new instance of the /// <see cref="ValidCharacters"/> class. /// </summary> /// <param name="xmlSrc">The XML source representation.</param> /// <param name="wsName">The name of the writing system that is being loaded</param> /// <param name="ws">The writing system</param> /// <param name="exceptionHandler">The exception handler to use if valid character data /// cannot be loaded.</param> /// <param name="legacyOverridesFile"></param> /// <returns></returns> /// ------------------------------------------------------------------------------------ public static ValidCharacters Load(string xmlSrc, string wsName, IWritingSystem ws, LoadExceptionDelegate exceptionHandler, string legacyOverridesFile) { Exception e; var validChars = XmlSerializationHelper.DeserializeFromString <ValidCharacters>(xmlSrc, out e); bool fTryOldStyleList = false; if (validChars != null) { validChars.LoadException += exceptionHandler; } else { validChars = new ValidCharacters(); validChars.LoadException += exceptionHandler; if (e != null) { fTryOldStyleList = !DataAppearsToBeMalFormedXml(xmlSrc); } if (!fTryOldStyleList && !String.IsNullOrEmpty(xmlSrc)) { var bldr = new StringBuilder(); bldr.AppendFormat("Invalid ValidChars field while loading the {0} writing system:", wsName); bldr.Append(Environment.NewLine); bldr.Append("\t"); bldr.Append(xmlSrc); validChars.ReportError(new ArgumentException(bldr.ToString(), "xmlSrc", e)); } } validChars.m_legacyOverridesFile = legacyOverridesFile; List <string> invalidChars = validChars.Init(); if (fTryOldStyleList) { e = null; List <string> list = ParseCharString(xmlSrc, " ", validChars.m_cpe, out invalidChars); validChars.AddCharacters(list); } if (invalidChars.Count > 0) { var bldr = new StringBuilder(); bldr.AppendFormat("Invalid ValidChars field while loading the {0} writing system. The following characters are invalid:", wsName); foreach (string chr in invalidChars) { bldr.Append(Environment.NewLine); bldr.Append("\t"); bldr.AppendFormat("{0} (U+{1:X4}", chr, (int)chr[0]); for (int ich = 1; ich < chr.Length; ich++) { bldr.AppendFormat(", U+{0:X4}", (int)chr[ich]); } bldr.Append(")"); } validChars.ReportError(new ArgumentException(bldr.ToString(), "xmlSrc")); } if ((e != null || invalidChars.Count > 0) && validChars.m_WordFormingCharacters.Count == 0) { validChars.AddDefaultWordformingCharOverrides(); } return(validChars); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Loads the specified XML source. /// </summary> /// <param name="xmlSource">The XML source.</param> /// <returns>information about the styles deserialized from the XML source</returns> /// ------------------------------------------------------------------------------------ public static StylePropsInfo Load(string xmlSource) { return(XmlSerializationHelper.DeserializeFromString <StylePropsInfo>(xmlSource)); }
private static void Load() { s_all = XmlSerializationHelper.DeserializeFromString <BiblicalAuthors>(Resources.BiblicalAuthors); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes the oxes annotation node. /// </summary> /// <param name="node">The node.</param> /// <param name="scr">The scripture.</param> /// <param name="styleSheet">The style sheet.</param> /// <returns>The deserialized annotation</returns> /// ------------------------------------------------------------------------------------ public static IScrScriptureNote Deserialize(XmlNode node, IScripture scr, FwStyleSheet styleSheet) { XmlScrNote xmlAnn = XmlSerializationHelper.DeserializeFromString <XmlScrNote>(node.OuterXml, true); return(xmlAnn.WriteToCache(scr, styleSheet)); }