/// <summary> /// Extracts the resource to a directory. /// </summary> /// <param name="path">The path.</param> /// <exception cref="ArgumentNullException"> /// path /// or /// DBLEntryUid /// or /// Name /// </exception> /// <remarks> /// After the resource is extracted, it can be a source or target. /// </remarks> public void ExtractToDirectory(string path) { // Check parameters if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(nameof(path)); } else if (string.IsNullOrWhiteSpace(this.DBLEntryUid)) { throw new ArgumentNullException(nameof(this.DBLEntryUid)); } else if (string.IsNullOrWhiteSpace(this.Name)) { throw new ArgumentNullException(nameof(this.Name)); } string resourceFile = ScrTextCollection.GetResourcePath(this.ExistingScrText, this.Name, this.DBLEntryUid); if (RobustFile.Exists(resourceFile)) { using var zipFile = ZipFile.Read(resourceFile); zipFile.Password = this._passwordProvider?.GetPassword(); zipFile.ExtractAll(path, ExtractExistingFileAction.DoNotOverwrite); } }
public static void GetParatextProjects() { var apiFolder = Util.ApiFolder(); if (!ParatextInfo.IsParatextInstalled) { return; } try { ParatextData.Initialize(); var paratextProjects = ScrTextCollection.ScrTexts(IncludeProjects.ScriptureOnly); if (paratextProjects == null) { return; } var jsonList = ParatextProjectsJsonList(paratextProjects); using (var sw = new StreamWriter(Path.Combine(apiFolder, "GetParatextProjects"))) { sw.Write($"[{string.Join(",", jsonList)}]"); } } catch (Exception ex) { string error = ex.Message; Debug.Print(error); Logger.WriteEvent(error); } }
/// <summary> Set the directory to the folder containing Paratext projects. </summary> public void Initialize(string projectsPath) { SettingsDirectory = projectsPath; // Initialize so that Paratext.Data can find settings files ScrTextCollection.Implementation = new SFScrTextCollection(); ScrTextCollection.Initialize(projectsPath); }
/// -------------------------------------------------------------------------------- /// <summary> /// Refreshes the list of Paratext projects. /// </summary> /// -------------------------------------------------------------------------------- public void RefreshProjects() { try { if (ParatextSettingsDirectoryExists()) { if (!m_IsParatextInitialized) { // It is possible that the Projects directory was not available when we first initialized // ScrTextCollection, but it now is (e.g. USB drive plugged or unplugged). So we initialize // again. ScrTextCollection.Initialize is safe to call multiple times and also refreshes texts. // We pass the directory (rather than passing no arguments, and letting the paratext dll figure // it out) because the figuring out goes wrong on Linux, where both programs are simulating // the registry. ScrTextCollection.Initialize(ParatextSettingsDirectory(), false); m_IsParatextInitialized = true; } else { ScrTextCollection.RefreshScrTexts(); } } else { m_IsParatextInitialized = false; } } catch (Exception e) { Logger.WriteError(e); m_IsParatextInitialized = false; } }
public void SetsSettingsDirectory() { ScrTextCollection.Implementation = new SFScrTextCollection(); ScrTextCollection.Initialize("/srv/scriptureforge/projects"); string dir = ScrTextCollection.SettingsDirectory; Assert.That(dir, Is.EqualTo("/srv/scriptureforge/projects")); }
/// <summary> /// The Transcribed Data is moved to Paratext SFM /// </summary> /// <param name="taskId">Task Id</param> /// <param name="heading">Heading for scripture</param> /// <returns>true if upload successful</returns> public static bool Upload(string taskId, string heading) { if (!ParatextInfo.IsParatextInstalled) { return(false); } try { // Get Task Details var currentTask = new Task(); currentTask = currentTask.GetTask(taskId); // Get the Task Transcription Text from EAF var folder = Util.FileFolder(taskId); string eafFilePath = Path.Combine(folder, Path.GetFileNameWithoutExtension(taskId) + ".eaf"); var transcriptionArray = GetTranscriptionTextFromEaf(eafFilePath); if (transcriptionArray[0].Trim().ToUpper().StartsWith("File Error:")) { return(false); } ParatextData.Initialize(); var paratextProject = ScrTextCollection.Find(currentTask.Project); if (paratextProject == null) { return(false); } var bookNum = paratextProject.BookNames.ScrText.BookNames.GetBookNumFromName(currentTask.BookName, true, BookNameSource.Abbreviation); if (bookNum == 0) { bookNum = (from i in paratextProject.BookNames.GetBookNames() where i.BookCode == currentTask.BookName select i.BookNum).FirstOrDefault(); } var vRef = new VerseRef(bookNum, currentTask.ChapterNumber, Convert.ToInt32(currentTask.VerseStart), paratextProject.Settings.Versification); var chapterContent = paratextProject.GetText(vRef, true, true); var sb = GenerateParatextData(currentTask, chapterContent, transcriptionArray[1], heading); paratextProject.PutText(bookNum, currentTask.ChapterNumber, true, sb.ToString(), null); return(true); } catch (Exception ex) { var error = ex.Message; Debug.Print(error); Logger.WriteEvent(error); } return(false); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Install the control. /// </summary> /// <param name="dockHost">The control that hosts the browser</param> /// <param name="cache">The cache (needed in case we have to create the English LDS file /// on the fly)</param> /// <param name="normalStyle">The normal style (needed in case we have to create the /// English LDS file on the fly)</param> /// <returns> /// <c>true</c> if the browser was installed successfully; <c>false</c> /// otherwise. /// </returns> /// ------------------------------------------------------------------------------------ public bool Install(Control dockHost, FdoCache cache, IStStyle normalStyle) { while (true) { try { RegistrationInfo.AllowP6RegistrationCode = true; RegistrationInfo.AllowAccessToResources(); string paratextProjectDir = ScrImportP6Project.ProjectDir; if (!String.IsNullOrEmpty(paratextProjectDir)) { string englishLdsPathname = Path.Combine(paratextProjectDir, "English.lds"); if (!File.Exists(englishLdsPathname)) { ParatextLdsFileAccessor ldsAccessor = new ParatextLdsFileAccessor(cache); UsfmStyEntry normalUsfmStyle = new UsfmStyEntry(); StyleInfoTable styleTable = new StyleInfoTable(normalStyle.Name, cache.LanguageWritingSystemFactoryAccessor); normalUsfmStyle.SetPropertiesBasedOnStyle(normalStyle); styleTable.Add(normalStyle.Name, normalUsfmStyle); styleTable.ConnectStyles(); ldsAccessor.WriteParatextLdsFile(englishLdsPathname, cache.LanguageWritingSystemFactoryAccessor.GetWsFromStr("en"), normalUsfmStyle); } } ScrTextCollection.Initialize(); break; } catch (Exception e) { try { ReflectionHelper.SetField(typeof(ScrTextCollection), "initialized", false); } catch (Exception reflectionHelperException) { throw new ContinuableErrorException("Paratext resource browser failed to initialize." + Environment.NewLine + reflectionHelperException.Message, e); } if (MessageBox.Show(dockHost.FindForm(), String.Format( Properties.Resources.kstidCannotDisplayResourcePane, Application.ProductName, e.Message), Application.ProductName, MessageBoxButtons.RetryCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) != DialogResult.Retry) { return(false); } } } m_toolStrip.Text = "USFM Resource Browser"; m_extender = new DockExtender(dockHost); dockHost.Controls.Add(this); m_floaty = m_extender.Attach(this, m_toolStrip, true); this.SendToBack(); return(true); }
/// <summary> Get list of book numbers in PT project. </summary> public IReadOnlyList <int> GetBookList(UserSecret userSecret, string ptProjectId) { ScrText scrText = ScrTextCollection.FindById(GetParatextUsername(userSecret), ptProjectId); if (scrText == null) { return(Array.Empty <int>()); } return(scrText.Settings.BooksPresentSet.SelectedBookNumbers.ToArray()); }
/// -------------------------------------------------------------------------------- /// <summary> /// Refreshes the list of Paratext projects. /// </summary> /// -------------------------------------------------------------------------------- public void RefreshProjects() { try { ScrTextCollection.RefreshScrTexts(); } catch (Exception e) { Logger.WriteError(e); } }
static ParatextProxy() { try { ScrTextCollection.Initialize(); } catch (Exception e) { Logger.WriteError(e); } }
/// <summary/> public ParatextHelperAdapter() { try { ScrTextCollection.Initialize(); } catch (Exception e) { Logger.WriteError(e); } }
/// <summary> Get PT book text in USX, or throw if can't. </summary> public string GetBookText(UserSecret userSecret, string ptProjectId, int bookNum) { ScrText scrText = ScrTextCollection.FindById(GetParatextUsername(userSecret), ptProjectId); if (scrText == null) { throw new DataNotFoundException("Can't get access to cloned project."); } string usfm = scrText.GetText(bookNum); return(UsfmToUsx.ConvertToXmlString(scrText, bookNum, usfm, false)); }
/// -------------------------------------------------------------------------------- /// <summary> /// Gets the list of Paratext projects. /// </summary> /// -------------------------------------------------------------------------------- public IEnumerable <ScrText> GetProjects() { try { ScrTextCollection.RefreshScrTexts(); return(ScrTextCollection.ScrTexts); } catch (Exception e) { Logger.WriteError(e); return(new ScrText[0]); } }
/// <summary> Get notes from the Paratext project folder. </summary> public string GetNotes(UserSecret userSecret, string projectId, int bookNum) { // TODO: should return some data structure instead of XML ScrText scrText = ScrTextCollection.FindById(GetParatextUsername(userSecret), projectId); if (scrText == null) { return(null); } CommentManager manager = CommentManager.Get(scrText); var threads = manager.FindThreads((commentThread) => { return(commentThread.VerseRef.BookNum == bookNum); }, true); return(NotesFormatter.FormatNotes(threads)); }
static void Main(string[] args) { if (args.Length != 5) { Console.WriteLine("Usage: rdwrtp7 -r|-w project book chapter|0 fileName"); Environment.Exit(-1); } ScrTextCollection.Initialize(); string operation = args[0]; string project = args[1]; string book = args[2]; string chapter = args[3]; string file = args[4]; ScrText scr = ScrTextCollection.Get(project); if (scr == null) { Console.WriteLine("Error: unknown project"); Environment.Exit(-1); } VerifyBook(book); VerifyChapter(chapter); VerseRef vref = new VerseRef(book, chapter, "1", scr.Versification); try { if (operation == "-r") DoRead(scr, vref, file); else if (operation == "-w") DoWrite(scr, vref, file); else { Console.WriteLine("Error: unknown operation"); Environment.Exit(-1); } } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(-1); } }
private void LoadSavedSelectionItem_Click(object sender, EventArgs e) { SavedScrTextList savedList = (sender as ToolStripMenuItem).Tag as SavedScrTextList; rightItems = new List <ScrText>(); foreach (string scrTextName in savedList.ScrTextNames) { ScrText scrText = ScrTextCollection.Get(scrTextName); if (scrText != null) { rightItems.Add(scrText); } } UpdateRightList(); UpdateSavedSelectionLinks(); }
/// <summary> /// Ensure the target project repository exists on the local SF server, cloning if necessary. /// </summary> private void EnsureProjectReposExists(UserSecret userSecret, ParatextProject target, IInternetSharedRepositorySource repositorySource) { string username = GetParatextUsername(userSecret); bool targetNeedsCloned = ScrTextCollection.FindById(username, target.ParatextId) == null; if (target is ParatextResource resource) { // If the target is a resource, install it InstallResource(resource, target.ParatextId, targetNeedsCloned); } else if (targetNeedsCloned) { SharedRepository targetRepo = new SharedRepository(target.ShortName, HexId.FromStr(target.ParatextId), RepositoryType.Shared); CloneProjectRepo(repositorySource, target.ParatextId, targetRepo); } }
/// -------------------------------------------------------------------------------- /// <summary> /// Gets the list of Paratext projects. /// </summary> /// -------------------------------------------------------------------------------- public IEnumerable <ScrText> GetProjects() { RefreshProjects(); if (m_IsParatextInitialized) { try { // The booleans say we are including resources (translations etc that are part of the Paratext release) // and non-Scripture items (not sure what these are). // Most likely neither of these are necessary, but I'm preserving the behavior we had with 7.3, // which did not have these arguments. // We also filter out invalid ScrTexts, because there is a bug in Paratext that allows them to get through. return(ScrTextCollection.ScrTexts(true, true).Where(st => Directory.Exists(st.Directory))); } catch (Exception e) { Logger.WriteError(e); m_IsParatextInitialized = false; } } return(new ScrText[0]); }
/// <summary> Prepare access to Paratext.Data library, authenticate, and prepare Mercurial. </summary> public void Init() { // Uncomment to output more info from ParatextData.dll for investigating. // Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // Trace.AutoFlush = true; SyncDir = Path.Combine(_siteOptions.Value.SiteDir, "sync"); if (!_fileSystemService.DirectoryExists(SyncDir)) { _fileSystemService.CreateDirectory(SyncDir); } // Disable caching VersionedText instances since multiple repos may exist on SF server with the same GUID Environment.SetEnvironmentVariable("PTD_CACHE_VERSIONED_TEXT", "DISABLED"); RegistryU.Implementation = new DotNetCoreRegistry(); Alert.Implementation = new DotNetCoreAlert(_logger); ParatextDataSettings.Initialize(new PersistedParatextDataSettings()); PtxUtilsDataSettings.Initialize(new PersistedPtxUtilsSettings()); SetupMercurial(); WritingSystemRepository.Initialize(); ScrTextCollection.Initialize(SyncDir); InstallStyles(); // Allow use of custom versification systems Versification.Table.Implementation = new ParatextVersificationTable(); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Restore settings (currently the list of texts displayed). /// </summary> /// <param name="key">The key.</param> /// ------------------------------------------------------------------------------------ public void LoadSettings(RegistryKey key) { try { m_floaty.LoadSettings(key); string texts = key.GetValue("UsfmTexts", "") as string; if (string.IsNullOrEmpty(texts)) { return; // foreach below does one iteration for empty string, which is bad. } List <TextCollectionItem> items = new List <TextCollectionItem>(); foreach (string name in texts.Split(',')) { ScrText text = null; try { foreach (ScrText st in ScrTextCollection.ScrTexts(true, true)) { if (st.Name == name) { text = st; break; } } } catch (Exception) { // If we for some reason can't make that text, carry on with the others. continue; } if (text == null) { continue; // forget any saved item that is no longer an option. } items.Add(new TextCollectionItem(text, 1.0)); } m_textCollection.Items = items; string curItemName = key.GetValue("UsfmCurItem", "") as string; if (string.IsNullOrEmpty(curItemName)) { for (int i = 0; i < m_textCollection.Items.Count; i++) { if (m_textCollection.Items[i].ScrText.Name == curItemName) { m_textCollection.CurItem = i; break; } } } // Paratext now requires a versification for Reload(), // so we'll default to English at this point. m_textCollection.Reference = new VerseRef("MAT 1:1", ScrVers.English); tryReloadTextCollection(); VerseRef vr = new VerseRef("MAT 1:1"); // default string reference = key.GetValue("UsfmCurRef", null) as string; if (!string.IsNullOrEmpty(reference)) { vr = new VerseRef(reference); } m_textCollection.CurItem = (int)key.GetValue("UsfmCurSel", -1); SetScriptureReference(vr); } catch { // ignore any problems. } }
private void SelectTexts() { // Create list of current items List <ScrText> currentItems = new List <ScrText>(); foreach (TextCollectionItem item in m_textCollection.Items) { currentItems.Add(item.ScrText); } TextCollectionItem currentItem = null; if (m_textCollection.CurItem >= 0 && m_textCollection.CurItem < m_textCollection.Items.Count) { currentItem = m_textCollection.Items[m_textCollection.CurItem]; } // Re-initialize, just in case. // We pass the directory (rather than passing no arguments, and letting the paratext dll figure // it out) because the figuring out goes wrong on Linux, where both programs are simulating // the registry. ScrTextCollection.Initialize(ParatextHelper.ProjectsDirectory, false); List <string> textNames = ScrTextCollection.ScrTextNames; foreach (string nameVar in textNames) { if (nameVar.Length < 1) { continue; } string name = nameVar.ToLower(); // Ignore P6 source language texts. if (name == "lxx" || name == "grk" || name == "heb") { continue; } try { if (ScrTextCollection.Get(nameVar) == null) { // REVIEW: I'm not sure how/if ScrTextCollection gets disposed ScrText scrText = new ScrText(nameVar); ScrTextCollection.Add(scrText); } } catch (Exception) { //MessageBox.Show(name + ": " + exception.Message); // TODO What will happen if a text can't be loaded? } } // the two booleans indicate we want all the available texts, including resources (part of the Paratext distribution) // and non-scriptural materials (things like commentaries maybe?) using (ScrTextListSelectionForm selForm = new ScrTextListSelectionForm( ScrTextCollection.ScrTexts(true, true), currentItems)) { if (selForm.ShowDialog(this) == DialogResult.OK) { // Create new list of items, keeping data from old one (to preserve zoom etc) List <TextCollectionItem> newItems = new List <TextCollectionItem>(); foreach (ScrText scrText in selForm.Selections) { // Attempt to find in old list bool found = false; foreach (TextCollectionItem item in m_textCollection.Items) { if (item.ScrText == scrText) { newItems.Add(item); found = true; break; } } if (!found) { newItems.Add(new TextCollectionItem(scrText, 1)); } } m_textCollection.Items = newItems; int curItemIndex = -1; // none selected for (int i = 0; i < newItems.Count; i++) { if (newItems[i] == currentItem) { curItemIndex = i; break; } } // select some current item if possible; out of range does not cause problem. // Currently it seems to cause a crash if the item is out of range for the OLD items; // I think this is a bug in the Paratext code. if (curItemIndex == -1 && m_textCollection.Items.Count > 0 && currentItems.Count > 0) { curItemIndex = 0; } m_textCollection.CurItem = curItemIndex; tryReloadTextCollection(); } } }
public IEnumerable <IScrText> ScrTexts() { return(ScriptureProvider.WrapPtCollection(ScrTextCollection.ScrTexts(IncludeProjects.ScriptureOnly), new Func <ScrText, IScrText>(ptText => new PT8ScrTextWrapper(ptText)))); }
public IScrText Get(string project) { return(new PT8ScrTextWrapper(ScrTextCollection.Get(project))); }
// Note: This method is very similar to the method by the same name in HearThis' ChooseProject dialog. If improvements // are made here, they should also be made there if applicable. // TODO: Move this into libpalaso private IEnumerable <ScrText> GetParatextProjects() { ScrText[] paratextProjects = null; try { paratextProjects = ScrTextCollection.ScrTexts(IncludeProjects.AccessibleScripture).ToArray(); var loadErrors = Program.CompatibleParatextProjectLoadErrors.ToList(); if (loadErrors.Any()) { StringBuilder sb = new StringBuilder(String.Format(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.ParatextProjectLoadErrors", "The following {0} project load errors occurred:", "Param 0: \"Paratext\" (product name)"), ParatextScrTextWrapper.kParatextProgramName)); foreach (var errMsgInfo in loadErrors) { sb.Append("\n\n"); try { switch (errMsgInfo.Reason) { case UnsupportedReason.UnknownType: AppendVersionIncompatibilityMessage(sb, errMsgInfo); sb.AppendFormat(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.ParatextProjectLoadError.UnknownProjectType", "This project has a project type ({0}) that is not supported.", "Param 0: Paratext project type"), errMsgInfo.ProjecType); break; case UnsupportedReason.CannotUpgrade: // Glyssen is newer than project version AppendVersionIncompatibilityMessage(sb, errMsgInfo); sb.AppendFormat(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.ParatextProjectLoadError.ProjectOutdated", "The project administrator needs to update it by opening it with {0} {1} or later. " + "Alternatively, you might be able to revert to an older version of {2}.", "Param 0: \"Paratext\" (product name); " + "Param 1: Paratext version number; " + "Param 2: \"Glyssen\" (product name)"), ParatextScrTextWrapper.kParatextProgramName, ParatextInfo.MinSupportedParatextDataVersion, GlyssenInfo.kProduct); break; case UnsupportedReason.FutureVersion: // Project version is newer than Glyssen AppendVersionIncompatibilityMessage(sb, errMsgInfo); sb.AppendFormat(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.ParatextProjectLoadError.GlyssenVersionOutdated", "To read this project, a version of {0} compatible with {1} {2} is required.", "Param 0: \"Glyssen\" (product name); " + "Param 1: \"Paratext\" (product name); " + "Param 2: Paratext version number"), GlyssenInfo.kProduct, ParatextScrTextWrapper.kParatextProgramName, ScrTextCollection.ScrTexts(IncludeProjects.Everything).First( p => p.Name == errMsgInfo.ProjectName).Settings.MinParatextDataVersion); break; case UnsupportedReason.Corrupted: case UnsupportedReason.Unspecified: sb.AppendFormat(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.ParatextProjectLoadError.Generic", "Project: {0}\nError message: {1}", "Param 0: Paratext project name; Param 1: error details"), errMsgInfo.ProjectName, errMsgInfo.Exception.Message); break; default: throw errMsgInfo.Exception; } } catch (Exception e) { ErrorReport.ReportNonFatalException(e); } } MessageBox.Show(sb.ToString(), Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception err) { NotifyUserOfParatextProblem(String.Format(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.CantAccessParatext", "There was a problem accessing {0} data files.", "Param: \"Paratext\" (product name)"), ParatextScrTextWrapper.kParatextProgramName), string.Format(LocalizationManager.GetString("DialogBoxes.OpenProjectDlg.ParatextError", "The error was: {0}"), err.Message)); paratextProjects = new ScrText[0]; } // ENHANCE (PG-63): Implement something like this if we decide to give the user the option of manually // specifying the location of Paratext data files if the program isn’t actually installed. // to select the location of Paratext data files. //if (paratextProjects.Any()) //{ // _lblNoParatextProjectsInFolder.Visible = false; // _lblNoParatextProjects.Visible = false; //} //else //{ // if (ParatextInfo.IsParatextInstalled) // _lblNoParatextProjects.Visible = true; // else // { // _lblNoParatextProjectsInFolder.Visible = _tableLayoutPanelParatextProjectsFolder.Visible; // } //} return(paratextProjects); }
public void RefreshScrTexts() { ScrTextCollection.RefreshScrTexts(); }
public bool LoadProjectMappings(string project, ScrMappingList mappingList, ImportDomain domain) { // If the new project ID is null, then do not load mappings. if (project == null) { return(false); } // Load the tags from the paratext project and create mappings for them. ScrText scParatextText; try { // REVIEW (EberhardB): I'm not sure if ScrTextCollection.Get() returns a // reference to a ScrText or a new object (in which case we would have to // call Dispose() on it) scParatextText = ScrTextCollection.Get(project); } catch (Exception ex) { Logger.WriteError(ex); return(false); } mappingList.ResetInUseFlags(domain); try { foreach (ScrTag tag in scParatextText.DefaultStylesheet.Tags) { if (tag == null) { break; } string marker = @"\" + tag.Marker; string endMarker = string.Empty; if (!String.IsNullOrEmpty(tag.Endmarker)) { endMarker = @"\" + tag.Endmarker; } // When the nth marker has an end marker, the nth + 1 marker will be // that end marker. Therefore, we have to skip those "end style" markers. if (tag.StyleType == ScrStyleType.scEndStyle) { continue; } // Create a new mapping for this marker. mappingList.AddDefaultMappingIfNeeded(marker, endMarker, domain, false, false); } ScrParser parser = scParatextText.Parser(); foreach (int bookNum in scParatextText.BooksPresentSet.SelectedBookNumbers()) { foreach (UsfmToken token in parser.GetUsfmTokens(new VerseRef(bookNum, 0, 0), false, true)) { if (token.Marker == null) { continue; // Tokens alternate between text and marker types } ImportMappingInfo mapping = mappingList[@"\" + token.Marker]; if (mapping != null) { mapping.SetIsInUse(domain, true); } // ENHANCE (TE-4408): Consider Detecting markers that occur in the data but are missing // from the STY file. How can we write a test for this? //else if (ScrImportFileInfo.IsValidMarker(sMarker)) //{ // mappingList.AddDefaultMappingIfNeeded(sMarker,domain, false, true); //} //else //{ // throw new ScriptureUtilsException(SUE_ErrorCode.InvalidCharacterInMarker, null, 0, // sMarker + sText, new ScrReference(scParatextTextSegment.FirstReference.BBCCCVVV)); //} } } } catch (Exception ex) { Logger.WriteError(ex); return(false); } return(true); }
/// <summary> Write up-to-date notes from the mongo database to the Paratext project folder </summary> public void PutNotes(UserSecret userSecret, string projectId, string notesText) { // TODO: should accept some data structure instead of XML string username = GetParatextUsername(userSecret); List <string> users = new List <string>(); int nbrAddedComments = 0, nbrDeletedComments = 0, nbrUpdatedComments = 0; ScrText scrText = ScrTextCollection.FindById(username, projectId); if (scrText == null) { throw new DataNotFoundException("Can't get access to cloned project."); } CommentManager manager = CommentManager.Get(scrText); var ptUser = new SFParatextUser(username); var notes = NotesFormatter.ParseNotes(notesText, ptUser); // Algorithm sourced from Paratext DataAccessServer foreach (var thread in notes) { CommentThread existingThread = manager.FindThread(thread[0].Thread); foreach (var comment in thread) { var existingComment = existingThread?.Comments.FirstOrDefault(c => c.Id == comment.Id); if (existingComment == null) { manager.AddComment(comment); nbrAddedComments++; } else if (comment.Deleted) { existingComment.Deleted = true; nbrDeletedComments++; } else { existingComment.ExternalUser = comment.ExternalUser; existingComment.Contents = comment.Contents; existingComment.VersionNumber += 1; nbrUpdatedComments++; } if (!users.Contains(comment.User)) { users.Add(comment.User); } } } try { foreach (string user in users) { manager.SaveUser(user, false); } _paratextDataHelper.CommitVersionedText(scrText, $"{nbrAddedComments} notes added and " + $"{nbrDeletedComments + nbrUpdatedComments} notes updated or deleted in synchronize"); _logger.LogInformation("{0} added {1} notes, updated {2} notes and deleted {3} notes", userSecret.Id, nbrAddedComments, nbrUpdatedComments, nbrDeletedComments); } catch (Exception e) { _logger.LogError(e, "Exception while updating notes: {0}", e.Message); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Method adapted from TextCollectionControl method of same name, to use our dialog. /// </summary> /// ------------------------------------------------------------------------------------ private void SelectTexts() { // Create list of current items List <ScrText> currentItems = new List <ScrText>(); foreach (TextCollectionItem item in m_textCollection.Items) { currentItems.Add(item.ScrText); } TextCollectionItem currentItem = null; if (m_textCollection.CurItem >= 0 && m_textCollection.CurItem < m_textCollection.Items.Count) { currentItem = m_textCollection.Items[m_textCollection.CurItem]; } ScrTextCollection.Initialize(); // Re-initialize, just in case List <string> textNames = ScrTextCollection.ScrTextNames; foreach (string nameVar in textNames) { if (nameVar.Length < 1) { continue; } string name = nameVar.ToLower(); // Ignore P6 source language texts. if (name == "lxx" || name == "grk" || name == "heb") { continue; } try { if (ScrTextCollection.Get(nameVar) == null) { ScrText scrText = new ScrText(nameVar); ScrTextCollection.Add(scrText); } } catch (Exception) { //MessageBox.Show(name + ": " + exception.Message); // TODO What will happen if a text can't be loaded? } } ScrTextListSelectionForm selForm = new ScrTextListSelectionForm( ScrTextCollection.ScrTexts, currentItems); if (selForm.ShowDialog(this) == DialogResult.OK) { // Create new list of items, keeping data from old one (to preserve zoom etc) List <TextCollectionItem> newItems = new List <TextCollectionItem>(); foreach (ScrText scrText in selForm.Selections) { // Attempt to find in old list bool found = false; foreach (TextCollectionItem item in m_textCollection.Items) { if (item.ScrText == scrText) { newItems.Add(item); found = true; break; } } if (!found) { newItems.Add(new TextCollectionItem(scrText, 1)); } } m_textCollection.Items = newItems; int curItemIndex = -1; // none selected for (int i = 0; i < newItems.Count; i++) { if (newItems[i] == currentItem) { curItemIndex = i; break; } } // select some current item if possible; out of range does not cause problem. // Currently it seems to cause a crash if the item is out of range for the OLD items; // I think this is a bug in the Paratext code. if (curItemIndex == -1 && m_textCollection.Items.Count > 0 && currentItems.Count > 0) { curItemIndex = 0; } m_textCollection.CurItem = curItemIndex; tryReloadTextCollection(); } }
public void Initialize() { ScrTextCollection.Initialize(); }
public IEnumerable <IScrText> ScrTexts() { return(ScriptureProvider.WrapPtCollection(ScrTextCollection.ScrTexts(true, true), new Func <ScrText, IScrText>(ptText => new PT7ScrTextWrapper(ptText)))); }