private void CreateTryAWordSandbox()
        {
            // skip if it's before we've set the word
            if (m_sWordForm == null)
            {
                return;
            }
            // skip if it's before we've set up the rootsite control
            if (m_rootb == null)
            {
                return;
            }
            // skip if we're not visible
            if (!Visible)
            {
                return;
            }
            //Debug.WriteLine("TryAWordRootSite:WordForm - creating sandbox for " + m_sWordForm.Text);
            NonUndoableUnitOfWorkHelper.Do(m_fdoCache.ActionHandlerAccessor, () =>
            {
                m_wordform = WfiWordformServices.FindOrCreateWordform(m_fdoCache, m_sWordForm);
            });
            //if (m_fdoCache.IsDummyObject(hvo))
            //	m_wordform = new WfiWordform();

            IAnalysis analysis = m_vc.GetGuessForWordform(m_wordform, m_fdoCache.DefaultVernWs);

            if (analysis is NullWAG)
            {
                analysis = m_wordform;
            }

            m_rootb.SetRootObject(analysis.Hvo, m_vc, m_kfragSingleInterlinearAnalysisWithLabels, m_styleSheet);

            //Debug.Assert(m_tryAWordSandbox == null);
            m_tryAWordSandbox = new TryAWordSandbox(m_fdoCache,
                                                    Mediator,
                                                    StyleSheet,
                                                    m_vc.LineChoices,
                                                    analysis);
            m_tryAWordSandbox.Visible = false;
            Controls.Add(m_tryAWordSandbox);
            SetSandboxSize();
            SetSandboxLocation();
            m_tryAWordSandbox.Visible = true;
            SetBackgroundColor();
            int height = Math.Max(ScrollRange.Height, m_tryAWordSandbox.Height) + SystemInformation.HorizontalScrollBarHeight;

            if (Height != height)
            {
                Height = height;
            }
            m_tryAWordSandbox.SizeChanged += m_tryAWordSandbox_SizeChanged;
            //m_tryAWordSandbox.Focus();
        }
Beispiel #2
0
        /// <summary>
        /// Handles the xWorks message to insert a new FsFeatDefn.
        /// Invoked by the RecordClerk via a main menu.
        /// </summary>
        /// <param name="argument">The xCore Command object.</param>
        /// <returns>true, if we handled the message, otherwise false, if there was an unsupported 'classname' parameter</returns>
        public override bool OnDialogInsertItemInVector(object argument)
        {
            CheckDisposed();

            Debug.Assert(argument != null && argument is XCore.Command);
            string className = XmlUtils.GetOptionalAttributeValue(
                (argument as XCore.Command).Parameters[0], "className");

            if ((className == null) || (className != "FsClosedFeature"))
            {
                return(false);
            }
            if (className == "FsClosedFeature" && (argument as XCore.Command).Id != "CmdInsertPhonologicalClosedFeature")
            {
                return(false);
            }

            using (MasterPhonologicalFeatureListDlg dlg = new MasterPhonologicalFeatureListDlg(className))
            {
                LcmCache cache = m_propertyTable.GetValue <LcmCache>("cache");
                Debug.Assert(cache != null);
                string sXmlFile = Path.Combine(FwDirectoryFinder.CodeDirectory, String.Format("Language Explorer{0}MGA{0}GlossLists{0}PhonFeatsEticGlossList.xml", Path.DirectorySeparatorChar));
                if (cache.LanguageProject.PhFeatureSystemOA == null)
                {
                    // Mainly for Memory-only backend, makes system more self-repairing.
                    NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(cache.ActionHandlerAccessor,
                                                                       () =>
                    {
                        cache.LanguageProject.PhFeatureSystemOA =
                            cache.ServiceLocator.GetInstance <IFsFeatureSystemFactory>().Create();
                    });
                }
                dlg.SetDlginfo(cache.LangProject.PhFeatureSystemOA, m_mediator, m_propertyTable, true, "masterPhonFeatListDlg", sXmlFile);
                switch (dlg.ShowDialog(m_propertyTable.GetValue <Form>("window")))
                {
                case DialogResult.OK:                         // Fall through.
                case DialogResult.Yes:
                    //m_mediator.SendMessage("JumpToRecord", dlg.SelectedFeatDefn.Hvo);
                    // This is the equivalent functionality, but is deferred processing.
                    // This is done so that the JumpToRecord can be processed last.
                    if (dlg.SelectedFeatDefn != null)
                    {
                        m_mediator.BroadcastMessageUntilHandled("JumpToRecord", dlg.SelectedFeatDefn.Hvo);
                    }
                    // LT-6412: this call will now cause the Mediator to be disposed while it is busy processing
                    // this call, so there is code in the Mediator to handle in the middle of a msg the case
                    // where the object is nolonger valid.  This has happend before and was being handled, this
                    // call "SendMessageToAllNow" has not had the code to handle the exception, so it was added.
                    m_mediator.SendMessageToAllNow("MasterRefresh", cache.LangProject.PhFeatureSystemOA);
                    break;
                }
            }
            return(true);            // We "handled" the message, regardless of what happened.
        }
Beispiel #3
0
        private void CommonAddWS(bool isAnalysis, MenuItem selectedMI)
        {
            CoreWritingSystemDefinition ws = null;

            if (selectedMI.Text == LexTextControls.ks_DefineNew_)
            {
                if (FwWritingSystemSetupDlg.ShowNewDialog(FindForm(), m_cache, m_helpTopicProvider, m_app,
                                                          isAnalysis ? FwWritingSystemSetupModel.ListType.Analysis : FwWritingSystemSetupModel.ListType.Vernacular,
                                                          out var newWritingSystems))
                {
                    ws = newWritingSystems.FirstOrDefault();
                }
            }
            else
            {
                ws = selectedMI.Tag as CoreWritingSystemDefinition;
            }

            if (ws != null)
            {
                m_wsNew = ws;
                // now add the ws to the FDO list for it
                NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
                {
                    // Add a global writing system to the local writing system store.  (Replace
                    // does this if there's nothing to replace.)
                    if (m_wsNew.Handle == 0)
                    {
                        m_cache.ServiceLocator.WritingSystemManager.Replace(m_wsNew);
                    }
                    if (isAnalysis)
                    {
                        m_cache.ServiceLocator.WritingSystems.AnalysisWritingSystems.Add(m_wsNew);
                        if (!m_cache.ServiceLocator.WritingSystems.CurrentAnalysisWritingSystems.Contains(m_wsNew))
                        {
                            m_cache.ServiceLocator.WritingSystems.CurrentAnalysisWritingSystems.Add(m_wsNew);
                        }
                    }
                    else
                    {
                        m_cache.ServiceLocator.WritingSystems.VernacularWritingSystems.Add(m_wsNew);
                        if (!m_cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems.Contains(m_wsNew))
                        {
                            m_cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems.Add(m_wsNew);
                        }
                    }
                    ProgressDialogWithTask.ImportTranslatedListsForWs(this.FindForm(), m_cache, m_wsNew.IcuLocale);
                });
                if (WritingSystemAdded != null)
                {
                    WritingSystemAdded(this, new EventArgs());
                }
            }
        }
Beispiel #4
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Fixture setup - define Scripture Check IDs.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public override void FixtureSetup()
 {
     base.FixtureSetup();
     // force scripture check definitions to be created - don't want this done as
     // part of the normal undoable work.
     NonUndoableUnitOfWorkHelper.Do(m_actionHandler, () =>
     {
         InstalledScriptureChecks.GetChecks(new ScrChecksDataSource(m_scr.Cache,
                                                                    ResourceHelper.GetResourceString("kstidPunctCheckWhitespaceChar"), FwDirectoryFinder.LegacyWordformingCharOverridesFile));
     });
 }
        /// <summary>
        /// If there are no pronunciation writing systems selected, make a default set, with IPA variants
        /// coming before EMC variants (if either of those exist).  If neither exists, the primary
        /// vernacular writing system is selected.
        /// </summary>
        private void InitializePronunciationWritingSystems()
        {
            if (m_currentPronunciationWritingSystems.Count > 0)
            {
                return;
            }

            NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(Cache.ActionHandlerAccessor,
                                                               () =>
            {
                var writingSystems = m_vernacularWritingSystems;
                var wsVern         = DefaultVernacularWritingSystem;
                var sVern          = wsVern.IcuLocale.ToLower();
                var idx            = sVern.IndexOf("_");
                sVern = idx > 0 ? sVern.Substring(0, idx + 1) : sVern + '_';
                // Add any relevant IPA writing systems: those that match the default vernacular at the start and end with _ipa
                foreach (var nws in writingSystems)
                {
                    var icuLocale = nws.IcuLocale.ToLower();
                    if (icuLocale.IndexOf(sVern) != 0)
                    {
                        continue;
                    }

                    idx = icuLocale.LastIndexOf("_ipa");
                    if (idx >= sVern.Length && idx == icuLocale.Length - 4)
                    {
                        m_currentPronunciationWritingSystems.Add(nws);
                    }
                }
                // Add any relevant EMC writing systems: match default vern at start and end with _emc.
                foreach (var nws in writingSystems)
                {
                    var icuLocale = nws.IcuLocale.ToLower();
                    if (icuLocale.IndexOf(sVern) != 0)
                    {
                        continue;
                    }

                    idx = icuLocale.LastIndexOf("_emc");
                    if (idx < sVern.Length || idx != icuLocale.Length - 4)
                    {
                        continue;
                    }

                    m_currentPronunciationWritingSystems.Add(nws);
                }
                // Add the primary vernacular writing system if nothing else fits.
                if (m_currentPronunciationWritingSystems.Count == 0)
                {
                    m_currentPronunciationWritingSystems.Add(wsVern);
                }
            });
        }
        /// <summary>
        /// If a localized lists file is available for the specified ws, load the information.
        /// Note: call this only when you are sure the WS is new to this project. It takes considerable time
        /// to run if it finds a localized list file.
        /// Our current strategy for loading localized lists is to have one file per localization.
        /// It is always LocalizedLists-XX.zip, where XX is the ICU locale for the writing system.
        /// (The zip file contains a single file, LocalizedLists-XX.xml.)
        /// So if such a file exists for this WS, we can import lists for that writing system.
        /// </summary>
        /// <param name="ws"></param>
        /// <param name="cache"></param>
        /// <param name="templateDir"></param>
        /// <param name="progress"> </param>
        public static void ImportTranslatedListsForWs(string ws, FdoCache cache, string templateDir, IProgress progress)
        {
            string path = TranslatedListsPathForWs(ws, templateDir);

            if (File.Exists(path))
            {
                var instance = new XmlTranslatedLists();
                NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(cache.ActionHandlerAccessor,
                                                                   () => instance.ImportTranslatedLists(path, cache, progress));
            }
        }
Beispiel #7
0
 private void SetParaToReparse(IStTxtPara para)
 {
     if (Cache.ActionHandlerAccessor.CurrentDepth > 0)
     {
         para.ParseIsCurrent = false;
     }
     else
     {
         NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () => para.ParseIsCurrent = false);
     }
 }
Beispiel #8
0
 public void NullLexemeForm()
 {
     NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
     {
         ILexEntry entry = m_cache.ServiceLocator.GetInstance <ILexEntryFactory>().Create(m_cache.ServiceLocator.GetInstance <IMoMorphTypeRepository>().GetObject(MoMorphTypeTags.kguidMorphStem),
                                                                                          m_cache.TsStrFactory.MakeString("form", m_cache.ServiceLocator.WritingSystems.VernacularWritingSystems.ElementAt(1).Handle), "gloss", new SandboxGenericMSA());
         entry.LexemeFormOA = null;
     });
     Assert.That(m_lexicon.Lexemes.Count(), Is.EqualTo(1));
     Assert.That(m_lexicon.Lexemes.Single().LexicalForm, Is.EqualTo(string.Empty));
 }
Beispiel #9
0
 private void ReparseParaInUowIfNeeded(IStTxtPara para)
 {
     if (Cache.ActionHandlerAccessor.CurrentDepth > 0)
     {
         ReparseParagraph(para);
     }
     else
     {
         NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () => ReparseParagraph(para));
     }
 }
Beispiel #10
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void btnOk_Click(object sender, EventArgs e)
		{
			using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
				m_cache.ServiceLocator.GetInstance<IActionHandler>()))
			{
				m_filter.ColumnInfo = string.Empty;
				m_filter.RowsOS[0].CellsOS.Clear();
				tvCategories.UpdateFilter(m_filter);

				undoHelper.RollBack = false;
			}
		}
        public void CreateOrRemoveReversalIndexConfigurationFiles_DeletethNotValidConfigs()
        {
            const string nonExtantWs = "es";
            var          analWss     = new[] { "en", "fr", "de" };

            NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(Cache.ActionHandlerAccessor,
                                                               () => Cache.LangProject.AnalysisWss = string.Join(" ", analWss));
            using (var tfProject = new TemporaryFolder("ProjForDontDeleteRealReversals"))
            {
                var projectsDir = Path.GetDirectoryName(tfProject.Path);
                var projectName = Path.GetFileName(tfProject.Path);
                var riConfigDir = Path.Combine(tfProject.Path, RIS.ConfigDir, RIS.RevIndexDir);
                FileUtils.EnsureDirectoryExists(riConfigDir);

                var crazyFilename = Path.Combine(riConfigDir, "FilenameHasNoWS" + RIS.ConfigFileExtension);
                CreateDummyConfigForWS(crazyFilename, analWss[0]);
                var nonExtantWsFilename = GetFilenameForWs(riConfigDir, nonExtantWs);
                CreateDummyConfigForWS(nonExtantWsFilename, nonExtantWs);
                var wrongWsFilename = GetFilenameForWs(riConfigDir, analWss[1]);
                CreateDummyConfigForWS(wrongWsFilename, analWss[2]);
                var allReversalsFilename = Path.Combine(riConfigDir, RIS.AllIndexesFileName + RIS.ConfigFileExtension);
                CreateDummyConfigForWS(allReversalsFilename, "");
                // A file with the expected name that the user had modified
                var          normalFilename     = GetFilenameForWs(riConfigDir, analWss[2]);
                const string normalFileModified = "2015-03-14";                 // arbitrary date in the past
                CreateDummyConfigForWS(normalFilename, analWss[2]);
                XAttribute normalFileModifiedAtt;
                var        normalFile = GetLastModifiedAttributeFromFile(normalFilename, out normalFileModifiedAtt);
                normalFileModifiedAtt.Value = normalFileModified;
                normalFile.Save(normalFilename);


                ReversalIndexServices.CreateOrRemoveReversalIndexConfigurationFiles(WSMgr, Cache, FwDirectoryFinder.DefaultConfigurations,
                                                                                    projectsDir, projectName);

                Assert.That(File.Exists(crazyFilename), crazyFilename + " should not have been deleted");
                Assert.AreEqual(analWss[0], GetWsFromFile(crazyFilename), "WS in custom-named file should not have been changed");
                Assert.That(!File.Exists(nonExtantWsFilename));
                Assert.That(File.Exists(wrongWsFilename));
                Assert.AreEqual(analWss[1], GetWsFromFile(wrongWsFilename), "WS in wrong ws-named file should have been changed (we think)");
                Assert.That(File.Exists(allReversalsFilename));
                Assert.AreEqual(string.Empty, GetWsFromFile(allReversalsFilename), "All reversals should not have a writing system");
                foreach (var ws in analWss)
                {
                    var filename = GetFilenameForWs(riConfigDir, ws);
                    Assert.That(File.Exists(filename), "No file for WS: " + ws);
                    Assert.AreEqual(ws, GetWsFromFile(filename), "Incorrect WS attribute in file");
                }
                XAttribute modifiedAtt;
                GetLastModifiedAttributeFromFile(normalFilename, out modifiedAtt);
                Assert.AreEqual(normalFileModified, modifiedAtt.Value, "File with proper name and WS should not have been modified");
            }
        }
Beispiel #12
0
 public void RemoveGloss(string language)
 {
     NonUndoableUnitOfWorkHelper.Do(m_gloss.Cache.ActionHandlerAccessor, () =>
     {
         CoreWritingSystemDefinition ws;
         if (!m_lexicon.Cache.ServiceLocator.WritingSystemManager.TryGet(language, out ws))
         {
             throw new ArgumentException("The specified language is unrecognized.", "language");
         }
         m_gloss.Form.set_String(ws.Handle, (ITsString)null);
     });
 }
 protected void CreateAndInitializeNewWindow()
 {
     m_window = new MockFwXWindow(m_application, m_configFilePath); // (MockFwXApp)
     ((MockFwXWindow)m_window).Init(Cache);                         // initializes Mediator values
     m_mediator = m_window.Mediator;
     ((MockFwXWindow)m_window).ClearReplacements();
     // delete property table settings.
     Properties.RemoveLocalAndGlobalSettings();
     ProcessPendingItems();
     m_window.LoadUI(m_configFilePath);             // actually loads UI here.
     NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, CreateTestData);
 }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private void btnOk_Click(object sender, EventArgs e)
        {
            using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
                       m_cache.ServiceLocator.GetInstance <IActionHandler>()))
            {
                m_filter.ColumnInfo = string.Empty;
                m_filter.RowsOS[0].CellsOS.Clear();
                tvCategories.UpdateFilter(m_filter);

                undoHelper.RollBack = false;
            }
        }
        void soundFieldControl_SoundDeleted(object sender, EventArgs e)
        {
            // We don't want the file name hanging aroudn once we deleted the file.
            var sc = (ShortSoundFieldControl)sender;
            int dummy;
            var ws     = WsForSoundField(sc, out dummy);
            var handle = ws == null ? 0 : ws.Handle;

            NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(m_innerView.Cache.ActionHandlerAccessor,
                                                               () => m_innerView.Cache.DomainDataByFlid.SetMultiStringAlt(m_innerView.HvoObj, m_innerView.Flid, handle,
                                                                                                                          m_innerView.Cache.TsStrFactory.MakeString("", handle)));
        }
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Does setup for all the tests
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public override void FixtureSetup()
 {
     base.FixtureSetup();
     Cache.ServiceLocator.WritingSystemManager.GetOrSet("de", out m_wsGerman);
     Cache.ServiceLocator.WritingSystemManager.GetOrSet("fr", out m_wsFrench);
     Cache.ServiceLocator.WritingSystemManager.GetOrSet("es", out m_wsSpanish);
     NonUndoableUnitOfWorkHelper.Do(m_actionHandler, () =>
     {
         ChangeDefaultAnalWs(m_wsGerman);
         Cache.LangProject.AddToCurrentAnalysisWritingSystems(m_wsSpanish);
     });
 }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Adds a new sense to the lexeme with the specified information
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public LexSense AddSenseToEntry(LexemeType type, string lexicalForm, int homograph)
        {
            LexicalProviderManager.ResetLexicalProviderTimer();
            Logger.WriteEvent("Adding new sense to lexeme '" + lexicalForm + "' from an external application");

            return(NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
            {
                string guid = string.Empty;
                switch (type)
                {
                case LexemeType.Word:
                    {
                        IWfiWordform dbWordform = GetDbWordform(lexicalForm);
                        if (dbWordform == null)
                        {
                            throw new ArgumentException("Entry in the lexicon not found for the specified information");
                        }

                        // For wordforms, our "senses" could be new meanings of an analysis for the word
                        // or it could be a brand new analysis. Because we have no idea what the user actually
                        // wanted, we just assume the worst (they want to create a new analysis for the word
                        // with a new meaning).
                        IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>().Create();
                        dbWordform.AnalysesOC.Add(dbAnalysis);
                        guid = kAnalysisPrefix + dbAnalysis.Guid;
                        break;
                    }

                default:
                    {
                        ILexEntry dbEntry = GetDbLexeme(type, lexicalForm, homograph);
                        if (dbEntry == null)
                        {
                            throw new ArgumentException("Entry in the lexicon not found for the specified information");
                        }

                        if (dbEntry.SensesOS.Count == 1 && dbEntry.SensesOS[0].Gloss.StringCount == 0)
                        {
                            // An empty sense exists (probably was created during a call to AddLexeme)
                            guid = dbEntry.SensesOS[0].Guid.ToString();
                            break;
                        }

                        ILexSense newSense = m_cache.ServiceLocator.GetInstance <ILexSenseFactory>().Create(
                            dbEntry, new SandboxGenericMSA(), null);
                        guid = newSense.Guid.ToString();
                        break;
                    }
                }
                return new LexSense(guid);
            }));
        }
Beispiel #18
0
        public LexiconSense AddSense()
        {
            LexiconSense sense       = null;
            bool         lexemeAdded = false;

            using (m_lexicon.ActivationContext.Activate())
            {
                NonUndoableUnitOfWorkHelper.Do(m_lexicon.Cache.ActionHandlerAccessor, () =>
                {
                    IWfiWordform wordform;
                    if (!m_lexicon.TryGetWordform(m_key.LexicalForm, out wordform))
                    {
                        wordform    = m_lexicon.CreateWordform(m_key.LexicalForm);
                        lexemeAdded = true;
                    }
                    // For wordforms, our "senses" could be new meanings of an analysis for the word
                    // or it could be a brand new analysis. Because we have no idea what the user actually
                    // wanted, we just assume the worst (they want to create a new analysis for the word
                    // with a new meaning).
                    IWfiAnalysis analysis = m_lexicon.Cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>().Create();
                    wordform.AnalysesOC.Add(analysis);
                    analysis.ApprovalStatusIcon = (int)Opinions.approves;                              // Assume the analysis from the external application is user approved
                    IMoStemAllomorph morph      = m_lexicon.Cache.ServiceLocator.GetInstance <IMoStemAllomorphRepository>().AllInstances().FirstOrDefault(allo =>
                    {
                        ITsString tss = allo.Form.StringOrNull(m_lexicon.DefaultVernWs);
                        if (tss != null)
                        {
                            return(tss.Text == LexicalForm.Normalize(NormalizationForm.FormD));
                        }
                        return(false);
                    });
                    if (morph != null)
                    {
                        IWfiMorphBundle mb = m_lexicon.Cache.ServiceLocator.GetInstance <IWfiMorphBundleFactory>().Create();
                        analysis.MorphBundlesOS.Add(mb);
                        mb.MorphRA = morph;
                        var entry  = morph.OwnerOfClass <ILexEntry>();
                        mb.SenseRA = entry.SensesOS[0];
                        mb.MsaRA   = entry.SensesOS[0].MorphoSyntaxAnalysisRA;
                    }
                    IWfiGloss gloss = m_lexicon.Cache.ServiceLocator.GetInstance <IWfiGlossFactory>().Create();
                    analysis.MeaningsOC.Add(gloss);
                    sense = new WfiGlossLexiconSense(m_lexicon, m_key, gloss);
                });
            }
            if (lexemeAdded)
            {
                m_lexicon.OnLexemeAdded(this);
            }
            m_lexicon.OnLexiconSenseAdded(this, sense);
            return(sense);
        }
        public void SetAndAccessDummyList()
        {
            ILexDb      lexDb  = Cache.LangProject.LexDbOA;
            ILexEntry   entry1 = null;
            ICmResource res1   = null;

            NonUndoableUnitOfWorkHelper.Do(m_actionHandler, () =>
            {
                var leFactory    = Cache.ServiceLocator.GetInstance <ILexEntryFactory>();
                entry1           = leFactory.Create();
                ILexEntry entry2 = leFactory.Create();
                res1             = Cache.ServiceLocator.GetInstance <ICmResourceFactory>().Create();
                lexDb.ResourcesOC.Add(res1);
            });

            int hvoRoot = 10578;
            ObjectListPublisher publisher = new ObjectListPublisher(Cache.MainCacheAccessor as ISilDataAccessManaged, ObjectListFlid);
            var      values   = new int[] { 23, 56, 2048 };
            Notifiee recorder = new Notifiee();

            publisher.AddNotification(recorder);
            publisher.CacheVecProp(hvoRoot, values);
            Assert.AreEqual(values.Length, publisher.get_VecSize(hvoRoot, ObjectListFlid), "override of vec size");
            //Assert.AreEqual(Cache.LangProject.Texts.Count, publisher.get_VecSize(Cache.LangProject.Hvo, LangProjectTags.kflidTexts), "base vec size");

            Assert.AreEqual(23, publisher.get_VecItem(hvoRoot, ObjectListFlid, 0), "override of vec item");
            Assert.AreEqual(res1.Hvo, publisher.get_VecItem(lexDb.Hvo, LexDbTags.kflidResources, 0), "base vec item");
            Assert.AreEqual(56, publisher.get_VecItem(hvoRoot, ObjectListFlid, 1), "override of vec item, non-zero index");

            VerifyCurrentValue(hvoRoot, publisher, values, "original value");
            Assert.AreEqual(lexDb.ResourcesOC.Count(), publisher.VecProp(lexDb.Hvo, LexDbTags.kflidResources).Length, "base VecProp");

            recorder.CheckChanges(new ChangeInformationTest[] { new ChangeInformationTest(hvoRoot, ObjectListFlid, 0, values.Length, 0) },
                                  "expected PropChanged from caching HVOs");
            publisher.RemoveNotification(recorder);

            recorder = new Notifiee();
            publisher.AddNotification(recorder);
            publisher.Replace(hvoRoot, 1, new int[] { 97, 98 }, 0);
            VerifyCurrentValue(hvoRoot, publisher, new int[] { 23, 97, 98, 56, 2048 }, "after inserting 97, 98");
            recorder.CheckChanges(new ChangeInformationTest[] { new ChangeInformationTest(hvoRoot, ObjectListFlid, 1, 2, 0) },
                                  "expected PropChanged from caching HVOs");
            publisher.RemoveNotification(recorder);

            recorder = new Notifiee();
            publisher.AddNotification(recorder);
            publisher.Replace(hvoRoot, 1, new int[0], 2);
            VerifyCurrentValue(hvoRoot, publisher, new int[] { 23, 56, 2048 }, "after deleting 97, 98");
            recorder.CheckChanges(new ChangeInformationTest[] { new ChangeInformationTest(hvoRoot, ObjectListFlid, 1, 0, 2) },
                                  "expected PropChanged from caching HVOs");
            publisher.RemoveNotification(recorder);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// If a test overrides this, it should call this base implementation.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public override void FixtureSetup()
        {
            base.FixtureSetup();

            var servLoc = Cache.ServiceLocator;

            NonUndoableUnitOfWorkHelper.Do(m_actionHandler, () =>
            {
                Cache.LanguageProject.PeopleOA = servLoc.GetInstance <ICmPossibilityListFactory>().Create();
                Cache.LanguageProject.PeopleOA.PossibilitiesOS.Add(servLoc.GetInstance <ICmPersonFactory>().Create());
            });
            m_possListFactory = servLoc.GetInstance <ICmPossibilityListFactory>();
        }
Beispiel #21
0
        public void kcptTimeTests()
        {
            var servLoc = Cache.ServiceLocator;
            var lp      = servLoc.GetInstance <ILangProjectRepository>().AllInstances().First();

            using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
            {
                lp.DateCreated      = DateTime.Now;
                undoHelper.RollBack = false;
            }
            CheckChanges(1, 0, lp.Hvo, CmProjectTags.kflidDateCreated, 0, 0, 0);
            ClearChanges();
        }
Beispiel #22
0
        public override void TestTearDown()
        {
            base.TestTearDown();
            var repo = Cache.ServiceLocator.GetInstance <ITextRepository>();

            NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () =>
            {
                foreach (var text in repo.AllInstances())
                {
                    text.Delete();
                }
            });
        }
Beispiel #23
0
        public void Process()
        {
            var cache = (FdoCache)Dialog.Mediator.PropertyTable.GetValue("cache");

            NonUndoableUnitOfWorkHelper.DoSomehow(cache.ActionHandlerAccessor, () =>
            {
                var fixedGuids = ReplacePOSGuidsWithGoldEticGuids(cache);
                var caption    = fixedGuids ? LexEdStrings.GoldEticGuidFixer_Guids_changed_Title : LexEdStrings.GoldEticGuidFixer_NoChangeTitle;
                var content    = fixedGuids ? LexEdStrings.GoldEticGuidFixer_GuidsChangedContent
                                                                                                 : LexEdStrings.GoldEticGuidFixer_NoChangeContent;
                MessageBox.Show(Dialog, content, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
            });
        }
Beispiel #24
0
        public static ICmPossibility AddPublicationType(string name, LcmCache cache)
        {
            Debug.Assert(cache.LangProject.LexDbOA.PublicationTypesOA != null);

            var item = cache.ServiceLocator.GetInstance <ICmPossibilityFactory>().Create();

            NonUndoableUnitOfWorkHelper.DoSomehow(cache.ActionHandlerAccessor, () =>
            {
                cache.LangProject.LexDbOA.PublicationTypesOA.PossibilitiesOS.Add(item);
                item.Name.set_String(cache.DefaultAnalWs, name);
            });
            return(item);
        }
Beispiel #25
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the ChooseScriptureDialog class.
 /// WARNING: this constructor is called by reflection, at least in the Interlinear
 /// Text DLL. If you change its parameters be SURE to find and fix those callers also.
 /// </summary>
 /// <param name="cache">The cache.</param>
 /// <param name="objList">A list of texts and books to check as an array of hvos</param>
 /// <param name="helpTopicProvider">The help topic provider.</param>
 /// <param name="importer">The Paratext book importer.</param>
 /// ------------------------------------------------------------------------------------
 public FilterTextsDialogTE(FdoCache cache, IStText[] objList,
                            IHelpTopicProvider helpTopicProvider, IBookImporter importer)
     : base(cache, objList, helpTopicProvider)
 {
     m_bookImporter = importer;
     using (var progressDlg = new ProgressDialogWithTask(null, cache.ThreadHelper))
     {
         NonUndoableUnitOfWorkHelper.Do(cache.ActionHandlerAccessor, () =>
                                        TeScrInitializer.EnsureMinimalScriptureInitialization(cache, progressDlg,
                                                                                              (IHelpTopicProvider)DynamicLoader.CreateObject(DirectoryFinder.TeDll,
                                                                                                                                             "SIL.FieldWorks.TE.TeHelpTopicProvider")));
     }
 }
        /// <summary>
        /// This class creates text, it must delete it here when UNDO is commanded
        /// so it can update InterestingTexts.
        /// </summary>

/*		public override void PropChanged(int hvo, int tag, int ivMin, int cvIns, int cvDel)
 *              {
 *                      if (cvDel != 1)
 *                              return;
 *                      SaveOnChangeRecord();
 *                      SuppressSaveOnChangeRecord = true;
 *                      try
 *                      {
 *                              m_list.DeleteCurrentObject();
 *                      }
 *                      finally
 *                      {
 *                              SuppressSaveOnChangeRecord = false;
 *                      }
 *                      GetInterestingTextList().UpdateInterestingTexts();
 *              } */

        #region IBookImporter Members
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Imports the specified book.
        /// </summary>
        /// <param name="bookNum">The canonical book number.</param>
        /// <param name="owningForm">Form that can be used as the owner of progress dialogs and
        /// message boxes.</param>
        /// <param name="importBt">True to import only the back translation, false to import
        /// only the main translation</param>
        /// <returns>
        /// The ScrBook created to hold the imported data
        /// </returns>
        /// ------------------------------------------------------------------------------------
        public IScrBook Import(int bookNum, Form owningForm, bool importBt)
        {
            IScripture scr = Cache.LangProject.TranslatedScriptureOA;
            bool       haveSomethingToImport = NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () =>
            {
                IScrImportSet importSettings   = scr.FindOrCreateDefaultImportSettings(TypeOfImport.Paratext6);
                importSettings.StyleSheet      = ScriptureStylesheet;
                IScrText paratextProj          = ParatextHelper.GetAssociatedProject(Cache.ProjectId);
                importSettings.ParatextScrProj = paratextProj.Name;
                importSettings.StartRef        = new BCVRef(bookNum, 0, 0);
                int chapter           = paratextProj.Versification.LastChapter(bookNum);
                importSettings.EndRef = new BCVRef(bookNum, chapter, paratextProj.Versification.LastVerse(bookNum, chapter));
                if (!importBt)
                {
                    importSettings.ImportTranslation     = true;
                    importSettings.ImportBackTranslation = false;
                }
                else
                {
                    List <IScrText> btProjects = ParatextHelper.GetBtsForProject(paratextProj).ToList();
                    if (btProjects.Count > 0 && (string.IsNullOrEmpty(importSettings.ParatextBTProj) ||
                                                 !btProjects.Any(st => st.Name == importSettings.ParatextBTProj)))
                    {
                        importSettings.ParatextBTProj = btProjects[0].Name;
                    }
                    if (string.IsNullOrEmpty(importSettings.ParatextBTProj))
                    {
                        return(false);
                    }
                    importSettings.ImportTranslation     = false;
                    importSettings.ImportBackTranslation = true;
                }
                ParatextHelper.LoadProjectMappings(importSettings);
                ScrMappingList importMap     = importSettings.GetMappingListForDomain(ImportDomain.Main);
                ImportMappingInfo figureInfo = importMap[@"\fig"];
                if (figureInfo != null)
                {
                    figureInfo.IsExcluded = true;
                }
                importSettings.SaveSettings();
                return(true);
            });

            if (haveSomethingToImport && ReflectionHelper.GetBoolResult(ReflectionHelper.GetType("TeImportExport.dll",
                                                                                                 "SIL.FieldWorks.TE.TeImportManager"), "ImportParatext", owningForm, ScriptureStylesheet,
                                                                        (FwApp)m_mediator.PropertyTable.GetValue("App")))
            {
                return(scr.FindBook(bookNum));
            }
            return(null);
        }
        internal static void ReferenceBreaker(FdoCache cache, out int m_count, out int m_circular, out string m_report)
        {
            m_count = cache.ServiceLocator.GetInstance <ILexEntryRefRepository>().AllInstances().Count(r => r.RefType == LexEntryRefTags.krtComplexForm);
            var list        = cache.ServiceLocator.GetInstance <ILexEntryRefRepository>().AllInstances().Where(r => r.RefType == LexEntryRefTags.krtComplexForm);
            var bldr        = new StringBuilder();
            var circularRef = m_circular = 0;

            NonUndoableUnitOfWorkHelper.Do(cache.ServiceLocator.GetInstance <IActionHandler>(), () =>
            {
                foreach (var ler in list)
                {
                    if (!ler.IsValidObject)
                    {
                        continue;                                       // we can remove LexEntryRef objects during processing, making them invalid.
                    }
                    m_refsProcessed.Clear();
                    m_entriesEncountered.Clear();
                    if (CheckForCircularRef(ler))
                    {
                                                        #if DEBUG
                        Debug.Assert(m_refsProcessed.Count > 1);
                        ShowFullProcessedRefs();
                                                        #endif
                        ++circularRef;
                        var lim    = m_refsProcessed.Count - 1;
                        var entry1 = m_refsProcessed[0].OwningEntry;
                        var entry2 = m_refsProcessed[lim].OwningEntry;
                        // Assume that the entry with the longer headword is probably the actual complex form, so remove that one
                        // from the references owned by the other entry.  If this assumption is somehow wrong, at least the user
                        // is going to be notified of what happened.
                        if (entry1.HeadWord.Text.Length > entry2.HeadWord.Text.Length)
                        {
                            RemoveEntryFromLexEntryRef(m_refsProcessed[lim], entry1, bldr);
                        }
                        else
                        {
                            RemoveEntryFromLexEntryRef(m_refsProcessed[0], entry2, bldr);
                        }
                        bldr.AppendLine();
                    }
                }
            });
            if (bldr.Length > 0)
            {
                bldr.Insert(0, Environment.NewLine);
            }
            m_circular = circularRef;
            bldr.Insert(0, String.Format(Strings.ksFoundNCircularReferences, m_circular, m_count));
            m_report = bldr.ToString();
        }
        void soundFieldControl_BeforeStartingToRecord(object sender, EventArgs e)
        {
            var    sc = (ShortSoundFieldControl)sender;
            string path;
            string filename = CreateNewSoundFilename(out path);

            sc.Path = path;
            int dummy;
            var ws = WsForSoundField(sc, out dummy);

            NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(m_innerView.Cache.ActionHandlerAccessor,
                                                               () => m_innerView.Cache.DomainDataByFlid.SetMultiStringAlt(m_innerView.HvoObj, m_innerView.Flid,
                                                                                                                          ws.Handle, m_innerView.Cache.TsStrFactory.MakeString(filename, ws.Handle)));
        }
        ///-------------------------------------------------------------------------------
        /// <summary>
        /// When the Source button is clicked, display the import wizard.
        /// </summary>
        ///-------------------------------------------------------------------------------
        private void btnSource_Click(object sender, System.EventArgs e)
        {
            using (ImportWizard importWizard = new ImportWizard(m_scr.Cache.ProjectId.Name,
                                                                m_scr, m_StyleSheet, m_helpTopicProvider, m_app))
            {
                using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(ActionHandler))
                {
                    if (importWizard.ShowDialog() == DialogResult.Cancel)
                    {
                        // Ditch any in-memory changes made to the settings. Reload from the DB.
                        m_importSettings.RevertToSaved();
                    }
                    else
                    {
                        undoHelper.RollBack = false;
                    }
                }

                // If there are no files after showing the wizard, close the import dialog
                if (InitBookNameList() == 0)
                {
                    MessageBox.Show(this, DlgResources.ResourceString("kstidImportFilesUnavailable"),
                                    m_app.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Close();
                    return;
                }

                // The default set of settings may have changed.
                m_importSettings = m_scr.DefaultImportSettings;

                // Update the file ranges for import because they may have changed.
                InitializeStartAndEndRefControls();

                // Update the passage controls to reflect the new range of files available
                // Only make changes that do not expand the available range of books since a
                // range may have been specified before the wizard was run that we do not
                // want to overwrite
                if (!scrPsgFrom.IsReferenceValid(scrPsgFrom.ScReference))
                {
                    SetStartRefToFirstImportableBook();
                }

                if (!scrPsgTo.IsReferenceValid(scrPsgTo.ScReference))
                {
                    SetEndRefToLastImportableBook();
                }
            }
            btnOK.Focus();
        }
        void soundFieldControl_SoundRecorded(object sender, EventArgs e)
        {
            var sc = (ShortSoundFieldControl)sender;
            int dummy;
            var ws          = WsForSoundField(sc, out dummy);
            var filenameNew = Path.GetFileName(sc.Path);
            var filenameOld = m_innerView.Cache.DomainDataByFlid.get_MultiStringAlt(m_innerView.HvoObj, m_innerView.Flid, ws.Handle).Text ?? "";

            if (filenameNew != filenameOld)
            {
                NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(m_innerView.Cache.ActionHandlerAccessor,
                                                                   () => m_innerView.Cache.DomainDataByFlid.SetMultiStringAlt(m_innerView.HvoObj, m_innerView.Flid,
                                                                                                                              ws.Handle, m_innerView.Cache.TsStrFactory.MakeString(filenameNew, ws.Handle)));
            }
        }
 /// <summary>
 /// Get the language project's list of pronunciation writing systems into sync with the supplied list.
 /// </summary>
 private void UpdatePronunciationWritingSystems(IEnumerable <IWritingSystem> newValues)
 {
     if (newValues.Count() != m_cache.ServiceLocator.WritingSystems.CurrentPronunciationWritingSystems.Count ||
         !m_cache.ServiceLocator.WritingSystems.CurrentPronunciationWritingSystems.SequenceEqual(newValues))
     {
         NonUndoableUnitOfWorkHelper.Do(m_cache.ServiceLocator.GetInstance <IActionHandler>(), () =>
         {
             m_cache.ServiceLocator.WritingSystems.CurrentPronunciationWritingSystems.Clear();
             foreach (IWritingSystem ws in newValues)
             {
                 m_cache.ServiceLocator.WritingSystems.CurrentPronunciationWritingSystems.Add(ws);
             }
         });
     }
 }
		/// <summary>
		/// Create a new Language Project.
		/// </summary>
		internal static void BootstrapNewSystem(IServiceLocator servLoc)
		{
			using (var nonUndoableUOW = new NonUndoableUnitOfWorkHelper(servLoc.GetInstance<IActionHandler>()))
			{
				var lp = servLoc.GetInstance<ILangProjectFactory>().Create();

				BootstrapWritingSystems(lp);

				// Add some required objects.
				SetupVariousPossibilityLists(lp);

				lp.MsFeatureSystemOA = servLoc.GetInstance<IFsFeatureSystemFactory>().Create();
				lp.PhFeatureSystemOA = servLoc.GetInstance<IFsFeatureSystemFactory>().Create();
				lp.PhonologicalDataOA = servLoc.GetInstance<IPhPhonDataFactory>().Create();
				lp.MorphologicalDataOA = servLoc.GetInstance<IMoMorphDataFactory>().Create();

				// This should possibly be in SetupVariousPossibilityLists, if we did that after making the owner.
				lp.MorphologicalDataOA.ProdRestrictOA = servLoc.GetInstance<ICmPossibilityListFactory>().Create();
				lp.MorphologicalDataOA.ProdRestrictOA.ItemClsid = CmPossibilityTags.kClassId;

				lp.PhonologicalDataOA.PhonRuleFeatsOA = servLoc.GetInstance<ICmPossibilityListFactory>().Create();
				lp.PhonologicalDataOA.PhonRuleFeatsOA.ItemClsid = PhPhonRuleFeatTags.kClassId;

				lp.ResearchNotebookOA = servLoc.GetInstance<IRnResearchNbkFactory>().Create();

				InitializeLexDb(lp);

				// Add all fixed Guid objects here.
				SetupAnnotationDefns(lp);
				SetupAgents(lp);

				// Translation Types Possibility List and KeyTerms List
				SetupTranslationTypesAndKeyTermsList(lp);

				// If there are any exceptions before this point,
				// then the whole mess gets rolled back.
				nonUndoableUOW.RollBack = false;
			}
		}
Beispiel #33
0
		public void kcptBinaryTests()
		{
			IUserConfigAcctFactory acctFactory = Cache.ServiceLocator.GetInstance<IUserConfigAcctFactory>();
			IUserConfigAcct acct;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				acct = acctFactory.Create();
				Cache.LanguageProject.UserAccountsOC.Add(acct);
				undoHelper.RollBack = false;
			}
			CheckChanges(1, 0, Cache.LanguageProject.Hvo, LangProjectTags.kflidUserAccounts, 0, 1, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				acct.Sid = new byte[] { 1, 2, 3 };
				undoHelper.RollBack = false;
			}
			// Changing a prop on an unowned object does make one PC.
			CheckChanges(1, 0, acct.Hvo, UserConfigAcctTags.kflidSid, 0, 0, 0);
			ClearChanges();
		}
Beispiel #34
0
		public void UnknownTests()
		{
			var lp = Cache.LanguageProject;
			var styleFactory = Cache.ServiceLocator.GetInstance<IStStyleFactory>();
			IStStyle style;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				style = styleFactory.Create();
				lp.StylesOC.Add(style);
				undoHelper.RollBack = false;
			}
			// Should be one PC.
			CheckChanges(1, 0, lp.Hvo, LangProjectTags.kflidStyles, 0, 1, 0);
			ClearChanges();

			var userWs = Cache.WritingSystemFactory.UserWs;
			var bldr = TsPropsBldrClass.Create();
			bldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, "Arial");
			bldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, userWs);
			var tpp = bldr.GetTextProps();
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				style.Rules = tpp;
				undoHelper.RollBack = false;
			}
			// Should be one PC.
			CheckChanges(1, 0, style.Hvo, StStyleTags.kflidRules, 0, 0, 0);
			ClearChanges();
		}
Beispiel #35
0
		public void kcptStringTests()
		{
			ILexEntry le;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				le = Cache.ServiceLocator.GetInstance<ILexEntryFactory>().Create();
				undoHelper.RollBack = false;
			}
			// Skip the main checking on the vector prop.
			CheckChanges(1, -1, 0, 0, 0, 0, 0);
			ClearChanges();

			var tsf = Cache.TsStrFactory;
			var userWs = Cache.WritingSystemFactory.UserWs;
			ITsString importResidue;
			int originalImportResidueLength = 0;
			UndoableUnitOfWorkHelper.Do("Undo stuff", "Redo stuff", m_actionHandler, () =>
			{
				importResidue = tsf.MakeString("import residue", userWs);
				originalImportResidueLength = importResidue.Length;
				le.ImportResidue = importResidue;
			});
			// Null to new value should have cvIns be the new length and cvDel be 0.
			CheckChanges(1, 0, le.Hvo, LexEntryTags.kflidImportResidue, 0, originalImportResidueLength, 0);
			ClearChanges();
			m_actionHandler.Undo();
			CheckChanges(1, 0, le.Hvo, LexEntryTags.kflidImportResidue, 0, 0, originalImportResidueLength);
			m_actionHandler.Redo();
			ClearChanges();

			int newImportResidueLength = 0;
			UndoableUnitOfWorkHelper.Do("Undo stuff", "Redo stuff", m_actionHandler, () =>
			{
				importResidue = tsf.MakeString("new import residue", userWs);
				newImportResidueLength = importResidue.Length;
				le.ImportResidue = importResidue;
			});
			// Old value to new value should have cvIns be the new length and cvDel be old value length.
			CheckChanges(1, 0, le.Hvo, LexEntryTags.kflidImportResidue, 0, newImportResidueLength, originalImportResidueLength);
			ClearChanges();
			m_actionHandler.Undo();
			CheckChanges(1, 0, le.Hvo, LexEntryTags.kflidImportResidue, 0, originalImportResidueLength, newImportResidueLength);
			m_actionHandler.Redo();
			ClearChanges();

			UndoableUnitOfWorkHelper.Do("Undo stuff", "Redo stuff", m_actionHandler, () => le.ImportResidue = null);
			// Old value to null should have cvIns be 0 and cvDel be old value length.
			CheckChanges(1, 0, le.Hvo, LexEntryTags.kflidImportResidue, 0, 0, newImportResidueLength);
			ClearChanges();
			m_actionHandler.Undo();
			CheckChanges(1, 0, le.Hvo, LexEntryTags.kflidImportResidue, 0, newImportResidueLength, 0);
			m_actionHandler.Redo();
			ClearChanges();
		}
Beispiel #36
0
		public void MultiUnicodeTests()
		{
			var tsf = Cache.TsStrFactory;
			var englishWsHvo = Cache.WritingSystemFactory.GetWsFromStr("en");
			var spanishWsHvo = Cache.WritingSystemFactory.GetWsFromStr("es");
			var lp = Cache.LanguageProject;

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				// Description is MultiString
				// Set LP's Description.
				lp.Description.set_String(
					englishWsHvo,
					tsf.MakeString("Stateful FDO Test Language Project: Desc", englishWsHvo));
				lp.Description.set_String(
					spanishWsHvo,
					tsf.MakeString("Proyecto de prueba: FDO: desc", spanishWsHvo));

				undoHelper.RollBack = false;
			}
			// Should be two PCs on LP.
			CheckChanges(2, 0, lp.Hvo, CmProjectTags.kflidDescription, englishWsHvo, 0, 0);
			CheckChanges(2, 1, lp.Hvo, CmProjectTags.kflidDescription, spanishWsHvo, 0, 0);
			ClearChanges();
		}
Beispiel #37
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes the specified application and creates a new main window for it. Also
		/// does application-specific cache initialization.
		/// </summary>
		/// <param name="app">The application</param>
		/// <param name="progressDlg">The progress dialog.</param>
		/// <returns>True if the application was started successfully, false otherwise</returns>
		/// ------------------------------------------------------------------------------------
		private static bool InitializeApp(FwApp app, IThreadedProgress progressDlg)
		{
			using (new DataUpdateMonitor(null, "Application Initialization"))
				app.DoApplicationInitialization(progressDlg);
			using (new DataUpdateMonitor(null, "Loading Application Settings"))
				app.LoadSettings();

			using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
				s_cache.ServiceLocator.GetInstance<IActionHandler>()))
			using (new DataUpdateMonitor(null, "Application Cache Initialization"))
			{
				try
				{
					if (!app.InitCacheForApp(progressDlg))
						throw new StartupException(Properties.Resources.kstidCacheInitFailure);
				}
				catch (Exception e)
				{
					if (e is StartupException)
						throw;
					throw new StartupException(Properties.Resources.kstidCacheInitFailure, e, true);
				}
				undoHelper.RollBack = false;
			}

			if (s_cache.ServiceLocator.GetInstance<IUndoStackManager>().HasUnsavedChanges)
			{
				if (progressDlg != null)
				{
					progressDlg.Message = String.Format(Properties.Resources.kstidSaving, s_cache.ProjectId.UiName);
					progressDlg.IsIndeterminate = true;
				}
				s_cache.ServiceLocator.GetInstance<IUndoStackManager>().Save();
				if (progressDlg != null)
					progressDlg.IsIndeterminate = false;
			}

			return CreateAndInitNewMainWindow(app, true, null, false);
		}
		public void KeyTermInit_DashDescription()
		{
			BiblicalTermsList terms = new BiblicalTermsList();
			terms.Version = Guid.NewGuid();
			terms.KeyTerms = new List<Term>();
			terms.KeyTerms.Add(new Term(56, "FA", "\u1F00\u03B5\u03C4\u1F79\u03C2", "Greek",
				"eagle; vulture", null, null,
				4002402809, 4201703717, 6600400728, 6600801306, 6601201409));

			List<BiblicalTermsLocalization> localizations = new List<BiblicalTermsLocalization>(1);
			BiblicalTermsLocalization loc = new BiblicalTermsLocalization(1);
			loc.WritingSystemHvo = m_wsEn;
			loc.Categories.Add(new CategoryLocalization("FA", "Fauna"));
			loc.Terms.Add(new TermLocalization(56, "eagle; vulture", "\t-"));
			localizations.Add(loc);

			ICmPossibilityList chkTermsList = Cache.ServiceLocator.GetInstance<ICmPossibilityListFactory>().Create();
			m_lp.CheckListsOC.Add(chkTermsList);

			// Load the term
			m_actionHandler.EndUndoTask();
			try
			{
				using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
				{
					DummyTeKeyTermsInit.CallLoadKeyTerms(chkTermsList, terms, localizations);

					undoHelper.RollBack = false;
				}
			}
			finally
			{
				m_actionHandler.BeginUndoTask("bla", "bla");
			}

			int wsGreek = m_wsf.GetWsFromStr("grc");

			// Make sure there is one category (possibility)
			Assert.AreEqual(1, chkTermsList.PossibilitiesOS.Count);
			ICmPossibility faCategory = chkTermsList.PossibilitiesOS[0];
			Assert.AreEqual("FA", faCategory.Abbreviation.get_String(m_wsEn).Text);

			// Make sure there is one entry in the Fauna category
			Assert.AreEqual(1, faCategory.SubPossibilitiesOS.Count);

			// Look at the contents of the ChkTerm
			IChkTerm keyterm = (IChkTerm)faCategory.SubPossibilitiesOS[0];
			Assert.AreEqual(56, keyterm.TermId);
			Assert.AreEqual("\u1F00\u03B5\u03C4\u1F79\u03C2".Normalize(NormalizationForm.FormD), keyterm.Name.get_String(wsGreek).Text);
			Assert.AreEqual("eagle", keyterm.Name.get_String(m_wsEn).Text);
			Assert.IsNull(keyterm.Description.get_String(m_wsEn).Text);
			Assert.AreEqual("vulture", keyterm.SeeAlso.get_String(m_wsEn).Text);
			Assert.AreEqual(0, keyterm.RenderingsOC.Count);

			// There should be 5 references for this key term
			Assert.AreEqual(5, keyterm.OccurrencesOS.Count);

			IChkRef reference = keyterm.OccurrencesOS[0];
			Assert.AreEqual(40024028, reference.Ref);
			Assert.AreEqual("\u1F00\u03B5\u03C4\u1F79\u03C2".Normalize(NormalizationForm.FormD), reference.KeyWord.Text);
			Assert.AreEqual(9, reference.Location);

			reference = keyterm.OccurrencesOS[1];
			Assert.AreEqual(42017037, reference.Ref);
			Assert.AreEqual("\u1F00\u03B5\u03C4\u1F79\u03C2".Normalize(NormalizationForm.FormD), reference.KeyWord.Text);
			Assert.AreEqual(17, reference.Location);

			reference = keyterm.OccurrencesOS[2];
			Assert.AreEqual(66004007, reference.Ref);
			Assert.AreEqual("\u1F00\u03B5\u03C4\u1F79\u03C2".Normalize(NormalizationForm.FormD), reference.KeyWord.Text);
			Assert.AreEqual(28, reference.Location);

			reference = keyterm.OccurrencesOS[3];
			Assert.AreEqual(66008013, reference.Ref);
			Assert.AreEqual("\u1F00\u03B5\u03C4\u1F79\u03C2".Normalize(NormalizationForm.FormD), reference.KeyWord.Text);
			Assert.AreEqual(6, reference.Location);

			reference = keyterm.OccurrencesOS[4];
			Assert.AreEqual(66012014, reference.Ref);
			Assert.AreEqual("\u1F00\u03B5\u03C4\u1F79\u03C2".Normalize(NormalizationForm.FormD), reference.KeyWord.Text);
			Assert.AreEqual(9, reference.Location);

			bool fFoundResource = false;
			foreach (ICmResource resource in m_lp.TranslatedScriptureOA.ResourcesOC)
			{
				if (resource.Name == "BiblicalTerms")
				{
					Assert.AreEqual(terms.Version, resource.Version);
					fFoundResource = true;
				}
			}
			Assert.IsTrue(fFoundResource);
		}
Beispiel #39
0
		public void kcptIntegerTests()
		{
			var servLoc = Cache.ServiceLocator;
			var lp = servLoc.GetInstance<ILangProjectRepository>().AllInstances().First();
			ICmPossibilityList peopleList;
			ICmPerson firstPerson;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				lp.PeopleOA = servLoc.GetInstance<ICmPossibilityListFactory>().Create();
				peopleList = lp.PeopleOA;
				firstPerson = servLoc.GetInstance<ICmPersonFactory>().Create();
				peopleList.PossibilitiesOS.Add(firstPerson);
				undoHelper.RollBack = false;
			}
			// Two new objects (nested) should only make one PC on the top owner.
			CheckChanges(1, 0, lp.Hvo, LangProjectTags.kflidPeople, 0, 1, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				peopleList.Depth += 1;
				undoHelper.RollBack = false;
			}
			CheckChanges(1, 0, peopleList.Hvo, CmPossibilityListTags.kflidDepth, 0, 0, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				// Get rid of the list.
				lp.PeopleOA = null;
				undoHelper.RollBack = false;
			}
			ClearChanges();
		}
Beispiel #40
0
		public void kcptGuidTests()
		{
			ICmPossibilityListFactory possFactory = Cache.ServiceLocator.GetInstance<ICmPossibilityListFactory>();
			ICmPossibilityList possList;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				possList = possFactory.Create();
				Cache.LanguageProject.TimeOfDayOA = possList;
				undoHelper.RollBack = false;
			}
			CheckChanges(1, 0, Cache.LanguageProject.Hvo, LangProjectTags.kflidTimeOfDay, 0, 1, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				possList.ListVersion = Guid.NewGuid();
				undoHelper.RollBack = false;
			}
			// Changing a prop on an unowned object does make one PC.
			CheckChanges(1, 0, possList.Hvo, CmPossibilityListTags.kflidListVersion, 0, 0, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				possList.ListVersion = Guid.NewGuid();
				possList.ListVersion = Guid.NewGuid();
				undoHelper.RollBack = false;
			}
			// Changing a prop twice in one UOW only makes one PC for the property.
			CheckChanges(1, 0, possList.Hvo, CmPossibilityListTags.kflidListVersion, 0, 0, 0);
			ClearChanges();

			// TODO: Delete unowned uv, as that should also not produce a PC.
		}
Beispiel #41
0
		public void kcptBooleanTests()
		{
			var servLoc = Cache.ServiceLocator;
			var lp = servLoc.GetInstance<ILangProjectRepository>().AllInstances().First();
			ICmPossibilityList peopleList;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				lp.PeopleOA = servLoc.GetInstance<ICmPossibilityListFactory>().Create();
				peopleList = lp.PeopleOA;
				undoHelper.RollBack = false;
			}
			CheckChanges(1, -1, 0, 0, 0, 0, 0);
			ClearChanges();

			using (var undoHelper = new UndoableUnitOfWorkHelper(m_actionHandler, "set boolean"))
			{
				peopleList.IsVernacular = !peopleList.IsVernacular;
				undoHelper.RollBack = false;
			}
			CheckChanges(1, 0, peopleList.Hvo, CmPossibilityListTags.kflidIsVernacular, 0, 0, 0);
			ClearChanges();
			// Check Undo/Redo to ensure they fire PropChanges.
			m_actionHandler.Undo();
			CheckChanges(1, 0, peopleList.Hvo, CmPossibilityListTags.kflidIsVernacular, 0, 0, 0);
			ClearChanges();
			m_actionHandler.Redo();
			CheckChanges(1, 0, peopleList.Hvo, CmPossibilityListTags.kflidIsVernacular, 0, 0, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				// Get rid of the list.
				lp.PeopleOA = null;
				undoHelper.RollBack = false;
			}
			ClearChanges();
		}
Beispiel #42
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get the settings for Import, either from database or from wizard
		/// </summary>
		/// <returns>Import settings, or <c>null</c> if user canceled dialog.</returns>
		/// ------------------------------------------------------------------------------------
		protected IScrImportSet GetImportSettings()
		{
			ILangProject proj = m_cache.LangProject;
			IScripture scr = proj.TranslatedScriptureOA;
			IScrImportSet importSettings = null;
			NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
			{
				importSettings =
					scr.FindOrCreateDefaultImportSettings(TypeOfImport.Unknown);
			});
			importSettings.StyleSheet = m_styleSheet;

			importSettings.OverlappingFileResolver = new ConfirmOverlappingFileReplaceDialog(m_helpTopicProvider);
			if (!importSettings.BasicSettingsExist)
			{
				using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
					m_cache.ServiceLocator.GetInstance<IActionHandler>()))
				{
					using (ImportWizard importWizard = new ImportWizard(m_cache.ProjectId.Name,
						scr, m_styleSheet, m_helpTopicProvider, m_app))
					{
						if (importWizard.ShowDialog() == DialogResult.Cancel)
							return null;
						// Scripture reference range may have changed
						ImportDialog.ClearDialogReferences();
						importSettings = scr.DefaultImportSettings;
					}
					undoHelper.RollBack = false;
				}
			}
			else
			{
				StringCollection sInvalidFiles;
				bool fCompletedWizard = false;
				while (!importSettings.ImportProjectIsAccessible(out sInvalidFiles))
				{
					// Display the "Project Not Found" message box
					using (ScrImportSetMessage dlg = new ScrImportSetMessage())
					{
						string[] files = new string[sInvalidFiles.Count];
						sInvalidFiles.CopyTo(files, 0);
						dlg.InvalidFiles = files;
						dlg.HelpURL = m_helpTopicProvider.HelpFile;
						dlg.HelpTopic = "/Beginning_Tasks/Import_Standard_Format/Project_Files_Unavailable.htm";
						dlg.DisplaySetupOption = true;
						switch(dlg.ShowDialog())
						{
							case DialogResult.OK: // Setup...
							{
								using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
									m_cache.ServiceLocator.GetInstance<IActionHandler>()))
								{
									using (ImportWizard importWizard = new ImportWizard(
										m_cache.ProjectId.Name, scr, m_styleSheet, m_helpTopicProvider, m_app))
									{
										if (importWizard.ShowDialog() == DialogResult.Cancel)
											return null;
										// Scripture reference range may have changed
										ImportDialog.ClearDialogReferences();
										importSettings = scr.DefaultImportSettings;
										fCompletedWizard = true;
									}
									undoHelper.RollBack = false;
								}
								break;
							}
							case DialogResult.Cancel:
								return null;
							case DialogResult.Retry:
								// Loop around until user gets tired.
								break;
						}
					}
				}
				if (!fCompletedWizard)
				{
					if (ParatextProjHasUnmappedMarkers(importSettings))
					{
						// TODO: Show message box and then bring up import wizard
					}
				}
			}

			return importSettings;
		}
Beispiel #43
0
		/// <summary>
		/// Here's where the rubber meets the road.  We have the settings, let's do the import!
		/// </summary>
		private object ImportStdFmtFile(IThreadedProgress progressDlg, object[] parameters)
		{
			int lineNumber = 0;
			using (var uowHelper = new NonUndoableUnitOfWorkHelper(m_cache.ActionHandlerAccessor))
			{
				try
				{
					m_dtStart = DateTime.Now;
					FixSettingsForThisDatabase();
					int cLines = m_SfmFile.Lines.Count;
					progressDlg.Title = String.Format(LexTextControls.ksImportingFrom0, Path.GetFileName(m_sSfmDataFile));
					progressDlg.StepSize = 1;
					int cExistingRecords = m_cache.LangProject.ResearchNotebookOA.RecordsOC.Count;
					if (m_rbReplaceAllEntries.Checked && cExistingRecords > 0)
					{
						progressDlg.Minimum = 0;
						progressDlg.Maximum = cLines + 50;
						progressDlg.Message = LexTextControls.ksDeletingExistingRecords;
						// This is rather drastic, but it's what the user asked for!
						// REVIEW: Should we ask for confirmation before doing this?
						m_cRecordsDeleted = cExistingRecords;
						m_cache.LangProject.ResearchNotebookOA.RecordsOC.Clear();
						progressDlg.Step(50);
					}
					else
					{
						m_cRecordsDeleted = 0;
						progressDlg.Minimum = 0;
						progressDlg.Maximum = cLines;
					}
					progressDlg.Message = LexTextControls.ksImportingNewRecords;
					IRnGenericRec recPrev = null;
					IRnGenericRec rec = null;
					IRnGenericRecFactory factRec = m_cache.ServiceLocator.GetInstance<IRnGenericRecFactory>();
					IRnGenericRecRepository repoRec = m_cache.ServiceLocator.GetInstance<IRnGenericRecRepository>();
					ICmPossibilityRepository repoPoss = m_cache.ServiceLocator.GetInstance<ICmPossibilityRepository>();
					ICmPossibility defaultType = repoPoss.GetObject(RnResearchNbkTags.kguidRecObservation);
					for (int i = 0; i < cLines; ++i)
					{
						progressDlg.Step(1);
						if (progressDlg.Canceled)
						{
							LogMessage(LexTextControls.ksImportCanceledByUser, lineNumber);
							break;
						}
						Sfm2Xml.SfmField field = m_SfmFile.Lines[i];
						lineNumber = field.LineNumber;
						if (field.Marker.StartsWith("_"))
							continue;
						RnSfMarker rsf;
						if (!m_mapMkrRsf.TryGetValue(field.Marker, out rsf))
						{
							// complain?  log complaint? throw a fit?
							continue;
						}
						if (rsf.m_nLevel == 1)
						{
							recPrev = rec;
							rec = factRec.Create();
							m_cache.LangProject.ResearchNotebookOA.RecordsOC.Add(rec);
							rec.TypeRA = defaultType;
							++m_cRecordsRead;
						}
						else if (rsf.m_nLevel > 1)
						{
							// we don't handle this yet!
						}
						if (rsf.m_flid == 0)
							continue;
						CellarPropertyType cpt = (CellarPropertyType) m_mdc.GetFieldType(rsf.m_flid);
						int clidDst;
						switch (cpt)
						{
							case CellarPropertyType.ReferenceAtomic:
							case CellarPropertyType.ReferenceCollection:
							case CellarPropertyType.ReferenceSequence:
								clidDst = m_mdc.GetDstClsId(rsf.m_flid);
								switch (clidDst)
								{
									case RnGenericRecTags.kClassId:
										StoreLinkData(rec, rsf, field);
										break;
									case CrossReferenceTags.kClassId:
									case ReminderTags.kClassId:
										// we don't handle these yet
										break;
									default:
										int clidBase = clidDst;
										while (clidBase != 0 && clidBase != CmPossibilityTags.kClassId)
											clidBase = m_mdc.GetBaseClsId(clidBase);
										if (clidBase == CmPossibilityTags.kClassId)
											SetListReference(rec, rsf, field);
										break;
								}
								break;
							case CellarPropertyType.OwningAtomic:
							case CellarPropertyType.OwningCollection:
							case CellarPropertyType.OwningSequence:
								clidDst = m_mdc.GetDstClsId(rsf.m_flid);
								switch (clidDst)
								{
									case StTextTags.kClassId:
										Debug.Assert(cpt == CellarPropertyType.OwningAtomic);
										SetTextContent(rec, rsf, field);
										break;
									case RnRoledParticTags.kClassId:
										SetListReference(rec, rsf, field);
										break;
									case RnGenericRecTags.kClassId:
										break;
									default:
										// we don't handle these yet.
										MessageBox.Show("Need to handle owned RnGenericRec", "DEBUG");
										break;
								}
								break;
							case CellarPropertyType.MultiString:
							case CellarPropertyType.MultiUnicode:
							case CellarPropertyType.String:
								SetStringValue(rec, rsf, field, cpt);
								break;
							case CellarPropertyType.GenDate:
								SetGenDateValue(rec, rsf, field);
								break;
							case CellarPropertyType.Time:
								SetDateTimeValue(rec, rsf, field);
								break;
							case CellarPropertyType.Unicode:
							case CellarPropertyType.Binary:
							case CellarPropertyType.Image:
							case CellarPropertyType.Boolean:
							case CellarPropertyType.Float:
							case CellarPropertyType.Guid:
							case CellarPropertyType.Integer:
							case CellarPropertyType.Numeric:
								break;
						}
					}
					ProcessStoredLinkData();
					uowHelper.RollBack = false;
				}
				catch (Exception e)
				{
					string sMsg = String.Format(LexTextControls.ksProblemImportingFrom,
												m_tbDatabaseFileName.Text, e.Message);
					LogMessage(sMsg, lineNumber);
					System.Windows.Forms.MessageBox.Show(this, sMsg);
				}
			}
			m_dtEnd = DateTime.Now;
			progressDlg.Message = LexTextControls.ksCreatingImportLog;
			return CreateImportReport();
		}
Beispiel #44
0
		/// -----------------------------------------------------------------------------------
		/// <summary>
		/// Create the client windows and add corresponding stuff to the sidebar, View menu,
		/// etc.
		/// </summary>
		///
		/// <exception cref="Exception">Invalid user view type in database</exception>
		/// -----------------------------------------------------------------------------------
		public override void InitAndShowClient()
		{
			CheckDisposed();

			using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
				m_cache.ServiceLocator.GetInstance<IActionHandler>()))
			{
				CreateBookFilterIfMissing();

				// Add the user views to the sidebar, menu, info bar
				AddUserViews();

				// Add the filters too
				AddFilters();

				undoHelper.RollBack = false;
			}

			if (SIBAdapter != null)
			{
				SIBAdapter.SetupViewMenuForSideBarTabs(TMAdapter, "mnuFilters");
				SIBAdapter.LoadSettings(MainWndSettingsKey);
			}

			GotoReferenceControl.PassageChanged +=
				new ScrPassageControl.PassageChangedHandler(OnPassageChanged);
		}
Beispiel #45
0
		public void NumberOfSenses()
		{
			ILexEntry entry;
			ILexSense sense2, sense2_2;
			ILexSense senseInserted;
			using (var helper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				entry = m_entryFactory.Create();
				var sense = m_senseFactory.Create();
				entry.SensesOS.Add(sense);
				Assert.AreEqual(1, entry.NumberOfSensesForEntry);
				sense2 = m_senseFactory.Create();
				entry.SensesOS.Add(sense2);
				Assert.AreEqual(2, entry.NumberOfSensesForEntry);
				var sense3 = m_senseFactory.Create();
				entry.SensesOS.Add(sense3);
				Assert.AreEqual(3, entry.NumberOfSensesForEntry);

				var sense2_1 = m_senseFactory.Create();
				sense2.SensesOS.Add(sense2_1);
				Assert.AreEqual(4, entry.NumberOfSensesForEntry);

				sense2_2 = m_senseFactory.Create();
				sense2.SensesOS.Add(sense2_2);
				Assert.AreEqual(5, entry.NumberOfSensesForEntry);

				var sense2_1_1 = m_senseFactory.Create();
				sense2_1.SensesOS.Add(sense2_1_1);
				Assert.AreEqual(6, entry.NumberOfSensesForEntry);

				var sense2_2_1 = m_senseFactory.Create();
				sense2_2.SensesOS.Add(sense2_2_1);
				Assert.AreEqual(7, entry.NumberOfSensesForEntry);

				helper.RollBack = false;
			}
			m_notifiee = new Notifiee();
			IFwMetaDataCache mdc = m_sda.MetaDataCache;
			int nosFlid = mdc.GetFieldId("LexEntry", "NumberOfSensesForEntry", false);
			m_sda.AddNotification(m_notifiee);
			using (var helper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				senseInserted = m_senseFactory.Create();
				entry.SensesOS.Insert(1, senseInserted);
				Assert.AreEqual(8, entry.NumberOfSensesForEntry); // Added one top-level sense
				helper.RollBack = false;
			}
			m_notifiee.CheckChangesWeaker(new[]
							 {
								 new ChangeInformationTest(entry.Hvo, LexEntryTags.kflidSenses, 1, 1, 0),
								 new ChangeInformationTest(entry.Hvo, nosFlid, 0, 0, 0),
							}, "insert second sense in entry");
			m_sda.RemoveNotification(m_notifiee);

			m_notifiee = new Notifiee();
			m_sda.AddNotification(m_notifiee);
			using (var helper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				entry.SensesOS.Remove(senseInserted);
				helper.RollBack = false;
			}
			m_notifiee.CheckChangesWeaker(new[]
							 {
								 new ChangeInformationTest(entry.Hvo, LexEntryTags.kflidSenses, 1, 0, 1),
								 new ChangeInformationTest(entry.Hvo, nosFlid, 0, 0, 0),
							 }, "delete second sense in entry");
			m_sda.RemoveNotification(m_notifiee);
			Assert.AreEqual(7, entry.NumberOfSensesForEntry);

			m_notifiee = new Notifiee();
			m_sda.AddNotification(m_notifiee);
			using (var helper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				senseInserted = m_senseFactory.Create();
				sense2.SensesOS.Insert(1, senseInserted);
				Assert.AreEqual(8, entry.NumberOfSensesForEntry); // Added a subsense.
				helper.RollBack = false;
			}
			m_notifiee.CheckChangesWeaker(new[]
							 {
								 new ChangeInformationTest(sense2.Hvo, LexSenseTags.kflidSenses, 1, 1, 0),
								 new ChangeInformationTest(entry.Hvo, nosFlid, 0, 0, 0),
							 }, "insert subsense in sense");
			m_sda.RemoveNotification(m_notifiee);
			Assert.AreEqual(8, entry.NumberOfSensesForEntry);

			m_notifiee = new Notifiee();
			m_sda.AddNotification(m_notifiee);
			using (var helper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				sense2.SensesOS.Remove(senseInserted);
				helper.RollBack = false;
			}
			m_notifiee.CheckChangesWeaker(new[]
							 {
								 new ChangeInformationTest(sense2.Hvo, LexSenseTags.kflidSenses, 1, 0, 1),
								 new ChangeInformationTest(entry.Hvo, nosFlid, 0, 0, 0),
							 }, "remove subsense from sense");
			m_sda.RemoveNotification(m_notifiee);
			Assert.AreEqual(7, entry.NumberOfSensesForEntry);
		}
Beispiel #46
0
		public void kcptTimeTests()
		{
			var servLoc = Cache.ServiceLocator;
			var lp = servLoc.GetInstance<ILangProjectRepository>().AllInstances().First();
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				lp.DateCreated = DateTime.Now;
				undoHelper.RollBack = false;
			}
			CheckChanges(1, 0, lp.Hvo, CmProjectTags.kflidDateCreated, 0, 0, 0);
			ClearChanges();
		}
Beispiel #47
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles the Click event of the m_btnOk control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		/// ------------------------------------------------------------------------------------
		private void btnOk_Click(object sender, EventArgs e)
		{
			using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(m_cache.ActionHandlerAccessor))
			{
				ICmCell cell;
				string fmtClassFlid = ScrScriptureNoteTags.kClassId + ",{0}|";
				StringBuilder bldr = new StringBuilder();
				m_filter.RowsOS[0].CellsOS.Clear();

				if (chkStatus.Checked)
				{
					bldr.AppendFormat(fmtClassFlid, ScrScriptureNoteTags.kflidResolutionStatus);

					cell = m_cellFactory.Create();
					m_filter.RowsOS[0].CellsOS.Add(cell);
					int value = (rbResolved.Checked ? 1 : 0);
					cell.SetIntegerMatchCriteria(ComparisonTypes.kEquals, value);
				}

				if (chkType.Checked)
				{
					bldr.AppendFormat(fmtClassFlid, CmAnnotationTags.kflidAnnotationType);

					cell = m_cellFactory.Create();
					m_filter.RowsOS[0].CellsOS.Add(cell);
					ICmAnnotationDefn type =
						m_cache.ServiceLocator.GetInstance<ICmAnnotationDefnRepository>().GetObject(
						rbConsultant.Checked ? CmAnnotationDefnTags.kguidAnnConsultantNote :
						CmAnnotationDefnTags.kguidAnnTranslatorNote);
					cell.SetObjectMatchCriteria(type, false, false);
				}

				if (chkScrRange.Checked)
				{
					bldr.AppendFormat(fmtClassFlid, CmBaseAnnotationTags.kflidBeginRef);
					bldr.AppendFormat(fmtClassFlid, CmBaseAnnotationTags.kflidBeginRef);

					ScrReference startRef = (scrBookFrom.ScReference.Chapter == 1 && scrBookFrom.ScReference.Verse == 1) ?
						new ScrReference(scrBookFrom.ScReference.Book, 0, 0, m_scr.Versification) :
						scrBookFrom.ScReference;

					cell = m_cellFactory.Create();
					m_filter.RowsOS[0].CellsOS.Add(cell);
					cell.SetIntegerMatchCriteria(ComparisonTypes.kGreaterThanEqual, startRef);
					cell = m_cellFactory.Create();
					m_filter.RowsOS[0].CellsOS.Add(cell);
					cell.SetIntegerMatchCriteria(ComparisonTypes.kLessThanEqual, scrBookTo.ScReference);
				}

				m_filter.ColumnInfo = bldr.ToString().TrimEnd('|');

				if (chkCategory.Checked)
					tvCatagories.UpdateFilter(m_filter);

				undoHelper.RollBack = false;
			}
		}
Beispiel #48
0
		public void kcptGenDateTests()
		{
			var servLoc = Cache.ServiceLocator;
			var lp = servLoc.GetInstance<ILangProjectRepository>().AllInstances().First();
			ICmPossibilityList peopleList;
			ICmPerson firstPerson;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				lp.PeopleOA = servLoc.GetInstance<ICmPossibilityListFactory>().Create();
				peopleList = lp.PeopleOA;
				firstPerson = servLoc.GetInstance<ICmPersonFactory>().Create();
				peopleList.PossibilitiesOS.Add(firstPerson);
				undoHelper.RollBack = false;
			}
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				firstPerson.DateOfBirth = new GenDate(GenDate.PrecisionType.Before, 1, 1, 3000, true);
				undoHelper.RollBack = false;
			}
			CheckChanges(1, 0, firstPerson.Hvo, CmPersonTags.kflidDateOfBirth, 0, 0, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				// Get rid of the list.
				lp.PeopleOA = null;
				undoHelper.RollBack = false;
			}
			ClearChanges();
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds the "invalid" character as a valid character.
		/// </summary>
		/// <param name="addedCharError">The checking error containing the character that will
		/// be added to the valid character inventory.</param>
		/// ------------------------------------------------------------------------------------
		private void AddAsValidCharacter(CheckingError addedCharError)
		{
			Debug.Assert(addedCharError.CheckId == StandardCheckIds.kguidCharacters,
				"Checking error should be from the valid characters check");

			IWritingSystem ws = m_cache.ServiceLocator.WritingSystems.DefaultVernacularWritingSystem;
			if (TsStringUtils.IsCharacterDefined(addedCharError.MyNote.CitedText))
			{
				using (new WaitCursor(Parent))
				{
					// Get the valid characters from the database
					ValidCharacters validChars = ValidCharacters.Load(ws, ValidCharsLoadException, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
					if (validChars != null)
					{
						validChars.AddCharacter(addedCharError.MyNote.CitedText);
						ws.ValidChars = validChars.XmlString;
						m_cache.ServiceLocator.WritingSystemManager.Save();
					}
					// Mark all data grid view rows containing the newly-defined valid character to irrelevant.
					for (int iRow = 0; iRow < m_list.Count; iRow++)
					{
						CheckingError checkError = GetCheckingError(iRow);
						if (((IStTxtPara)checkError.MyNote.QuoteOA.ParagraphsOS[0]).Contents.Text ==
							addedCharError.MyNote.CitedText)
						{
							// We don't want to create an undoable action, so we suppress subtasks.
							using (var unitOfWork =
									new NonUndoableUnitOfWorkHelper(m_cache.ServiceLocator.GetInstance<IActionHandler>()))
							{
								checkError.Status = CheckingStatus.StatusEnum.Irrelevant;
								unitOfWork.RollBack = false;
							}
						}
					}

					IsStale = true;

					m_dataGridView.Invalidate();
				}
			}
			else
			{
				string msg = ResourceHelper.GetResourceString("kstidUndefinedCharacterMsg");
				MessageBox.Show(this, msg, m_mainWnd.App.ApplicationName,
					MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}
Beispiel #50
0
		public void CustomPropertyTests()
		{
			var servLoc = Cache.ServiceLocator;
			var sda = Cache.DomainDataByFlid;
			var mdc = servLoc.GetInstance<IFwMetaDataCacheManaged>();
			var customCertifiedFlid = mdc.AddCustomField("WfiWordform", "Certified", CellarPropertyType.Boolean, 0);
			var customITsStringFlid = mdc.AddCustomField("WfiWordform", "NewTsStringProp", CellarPropertyType.String, 0);
			var customMultiUnicodeFlid = mdc.AddCustomField("WfiWordform", "MultiUnicodeProp", CellarPropertyType.MultiUnicode, 0);
			var customAtomicReferenceFlid = mdc.AddCustomField("WfiWordform", "NewAtomicRef", CellarPropertyType.ReferenceAtomic, CmPersonTags.kClassId);
			var lp = servLoc.GetInstance<ILangProjectRepository>().AllInstances().First();

			// Add wordform & person.
			IWfiWordform wf;
			ICmPerson person;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				// This does not fire a PC, since the wf is not owned.
				wf = servLoc.GetInstance<IWfiWordformFactory>().Create();

				lp.PeopleOA = servLoc.GetInstance<ICmPossibilityListFactory>().Create();
				var personFactory = servLoc.GetInstance<ICmPersonFactory>();
				person = personFactory.Create();
				lp.PeopleOA.PossibilitiesOS.Add(person);
				undoHelper.RollBack = false;
			}
			CheckChanges(1, -1, 0, 0, 0, 0, 0);
			ClearChanges();

			// Set custom value.
			var userWs = Cache.WritingSystemFactory.UserWs;
			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				sda.SetBoolean(wf.Hvo, customCertifiedFlid, false);
				var tsf = Cache.TsStrFactory;
				sda.SetString(wf.Hvo, customITsStringFlid,
					tsf.MakeString("New ITsString", userWs));
				sda.SetMultiStringAlt(wf.Hvo, customMultiUnicodeFlid,
					userWs, tsf.MakeString("New unicode ITsString", userWs));
				sda.SetObjProp(wf.Hvo, customAtomicReferenceFlid, person.Hvo);
				undoHelper.RollBack = false;
			}
			CheckChanges(4, 0, wf.Hvo, customCertifiedFlid, 0, 0, 0);
			CheckChanges(4, 1, wf.Hvo, customITsStringFlid, 0, 0, 0);
			CheckChanges(4, 2, wf.Hvo, customMultiUnicodeFlid, userWs, 0, 0);
			CheckChanges(4, 3, wf.Hvo, customAtomicReferenceFlid, 0, 0, 0);
			ClearChanges();

			using (var undoHelper = new NonUndoableUnitOfWorkHelper(m_actionHandler))
			{
				// Get rid of the list.
				lp.PeopleOA = null;
				undoHelper.RollBack = false;
			}
			ClearChanges();
		}
Beispiel #51
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates the Back Translation/Print Layout View
		/// </summary>
		/// <param name="viewName">Name of the view.</param>
		/// <param name="viewType">Type of the view.</param>
		/// <param name="pubName">Name of the publication.</param>
		/// <param name="tabItem">The tab item.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		protected ISelectableView CreateBackTransPrintLayoutView(string viewName,
			TeViewType viewType, string pubName, SBTabItemProperties tabItem)
		{
			// Construct the publication control (client window)
			IPublication pub =
				Cache.ServiceLocator.GetInstance<IPublicationRepository>().FindByName(pubName);
			int ws = GetBackTranslationWsForView(TeEditingHelper.ViewTypeString(viewType));
			ScripturePublication pubControl = CreatePublicationView(pub, viewType, ws);
			pubControl.BaseInfoBarCaption = viewName;
			IWritingSystem wsObj = m_cache.ServiceLocator.WritingSystemManager.Get(ws);

			using (NonUndoableUnitOfWorkHelper uowHelper =
				new NonUndoableUnitOfWorkHelper(m_cache.ServiceLocator.ActionHandler))
			{
				pub.IsLeftBound = !wsObj.RightToLeftScript;
				uowHelper.RollBack = false;
			}

			if (tabItem != null)
			{
				tabItem.Tag = pubControl;
				tabItem.Update = true;
			}

			ClientControls.Add(pubControl);

			// Bring the publication to the top of the z-order, so that
			// (if it is the active view) it fills only the remaining space
			ClientControls.SetChildIndex(pubControl, 0);
			m_rgClientViews.Add(TeEditingHelper.ViewTypeString(viewType), pubControl);
			m_uncreatedViews.Remove(viewType);
			return pubControl;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Determines if a dialog box asking for user settings is necessary and, if so,
		/// shows the dialog box.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private bool GetFilterValuesFromUser(ICmFilter userFilter)
		{
			if (userFilter == null)
				return true;

			using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
				Cache.ServiceLocator.GetInstance<IActionHandler>()))
			{
				userFilter.ShowPrompt = 0;
				undoHelper.RollBack = false;
			}

			switch (userFilter.FilterName)
			{
				case "kstidNoteMultiFilter":
					using (MultipleFilterDlg dlg = new MultipleFilterDlg(Cache,
						m_helpTopicProvider, userFilter))
					{
						if (dlg.ShowDialog() != DialogResult.OK)
							return false;
					}
					break;
				case "kstidCategoryNoteFilter":
					using (CategoryFilterDlg dlg = new CategoryFilterDlg(Cache,
						m_helpTopicProvider, userFilter))
					{
						if (dlg.ShowDialog() != DialogResult.OK)
							return false;
					}
					break;
			}
			return true;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Called when the run checks button is clicked.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event
		/// data.</param>
		/// ------------------------------------------------------------------------------------
		private void OnRunChecks(object sender, EventArgs e)
		{
			if (!AreAllSelectedChecksRunable)
				return;

			if (m_bookFilter.BookCount == 0)
			{
				m_btnRunChecks.Enabled = false;
				return;
			}

			if (RunChecksClick != null)
				RunChecksClick(this, EventArgs.Empty);

			if (m_ComboBox.DropDown.Visible)
				m_ComboBox.HideDropDown();

			using (var unitOfWork =
					new NonUndoableUnitOfWorkHelper(m_cache.ServiceLocator.GetInstance<IActionHandler>()))
			{
				Logger.WriteEvent("Running editorial checks");
				using (new WaitCursor(Parent))
				{
					foreach (int bookId in m_bookFilter.BookIds)
					{
						m_chkDataSource.GetText(bookId, 0);
						foreach (IScriptureCheck check in SelectedChecks)
							m_chkDataSource.RunCheck(check);
					}

					m_btnApplyFilter.Enabled = false;
					unitOfWork.RollBack = false;
				}
			}
			OnErrorsUpdated();
			RefreshCheckTree();
		}
			// Not much to do except to initialize the edit box embedded in the combobox with
			// the proper writing system factory, writing system, and TsString.
			public override void SetupCombo()
			{
				CheckDisposed();

				base.SetupCombo();
				int hvoEmptyGloss = 0;
				ITsStrBldr tsb = TsStrBldrClass.Create();

				ComboList.WritingSystemFactory =
					m_caches.MainCache.LanguageWritingSystemFactoryAccessor;
				// Find the WfiAnalysis (from existing analysis or guess) to provide its word glosses as options (cf. LT-1428)
				IWfiAnalysis wa = m_sandbox.GetWfiAnalysisInUse();
				if (wa != null)
				{
					AddComboItems(ref hvoEmptyGloss, tsb, wa);
				}
				// TODO: Maybe this should merge invisibly with the current top of the undo stack? or start an
				// invisible top?
				using (var helper = new NonUndoableUnitOfWorkHelper(m_caches.MainCache.ActionHandlerAccessor))
				{
					var analMethod = m_sandbox.CreateRealWfiAnalysisMethod();
					IAnalysis anal = analMethod.Run();

					helper.RollBack = false;
					if (anal is IWfiAnalysis && anal.Guid != wa.Guid)
					{
						AddComboItems(ref hvoEmptyGloss, tsb, anal as IWfiAnalysis);
					}
					Debug.Assert(analMethod.ObsoleteAnalysis == null);
					//if (analMethod.ObsoleteAnalysis != null)
					//{
					//	// Should we worry about fixing up a reference in a Segment.AnalysesOC?
					//	analMethod.ObsoleteAnalysis.Delete();
					//}
				}
				ComboList.Items.Add(new HvoTssComboItem(hvoEmptyGloss,
					TsStringUtils.MakeTss(ITextStrings.ksNewWordGloss2, m_caches.MainCache.DefaultUserWs)));
				// Set combo selection to current selection.
				ComboList.SelectedIndex = this.IndexOfCurrentItem;

				// Enhance JohnT: if the analysts decide so, here we add all the other glosses from other analyses.

			}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// User clicked OK button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		/// ------------------------------------------------------------------------------------
		private void OnOk(object sender, System.EventArgs e)
		{
			using (new WaitCursor(this))
			{
				StepThroughNodesAndAddToList(m_treeView.Nodes[0]);
				if (m_BooksToSave.Count == 0)
				{
					Close();
					return;
				}

				using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(
					m_cache.ServiceLocator.GetInstance<IActionHandler>()))
				{
					m_SavedVersion = m_cache.ServiceLocator.GetInstance<IScrDraftFactory>().Create(
						m_description.Text, m_BooksToSave);
					undoHelper.RollBack = false;
				}
				Close();
			}
		}
Beispiel #56
0
		///-------------------------------------------------------------------------------
		/// <summary>
		/// When the Source button is clicked, display the import wizard.
		/// </summary>
		///-------------------------------------------------------------------------------
		private void btnSource_Click(object sender, System.EventArgs e)
		{
			using (ImportWizard importWizard = new ImportWizard(m_scr.Cache.ProjectId.Name,
				m_scr, m_StyleSheet, m_helpTopicProvider, m_app))
			{
				using (NonUndoableUnitOfWorkHelper undoHelper = new NonUndoableUnitOfWorkHelper(ActionHandler))
				{
					if (importWizard.ShowDialog() == DialogResult.Cancel)
					{
						// Ditch any in-memory changes made to the settings. Reload from the DB.
						m_importSettings.RevertToSaved();
					}
					else
						undoHelper.RollBack = false;
				}

				// If there are no files after showing the wizard, close the import dialog
				if (InitBookNameList() == 0)
				{
					MessageBox.Show(this, DlgResources.ResourceString("kstidImportFilesUnavailable"),
						m_app.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
					Close();
					return;
				}

				// The default set of settings may have changed.
				m_importSettings = m_scr.DefaultImportSettings;

				// Update the file ranges for import because they may have changed.
				InitializeStartAndEndRefControls();

				// Update the passage controls to reflect the new range of files available
				// Only make changes that do not expand the available range of books since a
				// range may have been specified before the wizard was run that we do not
				// want to overwrite
				if (!scrPsgFrom.IsReferenceValid(scrPsgFrom.ScReference))
					SetStartRefToFirstImportableBook();

				if (!scrPsgTo.IsReferenceValid(scrPsgTo.ScReference))
					SetEndRefToLastImportableBook();
			}
			btnOK.Focus();
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Raises the <see cref="E:System.Windows.Forms.Control.HandleCreated"/> event.
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
		/// ------------------------------------------------------------------------------------
		protected override void OnHandleCreated(EventArgs e)
		{
			base.OnHandleCreated(e);

			try
			{
				using (NonUndoableUnitOfWorkHelper unitOfWork = new NonUndoableUnitOfWorkHelper(
					m_cache.ServiceLocator.GetInstance<IActionHandler>()))
				{
					m_scrCheckList = InstalledScriptureChecks.GetChecks(m_chkDataSource);
					unitOfWork.RollBack = false;
				}
			}
			catch (ApplicationException exception)
			{
				// REVIEW: what do we do in this case?
				Logger.WriteEvent("Got exception loading Scripture checks: ");
				Logger.WriteError(exception);
				MessageBox.Show(exception.Message, m_app.ApplicationName,
					MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}

			FillAvailableChecksTree(m_scrCheckList);

			if (m_checkErrorsList != null)
			{
				OnErrorsUpdated();
				m_btnApplyFilter.Enabled = false;
			}

			if (m_persistence != null)
				OnLoadSettings(m_persistence.SettingsKey);
		}