예제 #1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Ensures the given localization is at the current version.
        /// </summary>
        /// <param name="locale">The locale representing the required localization.</param>
        /// <param name="caller">The form that is calling this method (used as the owner
        /// of the progress dialog box - can be null if progress dialog is supplied).</param>
        /// <param name="existingProgressDlg">The existing progress dialog box if any.</param>
        /// ------------------------------------------------------------------------------------
        private void EnsureCurrentLocalization(string locale, Form caller, IThreadedProgress existingProgressDlg)
        {
            string localizationFile = FwDirectoryFinder.GetKeyTermsLocFilename(locale);

            if (!FileUtils.FileExists(localizationFile))
            {
                return;                 // There is no localization available for this locale, so we're as current as we're going to get.
            }
            BiblicalTermsLocalization loc;

            try
            {
                loc = DeserializeBiblicalTermsLocFile(localizationFile);
            }
            catch (InstallationException e)
            {
                ErrorReporter.ReportException(e, m_app.SettingsKey, m_app.SupportEmailAddress, caller, false);
                return;
            }

            string resourceName = GetLocalizationResourceName(locale);

            if (IsResourceOutdated(resourceName, loc.Version))
            {
                NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(m_servLoc.GetInstance <IActionHandler>(),
                                                                   () => {
                    existingProgressDlg.RunTask(true, UpdateLocalization, loc, locale);
                    SetNewResourceVersion(resourceName, loc.Version);
                });
            }
        }
예제 #2
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Perform a restore of the project specified in the settings.
        /// </summary>
        /// <param name="progressDlg">The progress dialog.</param>
        /// <exception cref="IOException">File does not exist, or some such problem</exception>
        /// <exception cref="InvalidBackupFileException">XML deserialization problem or required
        /// files not found in zip file</exception>
        /// ------------------------------------------------------------------------------------
        public void RestoreProject(IThreadedProgress progressDlg)
        {
            BackupFileSettings fileSettings = m_restoreSettings.Backup;

            fileSettings.Validate();             // Normally, this will already have been done, so this will do nothing.

            bool suppressConversion = false;

            //First of all, if the project exists and we are overwriting it, then make a copy of the project.  That way
            //if the restoration fails part way through, we can put it back the way it was.
            if (Directory.Exists(m_restoreSettings.ProjectPath))
            {
                // If the project already exists using the fwdata extension, either we're not sharing,
                // or it is a project for which sharing is suppressed. In any case we don't want to
                // convert the new project.
                suppressConversion = File.Exists(m_restoreSettings.FullProjectPath);
                CreateACopyOfTheProject();
            }

            //When restoring a project, ensure all the normal folders are there even if some
            //of those folders had nothing from them in the backup.
            Directory.CreateDirectory(m_restoreSettings.ProjectPath);
            FdoCache.CreateProjectSubfolders(m_restoreSettings.ProjectPath);

            try
            {
                //Import from FW version 6.0 based on the file extension.
                string extension = Path.GetExtension(fileSettings.File).ToLowerInvariant();
                if (extension == FwFileExtensions.ksFw60BackupFileExtension || extension == ".xml")
                {
                    ImportFrom6_0Backup(fileSettings, progressDlg);
                }
                else                     //Restore from FW version 7.0 and newer backup.
                {
                    RestoreFrom7_0AndNewerBackup(fileSettings);
                }
            }
            catch (Exception error)
            {
                if (error is IOException || error is InvalidBackupFileException ||
                    error is UnauthorizedAccessException)
                {
                    CleanupAfterRestore(false);
                    // ENHANCE: If/when we have the restore process using a progress dialog so that this code
                    // runs in the progress dialog thread instead of the main thread, all message boxes should
                    // be replaced with the ThreadHelper.ShowMessageBox() method so that they will be thread-safe.
                    MessageBoxUtils.Show(null, error.Message, AppStrings.ksRestoreDidNotSucceed,
                                         MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                throw;
            }

            // switch to the desired backend (if it's in the projects directory...anything else stays XML for now).
            if (DirectoryFinder.IsSubFolderOfProjectsDirectory(m_restoreSettings.ProjectPath) && !suppressConversion)
            {
                ClientServerServices.Current.Local.ConvertToDb4oBackendIfNeeded(progressDlg, m_restoreSettings.FullProjectPath);
            }

            CleanupAfterRestore(true);
        }
예제 #3
0
        private void ImportFrom6_0Backup(BackupFileSettings fileSettings, IThreadedProgress progressDlg)
        {
            var  importer = new ImportFrom6_0(progressDlg, m_converterConsolePath, m_dbPath);
            bool importSuccessful;

            try
            {
                string projFile;
                importSuccessful = importer.Import(fileSettings.File, m_restoreSettings.ProjectName, m_restoreSettings.ProjectsRootFolder, out projFile);
            }
            catch (CannotConvertException e)
            {
                FailedImportCleanUp(importer);
                throw;
            }
            if (!importSuccessful)
            {
                FailedImportCleanUp(importer);

                if (!importer.HaveOldFieldWorks || !importer.HaveFwSqlServer)
                {
                    throw new MissingOldFwException("Error restoring from FieldWorks 6.0 (or earlier) backup",
                                                    importer.HaveFwSqlServer, importer.HaveOldFieldWorks);
                }
                throw new FailedFwRestoreException("Error restoring from FieldWorks 6.0 (or earlier) backup");
            }
        }
예제 #4
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// TODO: for now, this just creates the key terms list if the list isn't in the DB...
        /// If the current key terms version in the DD doesn't match that of the current XML
        /// file, update the DB.
        /// </summary>
        /// <param name="lp">language project</param>
        /// <param name="app">The TE application.</param>
        /// <param name="existingProgressDlg">The existing progress dialog, if any.</param>
        /// ------------------------------------------------------------------------------------
        public static void EnsureCurrentKeyTerms(ILangProject lp, FwApp app,
                                                 IThreadedProgress existingProgressDlg)
        {
            TeKeyTermsInit keyTermsInit = new TeKeyTermsInit(lp.TranslatedScriptureOA, app);

            keyTermsInit.EnsureCurrentResource(existingProgressDlg);
        }
예제 #5
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Perform the data migration on the DTOs in the given repository.
        ///
        /// The resulting xml in the DTOs must be compatible with the xml of the given
        /// <paramref name="updateToVersion"/> number.
        ///
        /// The implementation of this interface will process as many migrations, in sequence,
        /// as are needed to move from whatever version is in the repository to bring it up to
        /// the specified version number in <paramref name="updateToVersion"/>.
        /// </summary>
        /// <param name="domainObjectDtoRepository">Repository of CmObject DTOs.</param>
        /// <param name="updateToVersion">
        /// Model version number the updated repository should have after the migration
        /// </param>
        /// <param name="progressDlg">The dialog to display migration progress</param>
        /// <remarks>
        /// An implementation of this interface is free to define its own migration definitions.
        /// These definitions need not be compatible with any other implementation of this interface.
        /// That is, there is no interface defined for declaring and consuming data migration instructions.
        /// </remarks>
        /// <exception cref="DataMigrationException">
        /// Thrown if the migration cannot be done successfully for the following reasons:
        /// <list type="disc">
        /// <item>
        /// <paramref name="domainObjectDtoRepository"/> is null.
        /// </item>
        /// <item>
        /// Don't know how to upgrade to version: <paramref name="updateToVersion"/>.
        /// </item>
        /// <item>
        /// Version number in <paramref name="domainObjectDtoRepository"/>
        /// is newer than <paramref name="updateToVersion"/>.
        /// </item>
        /// </list>
        /// </exception>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository,
                                     int updateToVersion, IThreadedProgress progressDlg)
        {
            if (domainObjectDtoRepository == null)
            {
                throw new DataMigrationException("'domainObjectDtoRepository' is null.");
            }

            // Current version of the source.
            int currentDataStoreModelVersion = domainObjectDtoRepository.CurrentModelVersion;

            if (currentDataStoreModelVersion == updateToVersion)
            {
                return;                                                              // That migration was easy enough. :-)
            }
            if (currentDataStoreModelVersion > updateToVersion)
            {
                throw new DataMigrationException(
                          String.Format("Cannot perform backward migration from the newer '{0}' data version to the older code version '{1}'.",
                                        currentDataStoreModelVersion, updateToVersion));
            }

            progressDlg.Title       = Strings.ksDataMigrationCaption;
            progressDlg.AllowCancel = false;
            progressDlg.Minimum     = 0;
            progressDlg.Maximum     = (updateToVersion - currentDataStoreModelVersion) + 1;
            progressDlg.RunTask(true, MigrateTask, domainObjectDtoRepository, updateToVersion);
        }
예제 #6
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Perform one-time initialization of a new Scripture project
		/// </summary>
		/// <param name="cache">The database cache</param>
		/// <param name="app">The TE application.</param>
		/// <param name="progressDlg">The progress dialog (can be null).</param>
		/// <returns>
		/// true if data loaded successfully; false, otherwise
		/// </returns>
		/// ------------------------------------------------------------------------------------
		public static bool Initialize(FdoCache cache, FwApp app,
			IThreadedProgress progressDlg)
		{
			TeScrInitializer scrInitializer = new TeScrInitializer(cache);
			scrInitializer.m_app = app;
			return scrInitializer.Initialize(progressDlg);
		}
예제 #7
0
		/// <summary>
		/// Constructor for run-time debugging.
		/// </summary>
		public ImportFrom6_0(IThreadedProgress progressDlg, string converterConsolePath, string dbPath, bool fDebug)
		{
			m_progressDlg = progressDlg;
			m_converterConsolePath = converterConsolePath;
			m_dbPath = dbPath;
			m_fVerboseDebug = fDebug;
		}
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Make sure the stylesheet for the specified object is current.
        /// </summary>
        /// <param name="progressDlg">The progress dialog if one is already up.</param>
        /// ------------------------------------------------------------------------------------
        public void EnsureCurrentResource(IThreadedProgress progressDlg)
        {
            var  doc = LoadDoc();
            Guid newVersion;

            try
            {
                newVersion = GetVersion(doc);
            }
            catch (Exception e)
            {
                ReportInvalidInstallation(string.Format(
                                              FrameworkStrings.ksInvalidResourceFileVersion, ResourceFileName), e);
                newVersion = Guid.Empty;
            }

            // Re-load the factory settings if they are not at current version.
            if (IsResourceOutdated(ResourceName, newVersion))
            {
                ProcessResources(progressDlg, doc);
#if DEBUG
                Debug.Assert(m_fVersionUpdated);
#endif
            }
            else
            {
                EnsureCurrentLocalizations(progressDlg);
            }
        }
예제 #9
0
        /// -------------------------------------------------------------------------------------
        /// <summary>
        /// Perform one-time initialization of a new Scripture project
        /// </summary>
        /// <returns>true if data loaded successfully; false, otherwise</returns>
        /// -------------------------------------------------------------------------------------
        protected bool Initialize(IThreadedProgress progressDlg)
        {
            if (m_scr != null)
            {
                // Preload all book, section and paragraphs if we already have Scripture
                m_cache.ServiceLocator.DataSetup.LoadDomainAsync(BackendBulkLoadDomain.Scripture);

                ILangProject lp = m_cache.LanguageProject;
                if (m_scr.BookAnnotationsOS.Count != 0 &&
                    m_scr.PublicationsOC.Count != 0 &&
                    lp.KeyTermsList.PossibilitiesOS.Count >= 1 &&
                    m_scr.NoteCategoriesOA != null && m_scr.NoteCategoriesOA.PossibilitiesOS.Count > 0)
                {
                    return(true);
                }
            }

            try
            {
                progressDlg.RunTask(InitializeScriptureProject);
            }
            catch (WorkerThreadException e)
            {
                while (m_cache.DomainDataByFlid.GetActionHandler().CanUndo())
                {
                    UndoResult ures = m_cache.DomainDataByFlid.GetActionHandler().Undo();
                    // Enhance JohnT: make use of ures?
                }
                MessageBox.Show(Form.ActiveForm, e.InnerException.Message, FwUtils.ksTeAppName,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
예제 #10
0
        private object MigrateTask(IThreadedProgress progressDlg, object[] parameters)
        {
            var domainObjectDtoRepository    = (IDomainObjectDTORepository)parameters[0];
            var updateToVersion              = (int)parameters[1];
            int currentDataStoreModelVersion = domainObjectDtoRepository.CurrentModelVersion;

            while (currentDataStoreModelVersion < updateToVersion)
            {
                var currentKey = currentDataStoreModelVersion + 1;
                progressDlg.Message = string.Format(Strings.ksDataMigrationStatusMessage, currentKey);
                m_individualMigrations[currentKey].PerformMigration(domainObjectDtoRepository);
                if (currentKey != domainObjectDtoRepository.CurrentModelVersion)
                {
                    throw new InvalidOperationException(
                              string.Format("Migrator for {0} did not function correctly and returned an invalid version number.", currentKey));
                }
                currentDataStoreModelVersion = domainObjectDtoRepository.CurrentModelVersion;
                progressDlg.Step(1);
            }

            // Have DTO repos 'merge' newbies, dirtballs, and goners into proper hashset.
            // This needs to be done for cases of multiple step migrations,
            // as one step can add a new DTO, while another can modify it.
            // That would put it in the newbies and the dirtball hashsets,
            // which causes the DM client code to crash.
            progressDlg.Message = Strings.ksDataMigrationFinishingMessage;
            domainObjectDtoRepository.EnsureItemsInOnlyOneSet();
            progressDlg.Step(1);
            return(null);
        }
예제 #11
0
		/// <summary>
		/// Perform a backup of the current project, using specified settings.
		/// </summary>
		/// <returns>The backup file or null if something went wrong.</returns>
		public bool BackupProject(IThreadedProgress progressDlg, out string backupFile)
		{
			PersistBackupFileSettings();

			backupFile = null;
			try
			{
				// Make sure any changes we want backup are saved.
				m_cache.ServiceLocator.GetInstance<IUndoStackManager>().Save();
				m_cache.ServiceLocator.GetInstance<IDataStorer>().CompleteAllCommits();

				string tempFilePath = ClientServerServices.Current.Local.CopyToXmlFile(m_cache, m_settings.DatabaseFolder);
				var filesToZip = CreateListOfFilesToZip();

				progressDlg.Title = Strings.ksBackupProgressCaption;
				progressDlg.IsIndeterminate = true;
				progressDlg.AllowCancel = false;
				m_failedFiles.Clear(); // I think it's always a new instance, but play safe.
				backupFile = (string)progressDlg.RunTask(true, BackupTask, filesToZip);
				if (tempFilePath != null)
					File.Delete(tempFilePath); // don't leave the extra fwdata file around to confuse things.
			}
			catch (Exception e)
			{
				// Something went catastrophically wrong. Don't leave a junk backup around.
				if (backupFile != null)
					File.Delete(backupFile);
				if (e is WorkerThreadException && e.InnerException is FwBackupException)
					throw e.InnerException;
				throw new ContinuableErrorException("Backup did not succeed. Code is needed to handle this case.", e);
			}

			return m_failedFiles.Count == 0;
		}
예제 #12
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Converts the chapter verse numbers.
        /// </summary>
        /// <param name="progressDlg">The progress DLG.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        private object ConvertChapterVerseNumbers(IThreadedProgress progressDlg, params object[] parameters)
        {
            char zeroDigit = (m_scr.UseScriptDigits ? (char)m_scr.ScriptDigitZero : '0');

            ILgCharacterPropertyEngine charEngine = m_cache.ServiceLocator.UnicodeCharProps;

            foreach (IScrBook book in m_scr.ScriptureBooksOS)
            {
                // update the status with the book name.
                progressDlg.Message =
                    string.Format(DlgResources.ResourceString("kstidConvertChapterVerseNumbersMessage"),
                                  book.BestUIName);

                foreach (IScrSection section in book.SectionsOS)
                {
                    foreach (IScrTxtPara para in section.ContentOA.ParagraphsOS)
                    {
                        ConvertChapterVerseNumbers(para, zeroDigit, charEngine);
                    }
                }

                progressDlg.Step(0);
            }

            return(null);
        }
예제 #13
0
 /// <summary>
 /// Constructor for run-time debugging.
 /// </summary>
 public ImportFrom6_0(IThreadedProgress progressDlg, string converterConsolePath, string dbPath, bool fDebug)
 {
     m_progressDlg          = progressDlg;
     m_converterConsolePath = converterConsolePath;
     m_dbPath        = dbPath;
     m_fVerboseDebug = fDebug;
 }
예제 #14
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Updates the verse bridges.
        /// </summary>
        /// <param name="progressDlg">The progress dialog.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns>Always null.</returns>
        /// ------------------------------------------------------------------------------------
        private object UpdateVerseBridges(IThreadedProgress progressDlg, object[] parameters)
        {
            Debug.Assert(parameters.Length == 1);
            string oldBridge = (string)parameters[0];
            string newBridge = m_scr.Bridge;

            foreach (IScrBook book in m_scr.ScriptureBooksOS)
            {
                progressDlg.Message =
                    string.Format(DlgResources.ResourceString("kstidUpdateVerseBridgesInBook"),
                                  book.Name.UserDefaultWritingSystem.Text);

                foreach (IScrSection section in book.SectionsOS)
                {
                    foreach (IScrTxtPara para in section.ContentOA.ParagraphsOS)
                    {
                        UpdateVerseBridgesInParagraph(para, oldBridge, newBridge);
                    }
                }

                progressDlg.Step(0);
            }

            return(null);
        }
        /// <summary>
        /// Method with required signature for ProgressDialogWithTask.RunTask, to invoke XmlTranslatedLists.ImportTranslatedListsForWs.
        /// Should only be called by the other overload of ImportTranslatedListsForWs.
        /// args must be a writing system identifier string and an FdoCache.
        /// </summary>
        /// <param name="dlg"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private static object ImportTranslatedListsForWs(IThreadedProgress dlg, object[] args)
        {
            var ws    = (string)args[0];
            var cache = (FdoCache)args[1];

            XmlTranslatedLists.ImportTranslatedListsForWs(ws, cache, dlg);
            return(null);
        }
예제 #16
0
		protected override void DoStage2Conversion(byte[] stage1, IThreadedProgress dlg)
		{
		   var stage2Converter = new LinguaLinksImport(m_cache, null, null);
			// Until we have a better idea, assume we're half done with the import when we've produced the intermediate.
			// TODO: we could do progress based on number of words to import.
			dlg.Position += 50;
			stage2Converter.ImportWordsFrag(() => new MemoryStream(stage1), LinguaLinksImport.ImportAnalysesLevel.WordGloss);
		}
예제 #17
0
        /// <summary>
        /// Method with required signature for ProgressDialogWithTask.RunTask, to invoke XmlTranslatedLists.ImportTranslatedListsForWs.
        /// Should only be called by the other overload of ImportTranslatedListsForWs.
        /// args must be a writing system identifier string and an LcmCache.
        /// </summary>
        /// <param name="dlg"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private static object ImportTranslatedListsForWs(IThreadedProgress dlg, object[] args)
        {
            var ws    = (string)args[0];
            var cache = (LcmCache)args[1];

            XmlTranslatedLists.ImportTranslatedListsForWs(ws, cache, FwDirectoryFinder.TemplateDirectory, dlg);
            return(null);
        }
예제 #18
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Perform one-time initialization of a new Scripture project
        /// </summary>
        /// <param name="cache">The database cache</param>
        /// <param name="app">The TE application.</param>
        /// <param name="progressDlg">The progress dialog (can be null).</param>
        /// <returns>
        /// true if data loaded successfully; false, otherwise
        /// </returns>
        /// ------------------------------------------------------------------------------------
        public static bool Initialize(FdoCache cache, FwApp app,
                                      IThreadedProgress progressDlg)
        {
            TeScrInitializer scrInitializer = new TeScrInitializer(cache);

            scrInitializer.m_app = app;
            return(scrInitializer.Initialize(progressDlg));
        }
예제 #19
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// If the current stylesheet version in the Db doesn't match that of the current XML
        /// file, update the DB.
        /// </summary>
        /// <param name="lp">The language project</param>
        /// <param name="progressDlg">The progress dialog.</param>
        /// ------------------------------------------------------------------------------------
        public static void EnsureCurrentStylesheet(ILangProject lp, IThreadedProgress progressDlg)
        {
            // We don't need to establish a NonUndoableUnitOfWork here because caller has already
            // done it and if not, the internal code of StylesXmlAccessor will do it for us.
            var acc = new FlexStylesXmlAccessor(lp.LexDbOA);

            acc.EnsureCurrentResource(progressDlg);
        }
예제 #20
0
		/// <summary>
		/// This method will display a message box above the progress dialog.
		/// </summary>
		/// <param name="progress"></param>
		/// <param name="text"></param>
		/// <param name="title"></param>
		/// <param name="buttons"></param>
		/// <returns></returns>
		private static DialogResult ShowDialogAboveProgressbar(IThreadedProgress progress,
			string text, string title, MessageBoxButtons buttons)
		{
			return MessageBox.Show(
				text,
				title,
				buttons,
				MessageBoxIcon.Warning);
		}
예제 #21
0
 private void SafelyEnsureStyleSheetPostTERemoval(IThreadedProgress progressDlg)
 {
     // Ensure that we have up-to-date versification information so that projects with old TE styles
     // will be able to migrate them from the Scripture area to the LanguageProject model
     ScrReference.InitializeVersification(FwDirectoryFinder.EditorialChecksDirectory, false);
     // Make sure this DB uses the current stylesheet version
     // Suppress adjusting scripture sections since isn't safe to do so at this point
     SectionAdjustmentSuppressionHelper.Do(() => FlexStylesXmlAccessor.EnsureCurrentStylesheet(Cache.LangProject, progressDlg));
 }
예제 #22
0
 /// <summary>
 /// This method will display a message box above the progress dialog.
 /// </summary>
 /// <param name="progress"></param>
 /// <param name="text"></param>
 /// <param name="title"></param>
 /// <param name="buttons"></param>
 /// <returns></returns>
 private static DialogResult ShowDialogAboveProgressbar(IThreadedProgress progress,
                                                        string text, string title, MessageBoxButtons buttons)
 {
     return(MessageBox.Show(progress.Form,
                            text,
                            title,
                            buttons,
                            MessageBoxIcon.Warning));
 }
예제 #23
0
        protected override void DoStage2Conversion(byte[] stage1, IThreadedProgress dlg)
        {
            var stage2Converter = new LinguaLinksImport(m_cache, null, null);

            // Until we have a better idea, assume we're half done with the import when we've produced the intermediate.
            // TODO: we could do progress based on number of words to import.
            dlg.Position += 50;
            stage2Converter.ImportWordsFrag(() => new MemoryStream(stage1), LinguaLinksImport.ImportAnalysesLevel.WordGloss);
        }
예제 #24
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Ensure that all the localizations of the key terms list for the UI and current
        /// analysis writing systems are up-to-date.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected override void EnsureCurrentLocalizations(IThreadedProgress progressDlg)
        {
            string locale = Cache.WritingSystemFactory.GetStrFromWs(Cache.DefaultUserWs);

            EnsureCurrentLocalization(locale, null, progressDlg);
            foreach (IWritingSystem ws in Cache.LangProject.AnalysisWritingSystems.Where(w => w.Handle != Cache.DefaultUserWs))
            {
                EnsureCurrentLocalization(ws.IcuLocale, null, progressDlg);
            }
        }
예제 #25
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Perform a restore of the project specified in the settings.
        /// </summary>
        /// <param name="progressDlg">The progress dialog.</param>
        /// <exception cref="IOException">File does not exist, or some such problem</exception>
        /// <exception cref="InvalidBackupFileException">XML deserialization problem or required
        /// files not found in zip file</exception>
        /// ------------------------------------------------------------------------------------
        public void RestoreProject(IThreadedProgress progressDlg)
        {
            BackupFileSettings fileSettings = m_restoreSettings.Backup;

            fileSettings.Validate();             // Normally, this will already have been done, so this will do nothing.

            bool suppressConversion = false;

            //First of all, if the project exists and we are overwriting it, then make a copy of the project.  That way
            //if the restoration fails part way through, we can put it back the way it was.
            if (Directory.Exists(m_restoreSettings.ProjectPath))
            {
                // If the project already exists using the fwdata extension, either we're not sharing,
                // or it is a project for which sharing is suppressed. In any case we don't want to
                // convert the new project.
                suppressConversion = File.Exists(m_restoreSettings.FullProjectPath);
                CreateACopyOfTheProject();
            }

            //When restoring a project, ensure all the normal folders are there even if some
            //of those folders had nothing from them in the backup.
            Directory.CreateDirectory(m_restoreSettings.ProjectPath);
            FdoCache.CreateProjectSubfolders(m_restoreSettings.ProjectPath);

            try
            {
                //Import from FW version 6.0 based on the file extension.
                var extension = Path.GetExtension(fileSettings.File).ToLowerInvariant();
                if (extension == FdoFileHelper.ksFw60BackupFileExtension || extension == ".xml")
                {
                    ImportFrom6_0Backup(fileSettings, progressDlg);
                }
                else                     //Restore from FW version 7.0 and newer backup.
                {
                    RestoreFrom7_0AndNewerBackup(fileSettings);
                }
            }
            catch (Exception error)
            {
                if (error is IOException || error is InvalidBackupFileException ||
                    error is UnauthorizedAccessException)
                {
                    CleanupAfterRestore(false);
                }
                throw;
            }

            // switch to the desired backend (if it's in the projects directory...anything else stays XML for now).
            if (Path.GetDirectoryName(m_restoreSettings.ProjectPath) == m_restoreSettings.ProjectsRootFolder && !suppressConversion)
            {
                ClientServerServices.Current.Local.ConvertToDb4oBackendIfNeeded(progressDlg, m_restoreSettings.FullProjectPath);
            }

            CleanupAfterRestore(true);
        }
예제 #26
0
 public void ExportReversalContent(string xhtmlPath, string reversalWs = null, DictionaryConfigurationModel configuration = null,
                                   IThreadedProgress progress          = null)
 {
     using (ClerkActivator.ActivateClerkMatchingExportType(ReversalType, m_mediator))
         using (ReversalIndexActivator.ActivateReversalIndex(reversalWs, m_mediator, m_cache))
         {
             configuration = configuration ?? new DictionaryConfigurationModel(
                 DictionaryConfigurationListener.GetCurrentConfiguration(m_mediator, "ReversalIndex"), m_cache);
             ExportConfiguredXhtml(xhtmlPath, configuration, ReversalType, progress);
         }
 }
예제 #27
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Backs up the project.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        internal void BackupProject(IThreadedProgress progressDlg)
        {
            BackupProjectSettings settings = new BackupProjectSettings(m_cache, m_backupProjectView);

            settings.DestinationFolder = m_backupProjectView.DestinationFolder;
            settings.AppAbbrev         = m_appAbbrev;

            ProjectBackupService backupService = new ProjectBackupService(m_cache, settings);

            backupService.BackupProject(progressDlg);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates the scripture note categories.
        /// </summary>
        /// <param name="dlg">The progress dialog.</param>
        /// <param name="parameters">The parameters: first parameter is a XmlNode with the
        /// notes categories, second parameter is the scripture object.</param>
        /// <returns>Always <c>null</c>.</returns>
        /// ------------------------------------------------------------------------------------
        private static object CreateScrNoteCategories(IThreadedProgress dlg, object[] parameters)
        {
            Debug.Assert(parameters.Length == 2);
            XmlNode    scrNoteCategories = (XmlNode)parameters[0];
            IScripture scr = (IScripture)parameters[1];

            TeScrNoteCategoriesInit noteCategoriesInitializer =
                new TeScrNoteCategoriesInit(dlg, scr, scrNoteCategories);

            noteCategoriesInitializer.CreateScrNoteCategories();

            return(null);
        }
예제 #29
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Update the existing categories and terms with new localized strings.
        /// </summary>
        /// <param name="dlg">The progress dialog.</param>
        /// <param name="parameters">The parameters: 1) the BiblicalTermsLocalization object
        /// representing the contents of the XML file with the localized strings; 2) The ICU
        /// locale (string).</param>
        /// <returns>always null</returns>
        /// ------------------------------------------------------------------------------------
        protected object UpdateLocalization(IThreadedProgress dlg, params object[] parameters)
        {
            BiblicalTermsLocalization loc = (BiblicalTermsLocalization)parameters[0];
            string locale = (string)parameters[1];

            const int kcStepsToBuildLookupTable = 4;

            dlg.Position = 0;
            dlg.Minimum  = 0;
            dlg.Maximum  = loc.Categories.Count + loc.Terms.Count + kcStepsToBuildLookupTable;
            dlg.Title    = TeResourceHelper.GetResourceString("kstidLoadKeyTermsInDBCaption");
            dlg.Message  = TeResourceHelper.FormatResourceString("kstidLoadKeyTermsLocalizations",
                                                                 m_wsf.get_Engine(locale).LanguageName);

            m_wsDefault = m_servLoc.WritingSystemManager.GetWsFromStr("en");

            int hvoLocWs = loc.WritingSystemHvo = m_wsf.GetWsFromStr(locale);

            IEnumerable <ICmPossibility> categories = ((ILangProject)m_scr.Owner).KeyTermsList.PossibilitiesOS;

            foreach (CategoryLocalization localizedCategory in loc.Categories)
            {
                ICmPossibility category = categories.FirstOrDefault(
                    p => p.Abbreviation.get_String(m_wsDefault).Text == localizedCategory.Id);
                if (category != null)
                {
                    category.Name.set_String(hvoLocWs, localizedCategory.Gloss);
                }
                dlg.Step(1);
            }

            Dictionary <int, IChkTerm> termLookupTable =
                m_servLoc.GetInstance <IChkTermRepository>().AllInstances().ToDictionary(t => t.TermId);

            dlg.Step(kcStepsToBuildLookupTable);

            IChkTerm term;
            string   message = TeResourceHelper.GetResourceString("kstidLoadKeyTermsInDBStatus");

            foreach (TermLocalization localizedTerm in loc.Terms)
            {
                dlg.Message = string.Format(message, localizedTerm.Gloss);

                if (termLookupTable.TryGetValue(localizedTerm.Id, out term))
                {
                    SetLocalizedGlossAndDescription(term, localizedTerm, loc.WritingSystemHvo);
                }
                dlg.Step(1);
            }
            return(null);
        }
예제 #30
0
        /// <summary/>
        public string CreateNewLangProj(IThreadedProgress progressDialog, ISynchronizeInvoke threadHelper)
        {
            try
            {
                var defaultAnalysis   = WritingSystemContainer.CurrentAnalysisWritingSystems.First();
                var defaultVernacular = WritingSystemContainer.CurrentVernacularWritingSystems.First();
                return(LcmCache.CreateNewLangProj(progressDialog, ProjectName, FwDirectoryFinder.LcmDirectories,
                                                  threadHelper,
                                                  defaultAnalysis,
                                                  defaultVernacular,
                                                  "en",// TODO: replicate original
                                                  new HashSet <CoreWritingSystemDefinition>(WritingSystemContainer.AnalysisWritingSystems.Skip(1)),
                                                  new HashSet <CoreWritingSystemDefinition>(WritingSystemContainer.VernacularWritingSystems.Skip(1)),
                                                  AnthroModel.AnthroFileName));
            }
            catch (WorkerThreadException wex)
            {
                Exception e = wex.InnerException;
                if (e is UnauthorizedAccessException)
                {
                    if (MiscUtils.IsUnix)
                    {
                        // Tell Mono user he/she needs to logout and log back in
                        MessageBoxUtils.Show(ResourceHelper.GetResourceString("ksNeedToJoinFwGroup"));
                    }
                    else
                    {
                        MessageBoxUtils.Show(string.Format(FwCoreDlgs.kstidErrorNewDb, e.Message),
                                             FwUtils.ksSuiteName);
                    }
                }
                else if (e is ApplicationException)
                {
                    MessageBoxUtils.Show(string.Format(FwCoreDlgs.kstidErrorNewDb, e.Message),
                                         FwUtils.ksSuiteName);
                }
                else if (e is LcmInitializationException)
                {
                    MessageBoxUtils.Show(string.Format(FwCoreDlgs.kstidErrorNewDb, e.Message),
                                         FwUtils.ksSuiteName);
                }
                else
                {
                    throw new Exception(FwCoreDlgs.kstidErrApp, e);
                }
            }

            return(null);
        }
예제 #31
0
        /// <summary>
        /// Perform a backup of the current project, using specified settings.
        /// </summary>
        /// <returns>The backup file or null if something went wrong.</returns>
        public string BackupProject(IThreadedProgress progressDlg)
        {
            PersistBackupFileSettings();

            string backupFile = null;

            try
            {
                // Make sure any changes we want backup are saved.
                m_cache.ServiceLocator.GetInstance <IUndoStackManager>().Save();
                m_cache.ServiceLocator.GetInstance <IDataStorer>().CompleteAllCommits();

                string tempFilePath = ClientServerServices.Current.Local.CopyToXmlFile(m_cache, m_settings.DatabaseFolder);
                var    filesToZip   = CreateListOfFilesToZip();

                progressDlg.Title            = Strings.ksBackupProgressCaption;
                progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee;
                progressDlg.AllowCancel      = false;
                m_failedFiles.Clear();                 // I think it's always a new instance, but play safe.
                backupFile = (string)progressDlg.RunTask(true, BackupTask, filesToZip);
                if (m_failedFiles.Count > 0)
                {
                    var msg = string.Format(Strings.ksCouldNotBackupSomeFiles, m_failedFiles.ToString(", ", Path.GetFileName));
                    if (MessageBox.Show(progressDlg.Form, msg, Strings.ksWarning, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) !=
                        DialogResult.Yes)
                    {
                        File.Delete(backupFile);
                    }
                }
                if (tempFilePath != null)
                {
                    File.Delete(tempFilePath);                     // don't leave the extra fwdata file around to confuse things.
                }
            }
            catch (Exception e)
            {
                // Something went catastrophically wrong. Don't leave a junk backup around.
                if (backupFile != null)
                {
                    File.Delete(backupFile);
                }
                if (e is WorkerThreadException && e.InnerException is FwBackupException)
                {
                    throw e.InnerException;
                }
                throw new ContinuableErrorException("Backup did not succeed. Code is needed to handle this case.", e);
            }
            return(backupFile);
        }
 protected virtual void DoStage2Conversion(byte[] stage1, IThreadedProgress dlg)
 {
     using (var stage2Input = new MemoryStream(stage1))
     {
         var stage2Converter = new LinguaLinksImport(m_cache, null, null);
         // Until we have a better idea, assume we're half done with the import when we've produced the intermediate.
         // Allocate 5 progress units to the ImportInterlinear, in case it can do better resolution.
         // Enhance JohnT: we could divide the progress up based on the lengths of the files,
         // and possibly converter.Convert could move the bar along based on how far through the file it is.
         // ImportInterlinear could do something similar. However, procesing a single file is so quick
         // that this very crude approximation is good enough.
         dlg.Position += 50;
         stage2Converter.ImportInterlinear(dlg, stage2Input, 50, ref m_firstNewText);
     }
 }
예제 #33
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Perform a restore of the project specified in the settings.
		/// </summary>
		/// <param name="progressDlg">The progress dialog.</param>
		/// <exception cref="IOException">File does not exist, or some such problem</exception>
		/// <exception cref="InvalidBackupFileException">XML deserialization problem or required
		/// files not found in zip file</exception>
		/// ------------------------------------------------------------------------------------
		public void RestoreProject(IThreadedProgress progressDlg)
		{
			BackupFileSettings fileSettings = m_restoreSettings.Backup;
			fileSettings.Validate(); // Normally, this will already have been done, so this will do nothing.

			bool suppressConversion = false;

			//First of all, if the project exists and we are overwriting it, then make a copy of the project.  That way
			//if the restoration fails part way through, we can put it back the way it was.
			if (Directory.Exists(m_restoreSettings.ProjectPath))
			{
				// If the project already exists using the fwdata extension, either we're not sharing,
				// or it is a project for which sharing is suppressed. In any case we don't want to
				// convert the new project.
				suppressConversion = File.Exists(m_restoreSettings.FullProjectPath);
				CreateACopyOfTheProject();
			}

			//When restoring a project, ensure all the normal folders are there even if some
			//of those folders had nothing from them in the backup.
			Directory.CreateDirectory(m_restoreSettings.ProjectPath);
			FdoCache.CreateProjectSubfolders(m_restoreSettings.ProjectPath);

			try
			{
				//Import from FW version 6.0 based on the file extension.
				var extension = Path.GetExtension(fileSettings.File).ToLowerInvariant();
				if (extension == FdoFileHelper.ksFw60BackupFileExtension || extension == ".xml")
					ImportFrom6_0Backup(fileSettings, progressDlg);
				else     //Restore from FW version 7.0 and newer backup.
					RestoreFrom7_0AndNewerBackup(fileSettings);
			}
			catch (Exception error)
			{
				if (error is IOException || error is InvalidBackupFileException ||
					error is UnauthorizedAccessException)
				{
					CleanupAfterRestore(false);
				}
				throw;
			}

			// switch to the desired backend (if it's in the projects directory...anything else stays XML for now).
			if (Path.GetDirectoryName(m_restoreSettings.ProjectPath) == m_restoreSettings.ProjectsRootFolder && !suppressConversion)
				ClientServerServices.Current.Local.ConvertToDb4oBackendIfNeeded(progressDlg, m_restoreSettings.FullProjectPath);

			CleanupAfterRestore(true);
		}
예제 #34
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// The task to do in the background. We just increment the progress and sleep in
        /// between.
        /// </summary>
        /// <param name="progressDlg">The progress dialog.</param>
        /// <param name="parameters">The parameters. Not used.</param>
        /// <returns>Current progress</returns>
        /// ------------------------------------------------------------------------------------
        private static object BackgroundTask(IThreadedProgress progressDlg, object[] parameters)
        {
            int i = 0;

            for (; i < 10; i++)
            {
                if (progressDlg.Canceled)
                {
                    break;
                }

                progressDlg.Step(1);
                Thread.Sleep(1000);
            }

            return(i);
        }
예제 #35
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        ///	App-specific initialization of the cache.
        /// </summary>
        /// <param name="progressDlg">The progress dialog.</param>
        /// <returns>True if the initialize was successful, false otherwise</returns>
        /// ------------------------------------------------------------------------------------
        public override bool InitCacheForApp(IThreadedProgress progressDlg)
        {
            if (!TeScrInitializer.Initialize(Cache, this, progressDlg))
            {
                return(false);
            }

            // Make sure this DB uses the current stylesheet version, note categories & and key terms list
            IActionHandler actionHandler = Cache.ServiceLocator.GetInstance <IActionHandler>();

            NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(actionHandler,
                                                               () => TeScrInitializer.EnsureProjectComponentsValid(Cache, this, progressDlg));

            Cache.ServiceLocator.GetInstance <IParagraphCounterRepository>().RegisterViewTypeId <TeParaCounter>((int)TeViewGroup.Scripture);
            Cache.ServiceLocator.GetInstance <IParagraphCounterRepository>().RegisterViewTypeId <TeParaCounter>((int)TeViewGroup.Footnote);
            return(true);
        }
예제 #36
0
        private void ImportFrom6_0Backup(BackupFileSettings fileSettings, IThreadedProgress progressDlg)
        {
            ImportFrom6_0 importer = new ImportFrom6_0(progressDlg);
            string        projFile;

            if (!importer.Import(fileSettings.File, m_restoreSettings.ProjectName, out projFile))
            {
                ExceptionHelper.LogAndIgnoreErrors(() => CleanupFrom6_0FailedRestore(importer));
                ExceptionHelper.LogAndIgnoreErrors(() => CleanupAfterRestore(false));
                if (!importer.HaveOldFieldWorks || !importer.HaveFwSqlServer)
                {
                    throw new MissingOldFwException("Error restoring from FieldWorks 6.0 (or earlier) backup",
                                                    importer.HaveFwSqlServer, importer.HaveOldFieldWorks);
                }
                MessageBoxUtils.Show(Strings.ksRestoringOldFwBackupFailed, Strings.ksFailed);
                throw new FailedFwRestoreException("Error restoring from FieldWorks 6.0 (or earlier) backup");
            }
        }
예제 #37
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// If the current Scripture Note categories list version in the Db doesn't match that of
		/// the current XML file, update the DB.
		/// </summary>
		/// <param name="lp">The language project</param>
		/// <param name="existingProgressDlg">The existing progress dialog, if any.</param>
		/// ------------------------------------------------------------------------------------
		public static void EnsureCurrentScrNoteCategories(ILangProject lp,
			IThreadedProgress existingProgressDlg)
		{
			XmlNode scrNoteCategories = LoadScrNoteCategoriesDoc();
			IScripture scr = lp.TranslatedScriptureOA;
			Guid newVersion = Guid.Empty;
			try
			{
				XmlNode version = scrNoteCategories.Attributes.GetNamedItem("version");
				newVersion = new Guid(version.Value);
			}
			catch (Exception e)
			{
				ReportInvalidInstallation("List version attribute invalid in TeScrNoteCategories.xml", e);
			}
			if (scr.NoteCategoriesOA == null || newVersion != scr.NoteCategoriesOA.ListVersion)
			{
				existingProgressDlg.RunTask(CreateScrNoteCategories, scrNoteCategories, scr);
			}
		}
		public void StartFwRemoteDatabaseConnector()
		{
			// Change the Project Directory to some temporary directory to ensure, other units tests don't add projects
			// which would slow these tests down.
			m_oldProjectDirectory = FwDirectoryFinder.ProjectsDirectory;
			FwDirectoryFinder.ProjectsDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
			Directory.CreateDirectory(FwDirectoryFinder.ProjectsDirectory);

			FdoTestHelper.SetupStaticFdoProperties();

			m_projectShared = false;
			RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => m_projectShared, v => m_projectShared = v);

			var connectString = String.Format("tcp://{0}:{1}/FwRemoteDatabaseConnector.Db4oServerInfo",
				"127.0.0.1", Db4OPorts.ServerPort);
			m_db4OServerInfo = (Db4oServerInfo)Activator.GetObject(typeof(Db4oServerInfo), connectString);

			// Arbitrary method call to ensure db4oServerInfo is created on server.
			m_db4OServerInfo.AreProjectShared();

			m_progress = new DummyProgressDlg();
		}
예제 #39
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Convert the specified project (assumed to be in the current Projects directory)
		/// to the current backend. This is used in Restore and New Project and when turning
		/// ShareMyProjects on.
		/// </summary>
		/// <param name="progressDlg">The progress dialog (for getting a message box owner and/or
		/// ensuring we're invoking on the UI thread).</param>
		/// <param name="xmlFilename">The full path of the existing XML file for the project</param>
		/// <returns>The project identifier, typically the path to the converted file (or the
		/// original, if not configured for the client-server backend)</returns>
		/// ------------------------------------------------------------------------------------
		public string ConvertToDb4oBackendIfNeeded(IThreadedProgress progressDlg, string xmlFilename)
		{
			if (!ShareMyProjects)
				return xmlFilename; // no conversion needed.
			string desiredPath = Path.ChangeExtension(xmlFilename, FdoFileHelper.ksFwDataDb4oFileExtension);
			if (!EnsureNoClientsAreConnected(Path.GetFileNameWithoutExtension(desiredPath)))
				return null; // fail

			try
			{
				using (FdoCache tempCache = FdoCache.CreateCacheFromExistingData(new SimpleProjectId(FDOBackendProviderType.kXML, xmlFilename),
					"en", new SilentFdoUI(progressDlg.SynchronizeInvoke), m_dirs, new FdoSettings(), progressDlg))
				{

				// The zero in the object array is for db4o and causes it not to open a port.
				// This is fine since we aren't yet trying to start up on this restored database.
				// The null says we are creating the file on the local host.
					using (FdoCache copyCache = FdoCache.CreateCacheCopy(new SimpleProjectId(FDOBackendProviderType.kDb4oClientServer, desiredPath),
						"en", new SilentFdoUI(progressDlg.SynchronizeInvoke), m_dirs, new FdoSettings(), tempCache))
					{
						copyCache.ServiceLocator.GetInstance<IDataStorer>().Commit(new HashSet<ICmObjectOrSurrogate>(), new HashSet<ICmObjectOrSurrogate>(), new HashSet<ICmObjectId>());
						// Enhance JohnT: how can we tell this succeeded?
					}
				}
			}
			catch (Exception)
			{
				// If we couldn't convert it, try not to leave a corrupted file around.
				File.Delete(desiredPath);
				throw;
			}

			File.Delete(xmlFilename);
			return desiredPath;
		}
예제 #40
0
		/// -------------------------------------------------------------------------------------
		/// <summary>
		/// If the current stylesheet version in the Db doesn't match that of the current XML
		/// file, update the DB.
		/// </summary>
		/// <param name="cache">The FDO cache</param>
		/// <param name="progressDlg">The progress dialog from the splash screen</param>
		/// <param name="helpTopicProvider">A Help topic provider that can serve up a help topic
		/// that only exists in TE Help.</param>
		/// -------------------------------------------------------------------------------------
		public static void EnsureCurrentStylesheet(FdoCache cache, IThreadedProgress progressDlg,
			IHelpTopicProvider helpTopicProvider)
		{
			TeStylesXmlAccessor acc = new TeStylesXmlAccessor(cache.LangProject.TranslatedScriptureOA);
			acc.EnsureCurrentResource(progressDlg);

			// This class is used specifically for TE styles; FLEx *should* use a different class,
			// but per LT-14704, that is not the case. So always checking for current styles, but
			// suppressing a potentially confusing dialog when TE is not installed.
			if (acc.UserModifiedStyles.Count > 0 && FwUtils.IsTEInstalled)
			{
				using (FwStylesModifiedDlg dlg = new FwStylesModifiedDlg(acc.UserModifiedStyles,
					cache.ProjectId.UiName, helpTopicProvider))
				{
					dlg.ShowDialog();
				}
			}
		}
예제 #41
0
		/// <summary>
		/// Import from a LIFT file.
		/// </summary>
		/// <param name="progressDlg">The progress dialog.</param>
		/// <param name="parameters">The parameters: 1) filename</param>
		/// <returns></returns>
		private object ImportLIFT(IThreadedProgress progressDlg, params object[] parameters)
		{
			m_progressDlg = progressDlg;
			Debug.Assert(parameters.Length == 1);
			string sOrigFile = (string)parameters[0];
			try
			{
				// Create a temporary directory %temp%\TempForLIFTImport. Migrate as necessary and import from this
				// directory. Directory is left after import is done in case it is needed, but will be deleted next time
				// if it exists.
				var sLIFTfolder = Path.GetDirectoryName(sOrigFile);
				var sLIFTtempFolder = Path.Combine(Path.GetTempPath(), "TempForLIFTImport");
				if (Directory.Exists(sLIFTtempFolder) == true)
					Directory.Delete(sLIFTtempFolder, true);
				LdmlFileBackup.CopyDirectory(sLIFTfolder, sLIFTtempFolder);
				// Older LIFT files had ldml files in root directory. If found, move them to WritingSystem folder.
				if (Directory.GetFiles(sLIFTtempFolder, "*.ldml").Length > 0)
				{
					var sWritingSystems = Path.Combine(sLIFTtempFolder, "WritingSystems");
					if (Directory.Exists(sWritingSystems) == false)
						Directory.CreateDirectory(sWritingSystems);
					foreach (string filePath in Directory.GetFiles(sLIFTtempFolder, "*.ldml"))
					{
						string file = Path.GetFileName(filePath);
						if (!File.Exists(Path.Combine(sWritingSystems, file)))
							File.Move(filePath, Path.Combine(sWritingSystems, file));
					}
				}
				var sTempOrigFile = Path.Combine(sLIFTtempFolder, sOrigFile.Substring(sLIFTfolder.Length + 1));
				string sFilename;
				//Do a LIFT Migration to the current version of LIFT if it is needed.
				bool fMigrationNeeded = Migrator.IsMigrationNeeded(sTempOrigFile);
				if (fMigrationNeeded)
				{
					string sOldVersion = Validator.GetLiftVersion(sTempOrigFile);
					m_progressDlg.Message = String.Format(LexTextControls.ksMigratingLiftFile,
						sOldVersion, Validator.LiftVersion);
					sFilename = Migrator.MigrateToLatestVersion(sTempOrigFile);
				}
				else
				{
					sFilename = sTempOrigFile;
				}
				//Validate the LIFT file.
				if (!Validate(sFilename, sTempOrigFile))
					return null;

				//Import the LIFT file and ranges file.
				m_progressDlg.Message = LexTextControls.ksLoadingVariousLists;
				var flexImporter = new FlexLiftMerger(m_cache, m_msImport, m_chkTrustModTimes.Checked);
				var parser = new LiftParser<LiftObject, CmLiftEntry, CmLiftSense, CmLiftExample>(flexImporter);
				parser.SetTotalNumberSteps += parser_SetTotalNumberSteps;
				parser.SetStepsCompleted += parser_SetStepsCompleted;
				parser.SetProgressMessage += parser_SetProgressMessage;

				flexImporter.LiftFile = sTempOrigFile;

				//Before imporing the LIFT files ensure the LDML (language definition files) have the correct writing system codes.
				flexImporter.LdmlFilesMigration(sLIFTtempFolder, sFilename, sTempOrigFile + "-ranges");
				//Import the Ranges file.
				flexImporter.LoadLiftRanges(sTempOrigFile + "-ranges");	// temporary (?) fix for FWR-3869.
				//Import the LIFT data file.
				int cEntries = parser.ReadLiftFile(sFilename);

				if (fMigrationNeeded)
				{
					// Try to move the migrated file to the temp directory, even if a copy of it
					// already exists there.
					string sTempMigrated = Path.Combine(Path.GetTempPath(),
						Path.ChangeExtension(Path.GetFileName(sFilename), "." + Validator.LiftVersion + FwFileExtensions.ksLexiconInterchangeFormat));
					if (File.Exists(sTempMigrated))
						File.Delete(sTempMigrated);
					File.Move(sFilename, sTempMigrated);
				}
				flexImporter.ProcessPendingRelations(m_progressDlg);
				return flexImporter.DisplayNewListItems(sOrigFile, cEntries);
			}
			catch (Exception error)
			{
				string sMsg = String.Format(LexTextControls.ksLIFTImportProblem,
					sOrigFile, error.Message);
				try
				{
					StringBuilder bldr = new StringBuilder();
					// leave in English for programmer's sake...
					bldr.AppendFormat("Something went wrong while FieldWorks was attempting to import {0}.",
						sOrigFile);
					bldr.AppendLine();
					bldr.AppendLine(error.Message);
					bldr.AppendLine();
					bldr.AppendLine(error.StackTrace);

					if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
						ClipboardUtils.SetDataObject(bldr.ToString(), true);
					else
						progressDlg.SynchronizeInvoke.Invoke(() => ClipboardUtils.SetDataObject(bldr.ToString(), true));
						SIL.Utils.Logger.WriteEvent(bldr.ToString());
				}
				catch
				{
				}
				MessageBox.Show(sMsg, LexTextControls.ksProblemImporting,
					MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return null;
			}
		}
예제 #42
0
		/// <summary/>
		public override bool InitCacheForApp(IThreadedProgress progressDlg)
		{
			throw new System.NotImplementedException();
		}
예제 #43
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Converts all projects to db4o.
		/// </summary>
		/// <param name="progressDlg">The progress dialog box.</param>
		/// ------------------------------------------------------------------------------------
		private bool ConvertAllProjectsToDb4o(IThreadedProgress progressDlg)
		{
			progressDlg.Title = Strings.ksConvertingToShared;
			progressDlg.AllowCancel = false;
			progressDlg.Maximum = Directory.GetDirectories(m_dirs.ProjectsDirectory).Count();
			return (bool)progressDlg.RunTask(true, ConvertAllProjectsToDb4o);
		}
		/// <summary>
		/// Do the conversion. The signature of this method is required for use with ProgressDialogWithTask.RunTask,
		/// but the parameters and return result are not actually used.
		/// </summary>
		private object DoConversion(IThreadedProgress dlg, object[] parameters)
		{
			m_firstNewText = null;
			foreach (var path1 in InputFiles)
			{
				var path = path1.Trim();
				if (!File.Exists(path))
					continue; // report?
				var input = new ByteReader(path);
				var converterStage1 = GetSfmConverter();
				var stage1 = converterStage1.Convert(input, m_mappings, m_cache.WritingSystemFactory);
				// Skip actual import if SHIFT was held down.
				if (secretShiftText.Visible == true)
					continue;
				DoStage2Conversion(stage1, dlg);
			}
			return null;
		}
예제 #45
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Make sure all of the pages are laid out to and including the given page.
		/// </summary>
		/// <param name="pageIndex">page index to layout through</param>
		/// <param name="dpiX">The X dpi</param>
		/// <param name="dpiY">The Y dpi</param>
		/// <param name="dlg">Progress dialog to display the progress of the layout, null
		/// to not display one.</param>
		/// <returns>
		/// True if it did a layout of a page, false otherwise
		/// </returns>
		/// ------------------------------------------------------------------------------------
		protected bool LayoutToPageIfNeeded(int pageIndex, float dpiX, float dpiY, IThreadedProgress dlg)
		{
			lock (m_pages)
			{
				if (m_pages.Count == 0 || m_printerDpiX != dpiX || m_printerDpiY != dpiY)
				{
					m_printerDpiX = dpiX;
					m_printerDpiY = dpiY;
					CreatePages();
				}
			}

			// ENHANCE (TE-5651; EberhardB): right now we lay out everything up to the desired
			// page. This might take a loooong time if you have a large project. Now that we have
			// multiple divisions (and each book starting on a new page) it should be possible
			// to start with the page that starts the division that is on the desired page,
			// or go back through the divisions and start with the page that starts a
			// division that begins on a new page.
			bool fDidLayout = false;
			for (int iPage = 0; (iPage <= pageIndex) && (iPage < m_pages.Count); iPage++)
			{
				if (dlg != null)
				{
					dlg.Minimum = 0;
					dlg.Maximum = m_pages.Count;
					dlg.Message = string.Format(
						ResourceHelper.GetResourceString("kstidUpdatePageBreakPageCount"),
						iPage + 1, m_pages.Count);
				}

				// To be completely thread safe, we need to check the page count again
				// just in case the count changed while the lock was released.
				if (iPage < m_pages.Count && m_pages[iPage].LayOutIfNeeded())
				{
					if (dlg != null)
					{
						dlg.Position = iPage + 1;
						//Debug.WriteLine(string.Format("Page {0} of {1}", dlg.Value, dlg.Maximum));
						if (dlg.Canceled)
							break;
					}
					fDidLayout = true;
				}
			}

			return fDidLayout;
		}
예제 #46
0
		/// <summary>
		/// Method to be the task executed by ProgressDialogWithTask.RunTask; must have this exact signature.
		/// Takes two parameters, as indicated by the first two lines of code.
		/// </summary>
		/// <returns>true if completed, false if canceled</returns>
		private object ExtractFile(IThreadedProgress progressDlg, object[] parameters)
		{
			var stream = (Stream)parameters[0];
			FileStream tempStream = (FileStream)parameters[1];
			progressDlg.Message = (string)parameters[2];
			const int interval = 100000; // update progress every 100K.
			int count = 0;
			for (int oneByte = stream.ReadByte(); oneByte != -1; oneByte = stream.ReadByte())
			{
				tempStream.WriteByte((byte) oneByte);
				if (count++ % interval == 0)
				{
					progressDlg.Position = count;
					if (progressDlg.Canceled)
						return false;
				}
			}
			return true;
		}
예제 #47
0
		/// <summary>
		/// Method to be the task executed by ProgressDialogWithTask.RunTask; must have this exact signature.
		/// Takes one parameter, as indicated by the first line of code.
		/// </summary>
		/// <returns>true if completed, false if canceled</returns>
		public object ProcessFile(IThreadedProgress progressDlg, object[] parameters)
		{
			var process = (Process) parameters[0];
			progressDlg.Message = (string)parameters[1];
			m_errorMessages = "";
			m_stdoutBldr = new StringBuilder();
			process.Start();
			process.BeginErrorReadLine();
			process.BeginOutputReadLine();
			while (!process.WaitForExit(300))
			{
				if (progressDlg.Canceled)
				{
					process.Kill();
					process.WaitForExit();
					return false;
				}
			}
			return true;
		}
예제 #48
0
		/// <summary>
		/// Constructor.
		/// </summary>
		public ImportFrom6_0(IThreadedProgress progressDlg, string converterConsolePath, string dbPath)
			: this(progressDlg, converterConsolePath, dbPath, false)
		{
		}
예제 #49
0
			protected override DialogResult ShowPossibleMergeDialog(IThreadedProgress progress)
			{
				NumTimesDlgShown++;
				return DialogResult.No;
			}
예제 #50
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Converts all projects to XML.
		/// </summary>
		/// <returns><c>true</c> if successful; <c>false</c> if other clients are connected,
		/// which prevents conversion of shared projects.</returns>
		/// ------------------------------------------------------------------------------------
		private bool ConvertAllProjectsToXml(IThreadedProgress progressDlg)
		{
			if (!EnsureNoClientsAreConnected())
				return false;

			progressDlg.Title = Strings.ksConvertingToNonShared;
			progressDlg.AllowCancel = false;
			progressDlg.Maximum = Directory.GetDirectories(m_dirs.ProjectsDirectory).Count();
			progressDlg.RunTask(true, ConvertAllProjectsToXmlTask);
			return true;
		}
예제 #51
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Backs up the project.
		/// </summary>
		/// <returns>The path to the backup file, or <c>null</c></returns>
		/// ------------------------------------------------------------------------------------
		internal string BackupProject(IThreadedProgress progressDlg)
		{
			BackupProjectSettings settings = new BackupProjectSettings(m_cache, m_backupProjectView, FwDirectoryFinder.DefaultBackupDirectory);
			settings.DestinationFolder = m_backupProjectView.DestinationFolder;
			settings.AppAbbrev = m_appAbbrev;

			ProjectBackupService backupService = new ProjectBackupService(m_cache, settings);
			string backupFile;
			if (!backupService.BackupProject(progressDlg, out backupFile))
			{
				string msg = string.Format(FwCoreDlgs.ksCouldNotBackupSomeFiles, backupService.FailedFiles.ToString(", ", Path.GetFileName));
				if (MessageBox.Show(msg, FwCoreDlgs.ksWarning, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
					File.Delete(backupFile);
				backupFile = null;
			}
			return backupFile;
		}
예제 #52
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// If the current stylesheet version in the Db doesn't match that of the current XML
		/// file, update the DB.
		/// </summary>
		/// <param name="lp">The language project</param>
		/// <param name="progressDlg">The progress dialog.</param>
		/// ------------------------------------------------------------------------------------
		public static void EnsureCurrentStylesheet(ILangProject lp, IThreadedProgress progressDlg)
		{
			// We don't need to establish a NonUndoableUnitOfWork here because caller has already
			// done it and if not, the internal code of StylesXmlAccessor will do it for us.
			var acc = new FlexStylesXmlAccessor(lp.LexDbOA);
			acc.EnsureCurrentResource(progressDlg);
		}
예제 #53
0
		private object ConvertAllProjectsToDb4o(IThreadedProgress progress, object[] args)
		{
			for (; ; )
			{
				string projects = "";
				foreach (string projectFolder in Directory.GetDirectories(m_dirs.ProjectsDirectory))
				{
					var projectName = Path.GetFileName(projectFolder);
					var projectPath = Path.Combine(projectFolder, FdoFileHelper.GetXmlDataFileName(projectName));
					var suppressPath = Path.Combine(projectFolder, ksDoNotShareProjectTxt);
					if (!File.Exists(projectPath) || File.Exists(suppressPath))
						continue; // not going to convert, it isn't a problem.
					if (XMLBackendProvider.IsProjectLocked(projectPath))
						projects = projects + projectName + ", ";
				}
				if (projects.Length == 0)
					break;
				projects = projects.Substring(0, projects.Length - ", ".Length);

				if (!m_ui.Retry(string.Format(Strings.ksMustCloseProjectsToShare, projects), Strings.ksConvertingToShared))
					return false;
			}
			foreach (string projectFolder in Directory.GetDirectories(m_dirs.ProjectsDirectory))
			{
				string projectName = Path.GetFileName(projectFolder);
				string projectPath = Path.Combine(projectFolder, FdoFileHelper.GetXmlDataFileName(projectName));
				var suppressPath = Path.Combine(projectFolder, ksDoNotShareProjectTxt);
				progress.Message = Path.GetFileNameWithoutExtension(projectPath);
				if (File.Exists(projectPath) && !File.Exists(suppressPath))
				{
					try
					{
						ConvertToDb4oBackendIfNeeded(progress, projectPath);
					}
					catch (Exception e)
					{
						ReportConversionError(projectPath, e);
					}
				}
				progress.Step(1);
			}
			return true;
		}
예제 #54
0
		/// --------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// <param name="progressDlg"></param>
		/// --------------------------------------------------------------------------------
		new public void DetectDifferences(IThreadedProgress progressDlg)
		{
			base.DetectDifferences(new DummyProgressDlg());

			//PrintDiffSummary();
		}
예제 #55
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Updates the page breaks.
		/// </summary>
		/// <param name="dialog">The progress dialog.</param>
		/// <param name="parameters">Float X dpi as first parameter, float Y dpi as second</param>
		/// ------------------------------------------------------------------------------------
		private object UpdatePageBreaks(IThreadedProgress dialog, object[] parameters)
		{
			Debug.Assert(parameters.Length == 2);
			float dpiX = (float)parameters[0];
			float dpiY = (float)parameters[1];
			while (true)
			{
				if (dialog.Canceled)
					break;
				bool moreLayoutRequired;
				if (InvokeRequired)
					moreLayoutRequired = (bool)Invoke((Func<bool>)(() => LayoutToPageIfNeeded(m_pages.Count - 1, dpiX, dpiY, dialog)));
				else
					moreLayoutRequired = LayoutToPageIfNeeded(m_pages.Count - 1, dpiX, dpiY, dialog);
				if (!moreLayoutRequired)
					break;
			}
			return null;
		}
예제 #56
0
		bool DummyCheckAndAddLanguagesInternal(FdoCache cache, Interlineartext interlinText, ILgWritingSystemFactory wsFactory, IThreadedProgress progress)
		{
			return true;
		}
예제 #57
0
		private object ConvertAllProjectsToXmlTask(IThreadedProgress progress, object[] args)
		{
			foreach (string projectFolder in Directory.GetDirectories(m_dirs.ProjectsDirectory))
			{
				var projectName = Path.GetFileName(projectFolder);
				var projectPath = Path.Combine(projectFolder, FdoFileHelper.GetDb4oDataFileName(projectName));
				progress.Message = Path.GetFileNameWithoutExtension(projectPath);
				if (File.Exists(projectPath))
				{
					try
					{
						// The zero in the object array is for db4o and causes it not to open a port.
						// This is fine since we aren't yet trying to start up on this restored database.
						// The null says we are creating the file on the local host.
						using (FdoCache tempCache = FdoCache.CreateCacheFromExistingData(
							new SimpleProjectId(FDOBackendProviderType.kDb4oClientServer, projectPath), "en", new SilentFdoUI(progress.SynchronizeInvoke),
							m_dirs, new FdoSettings(), progress))
						{
							CopyToXmlFile(tempCache, tempCache.ProjectId.ProjectFolder);
						// Enhance JohnT: how can we tell this succeeded?
						}
						File.Delete(projectPath); // only if we converted successfully; otherwise will throw.
					}
					catch (Exception e)
					{
						ReportConversionError(projectPath, e);
					}
				}
				progress.Step(1);
			}
			return null;
		}
예제 #58
0
		private object DoExportWithProgress(IThreadedProgress progressDlg, params object[] args)
		{
			var outPath = (string)args[0];
			var fxtPath = (string)args[1];

			if (m_objs.Count == 0)
				m_objs.Add(m_objRoot);

			var ddNode = m_ddNodes[NodeIndex(fxtPath)];
			var mode = XmlUtils.GetOptionalAttributeValue(ddNode, "mode", "xml");
			using (new WaitCursor(this))
			{
				try
				{
					InterlinearExporter exporter;
					ExportPhase1(mode, out exporter, outPath);
					string rootDir = FwDirectoryFinder.CodeDirectory;
					string transform = XmlUtils.GetOptionalAttributeValue(ddNode, "transform", "");
					string sTransformPath = Path.Combine(rootDir,
							String.Format("Language Explorer{0}Export Templates{0}Interlinear",
							Path.DirectorySeparatorChar));
					switch (mode)
					{
						// ReSharper disable RedundantCaseLabel
						default:
						case "doNothing":
						case "xml":
						case "elan":
							// no further processing needed.
							break;
						// ReSharper restore RedundantCaseLabel
						case "applySingleTransform":
							string sTransform = Path.Combine(sTransformPath, transform);
							exporter.PostProcess(sTransform, outPath, 1);
							break;
						case "openOffice":
							string tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
							// Paranoia...probably GetRandomFileName will never make the name of an existing folder, but make sure of it.
							while (Directory.Exists(tempDir))
								tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
							Directory.CreateDirectory(tempDir);
							try
							{
								var xsl = new XslCompiledTransform();
								var implementation = XmlUtils.GetFirstNonCommentChild(ddNode);
								var styleFileTransform = "xml2OOStyles.xsl";
								if (implementation != null)
									styleFileTransform = XmlUtils.GetOptionalAttributeValue(implementation,
																							"styleTransform",
																							styleFileTransform);
								xsl.Load(Path.Combine(sTransformPath, styleFileTransform));
								xsl.Transform(outPath, Path.Combine(tempDir, "styles.xml"));

								// Now generate the content. Do this after using outPath as the source above, because it renames the file.
								string contentFileTransform = "xml2OO.xsl";
								if (implementation != null)
									contentFileTransform = XmlUtils.GetOptionalAttributeValue(implementation,
																							  "contentTransform",
																							  contentFileTransform);
#pragma warning disable 219 // ReSharper disable UnusedVariable
								var xsl2 = new XslCompiledTransform();
#pragma warning restore 219 // ReSharper restore UnusedVariable
								xsl.Load(Path.Combine(sTransformPath, contentFileTransform));
								xsl.Transform(outPath, Path.Combine(tempDir, "content.xml"));
								string mimetypePath = Path.Combine(tempDir, "mimetype");
								File.Copy(Path.Combine(sTransformPath, "mimetype"),
										  mimetypePath);
								File.SetAttributes(mimetypePath, File.GetAttributes(mimetypePath) & ~FileAttributes.ReadOnly);
								string manifestDir = Path.Combine(tempDir, "META-INF");
								string manifestPath = Path.Combine(manifestDir, "manifest.xml");
								Directory.CreateDirectory(manifestDir);
								File.Copy(Path.Combine(sTransformPath, "manifest.xml"),
										  manifestPath);
								File.SetAttributes(manifestPath, File.GetAttributes(manifestPath) & ~FileAttributes.ReadOnly);
								FastZip zf = new FastZip();
								zf.CreateZip(outPath, tempDir, true, string.Empty);
							}
							finally
							{
								Directory.Delete(tempDir, true);
							}
							break;
					}
				}
				catch (Exception e)
				{
					MessageBox.Show(this, string.Format(ITextStrings.ksExportErrorMsg, e.Message));
				}
			}
			return null;
		}
		protected virtual void DoStage2Conversion(byte[] stage1, IThreadedProgress dlg)
		{
			using (var stage2Input = new MemoryStream(stage1))
			{
				var stage2Converter = new LinguaLinksImport(m_cache, null, null);
				// Until we have a better idea, assume we're half done with the import when we've produced the intermediate.
				// Allocate 5 progress units to the ImportInterlinear, in case it can do better resolution.
				// Enhance JohnT: we could divide the progress up based on the lengths of the files,
				// and possibly converter.Convert could move the bar along based on how far through the file it is.
				// ImportInterlinear could do something similar. However, procesing a single file is so quick
				// that this very crude approximation is good enough.
				dlg.Position += 50;
				stage2Converter.ImportInterlinear(dlg, stage2Input, 50, ref m_firstNewText);
			}
		}
예제 #60
0
		private void ImportFrom6_0Backup(BackupFileSettings fileSettings, IThreadedProgress progressDlg)
		{
			var importer = new ImportFrom6_0(progressDlg, m_converterConsolePath, m_dbPath);
			bool importSuccessful;
			try
			{
				string projFile;
				importSuccessful = importer.Import(fileSettings.File, m_restoreSettings.ProjectName, m_restoreSettings.ProjectsRootFolder, out projFile);
			}
			catch (CannotConvertException e)
			{
				FailedImportCleanUp(importer);
				throw;
			}
			if (!importSuccessful)
			{
				FailedImportCleanUp(importer);

				if (!importer.HaveOldFieldWorks || !importer.HaveFwSqlServer)
				{
					throw new MissingOldFwException("Error restoring from FieldWorks 6.0 (or earlier) backup",
						importer.HaveFwSqlServer, importer.HaveOldFieldWorks);
				}
				throw new FailedFwRestoreException("Error restoring from FieldWorks 6.0 (or earlier) backup");
			}
		}