private void UncompressLinkedFiles(Dictionary <String, DateTime> fileList, String destinationLinkedFilesPath,
                                           String linkedFilesPathPersisted)
        {
            using (var zipIn = OpenFWBackupZipfile())
            {
                ZipEntry entry;

                while ((entry = zipIn.GetNextEntry()) != null)
                {
                    //Code to use for restoring files with new file structure.
                    if (!fileList.ContainsKey(entry.Name))
                    {
                        continue;
                    }
                    var fileName = Path.GetFileName(entry.Name);
                    Debug.Assert(!String.IsNullOrEmpty(fileName));

                    //Contruct the path where the file will be unzipped too.
                    var    zipFileLinkFilesPath   = LcmFileHelper.GetZipfileFormattedPath(linkedFilesPathPersisted);
                    var    filenameWithSubFolders = entry.Name.Substring(zipFileLinkFilesPath.Length);
                    String pathForFileSubFolders  = "";
                    if (!fileName.Equals(filenameWithSubFolders))                     //if they are equal the file is in the root of LinkedFiles
                    {
                        pathForFileSubFolders = GetPathForSubFolders(filenameWithSubFolders, fileName.Length);
                    }
                    var destFolderZipFileFormat = LcmFileHelper.GetZipfileFormattedPath(destinationLinkedFilesPath);
                    var pathRoot = Path.GetPathRoot(destinationLinkedFilesPath);
                    Debug.Assert(!String.IsNullOrEmpty(pathRoot));
                    var pathforfileunzip = Path.Combine(pathRoot, destFolderZipFileFormat, pathForFileSubFolders);
                    UnzipFileToRestoreFolder(zipIn, fileName, entry.Size, pathforfileunzip, entry.DateTime);
                }
            }
        }
Exemple #2
0
        public void GatherBuiltInAndUserConfigurations_ProjectOverrideReplacesShipped()
        {
            var configObjectName         = "Dictionary";
            var projectDictionaryConfigs =
                Path.Combine(LcmFileHelper.GetConfigSettingsDir(Cache.ProjectId.ProjectFolder),
                             "Dictionary");

            Directory.CreateDirectory(projectDictionaryConfigs);
            using (var tempConfigFile = TempFile.WithFilename(Path.Combine(projectDictionaryConfigs, "Override" + DictionaryConfigurationModel.FileExtension)))
            {
                string firstShippedConfigName;
                var    shippedFileList = Directory.EnumerateFiles(Path.Combine(FwDirectoryFinder.DefaultConfigurations, "Dictionary"),
                                                                  "*" + DictionaryConfigurationModel.FileExtension);
                var fileList = shippedFileList.ToArray();
                using (var stream = new FileStream(fileList.First(), FileMode.Open))
                {
                    var doc = new XmlDocument();
                    doc.Load(stream);
                    var node = doc.SelectSingleNode("DictionaryConfiguration");
                    firstShippedConfigName = node.Attributes["name"].Value;
                }

                File.WriteAllText(tempConfigFile.Path,
                                  "<?xml version='1.0' encoding='utf-8'?><DictionaryConfiguration name='" +
                                  firstShippedConfigName + "'/>");
                // SUT
                var fileListFromResults = DictionaryConfigurationUtils.GatherBuiltInAndUserConfigurations(Cache, configObjectName).Values;
                CollectionAssert.Contains(fileListFromResults, tempConfigFile.Path);
                Assert.AreEqual(fileListFromResults.Count, fileList.Count(),
                                "Override was added instead of replacing a shipped config.");
            }
        }
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Uncompress the FieldWorks project data file and the Questions files.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 private void UncompressDataFiles()
 {
     using (var zipIn = OpenFWBackupZipfile())
     {
         ZipEntry entry;
         while ((entry = zipIn.GetNextEntry()) != null)
         {
             var fileName = Path.GetFileName(entry.Name);
             if (fileName == LcmFileHelper.GetXmlDataFileName(m_restoreSettings.Backup.ProjectName))
             {
                 UnzipFileToRestoreFolder(zipIn, m_restoreSettings.DbFilename, entry.Size,
                                          m_restoreSettings.ProjectPath, entry.DateTime);
             }
             if (fileName == m_restoreSettings.QuestionNotesFilename)
             {
                 UnzipFileToRestoreFolder(zipIn, m_restoreSettings.QuestionNotesFilename, entry.Size,
                                          m_restoreSettings.ProjectPath, entry.DateTime);
             }
         }
         string bakFile = Path.Combine(m_restoreSettings.ProjectPath, m_restoreSettings.ProjectName)
                          + LcmFileHelper.ksFwDataFallbackFileExtension;
         if (FileUtils.TrySimilarFileExists(bakFile, out bakFile))
         {
             FileUtils.Delete(bakFile);                     // TODO: do something about the .Lock file.......
         }
     }
 }
 /// <summary>
 /// Restore LinkedFiles to the project or a non-standard location depending on the
 /// fPutFilesInProject parameter.
 /// </summary>
 /// <param name="fPutFilesInProject"></param>
 /// <param name="filesContainedInLinkdFilesFolder"></param>
 /// <param name="linkedFilesPathInZip"></param>
 /// <param name="proposedDestinationLinkedFilesPath"></param>
 protected void RestoreLinkedFiles(bool fPutFilesInProject, Dictionary <string, DateTime> filesContainedInLinkdFilesFolder,
                                   string linkedFilesPathInZip, string proposedDestinationLinkedFilesPath)
 {
     if (fPutFilesInProject)
     {
         m_sLinkDirChangedTo = LcmFileHelper.GetDefaultLinkedFilesDir(m_restoreSettings.ProjectPath);
         //Restore the files to the project folder.
         UncompressLinkedFiles(filesContainedInLinkdFilesFolder, m_sLinkDirChangedTo, linkedFilesPathInZip);
     }
     else
     {
         if (!Directory.Exists(proposedDestinationLinkedFilesPath))
         {
             try
             {
                 Directory.CreateDirectory(proposedDestinationLinkedFilesPath);
             }
             catch (Exception)
             {
                 CouldNotRestoreLinkedFilesToOriginalLocation(linkedFilesPathInZip, filesContainedInLinkdFilesFolder);
                 return;
             }
         }
         UncompressLinkedFiles(filesContainedInLinkdFilesFolder, proposedDestinationLinkedFilesPath, linkedFilesPathInZip);
     }
 }
Exemple #5
0
        public void MigrateOldConfigurationsIfNeeded_MatchesLabelsWhenUIIsLocalized()
        {
            // Localize a Part's label to German (sufficient to cause a mismatched nodes crash if one config's labels are localized)
            var localizedPartLabels = new Dictionary <string, string>();

            localizedPartLabels["Main Entry"] = "Haupteintrag";
            var pathsToL10NStrings = (Dictionary <string, Dictionary <string, string> >)ReflectionHelper.GetField(StringTable.Table, "m_pathsToStrings");

            pathsToL10NStrings["group[@id = 'LocalizedAttributes']/"] = localizedPartLabels;

            var configSettingsDir = LcmFileHelper.GetConfigSettingsDir(Path.GetDirectoryName(Cache.ProjectId.Path));
            var newConfigFilePath = Path.Combine(configSettingsDir, DictionaryConfigurationListener.DictionaryConfigurationDirectoryName,
                                                 "Lexeme" + DictionaryConfigurationModel.FileExtension);

            Assert.False(File.Exists(newConfigFilePath), "should not yet be migrated");
            Directory.CreateDirectory(configSettingsDir);
            File.WriteAllLines(Path.Combine(configSettingsDir, "Test.fwlayout"), new[] {
                @"<layoutType label='Lexeme-based (complex forms as main entries)' layout='publishStem'><configure class='LexEntry' label='Main Entry' layout='publishStemEntry' />",
                @"<configure class='LexEntry' label='Minor Entry' layout='publishStemMinorEntry' hideConfig='true' /></layoutType>'"
            });
            var migrator = new DictionaryConfigurationMigrator(m_propertyTable, m_mediator);

            Assert.DoesNotThrow(() => migrator.MigrateOldConfigurationsIfNeeded(), "ArgumentException indicates localized labels.");             // SUT
            var updatedConfigModel = new DictionaryConfigurationModel(newConfigFilePath, Cache);

            Assert.AreEqual(2, updatedConfigModel.Parts.Count, "Should have 2 top-level nodes");
            Assert.AreEqual("Main Entry", updatedConfigModel.Parts[0].Label);
            RobustIO.DeleteDirectoryAndContents(configSettingsDir);
        }
Exemple #6
0
        public void MigrateIfNeeded(SimpleLogger logger, PropertyTable propertyTable, string appVersion)
        {
            m_logger = logger;
            Cache    = propertyTable.GetValue <LcmCache>("cache");
            var foundOne = string.Format("{0}: Configuration was found in need of migration. - {1}",
                                         appVersion, DateTime.Now.ToString("yyyy MMM d h:mm:ss"));
            var configSettingsDir   = LcmFileHelper.GetConfigSettingsDir(Cache.ProjectId.ProjectFolder);
            var dictionaryConfigLoc = Path.Combine(configSettingsDir, DictionaryConfigurationListener.DictionaryConfigurationDirectoryName);
            var stemPath            = Path.Combine(dictionaryConfigLoc, "Stem" + DictionaryConfigurationModel.FileExtension);
            var lexemePath          = Path.Combine(dictionaryConfigLoc, "Lexeme" + DictionaryConfigurationModel.FileExtension);

            if (File.Exists(stemPath) && !File.Exists(lexemePath))
            {
                File.Move(stemPath, lexemePath);
            }
            RenameReversalConfigFiles(configSettingsDir);
            foreach (var config in DCM.GetConfigsNeedingMigration(Cache, DCM.VersionCurrent))
            {
                m_logger.WriteLine(foundOne);
                if (config.Label.StartsWith("Stem-"))
                {
                    config.Label = config.Label.Replace("Stem-", "Lexeme-");
                }
                m_logger.WriteLine(string.Format("Migrating {0} configuration '{1}' from version {2} to {3}.",
                                                 config.Type, config.Label, config.Version, DCM.VersionCurrent));
                m_logger.IncreaseIndent();
                MigrateFrom83Alpha(logger, config, LoadBetaDefaultForAlphaConfig(config));
                config.Save();
                m_logger.DecreaseIndent();
            }
        }
Exemple #7
0
        private string CreateNewSoundFilename(out string path)
        {
            var obj      = m_innerView.Cache.ServiceLocator.GetObject(m_innerView.HvoObj);
            var mediaDir = LcmFileHelper.GetMediaDir(m_innerView.Cache.LangProject.LinkedFilesRootDir);

            Directory.CreateDirectory(mediaDir);             // Palaso media library does not cope if it does not exist.
            // Make up a unique file name for the new recording. It starts with the shortname of the object
            // so as to somewhat link them together, then adds a unique timestamp, then if by any chance
            // that exists it keeps trying.
            var baseNameForFile = obj.ShortName ?? string.Empty;

            // LT-12926: Path.ChangeExtension checks for invalid filename chars,
            // so we need to fix the filename before calling it.
            foreach (var c in Path.GetInvalidFileNameChars())
            {
                baseNameForFile = baseNameForFile.Replace(c, '_');
            }
            // WeSay and most other programs use NFC for file names, so we'll standardize on this.
            baseNameForFile = baseNameForFile.Normalize(NormalizationForm.FormC);
            string filename;

            do
            {
                filename = baseNameForFile;
                filename = Path.ChangeExtension(DateTime.UtcNow.Ticks + filename, "wav");
                path     = Path.Combine(mediaDir, filename);
            } while (File.Exists(path));
            return(filename);
        }
Exemple #8
0
        public void NameAndPath()
        {
            string    myProjectFolder = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "My.Project");
            ProjectId projId          = new ProjectId(BackendProviderType.kXML, "My.Project");

            Assert.AreEqual(Path.Combine(myProjectFolder, LcmFileHelper.GetXmlDataFileName("My.Project")), projId.Path);
            Assert.AreEqual("My.Project", projId.Name);
        }
Exemple #9
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="backupProjectView">The backup project dialog box.</param>
        /// <param name="cache">The cache.</param>
        /// ------------------------------------------------------------------------------------
        internal BackupProjectPresenter(IBackupProjectView backupProjectView, LcmCache cache)
        {
            m_cache             = cache;
            m_backupProjectView = backupProjectView;

            //Older projects might not have this folder so when launching the backup dialog we want to create it.
            Directory.CreateDirectory(LcmFileHelper.GetSupportingFilesDir(m_cache.ProjectId.ProjectFolder));
        }
Exemple #10
0
        public void AssertValid_Valid()
        {
            string projFile = GetXmlProjectFilename("monkey");

            m_mockFileOs.AddExistingFile(projFile);

            var proj = new ProjectId(LcmFileHelper.GetXmlDataFileName("monkey"));

            proj.AssertValid();             // no exception should be thrown here for a valid project.
        }
Exemple #11
0
        public void IsValid_XML_True()
        {
            const string sProjectName = "monkey";
            string       sFile        = LcmFileHelper.GetXmlDataFileName(sProjectName);

            m_mockFileOs.AddExistingFile(GetXmlProjectFilename(sProjectName));
            ProjectId proj = new ProjectId("xml", sFile);

            Assert.IsTrue(proj.IsValid);
        }
Exemple #12
0
        public void IsValid_NullType()
        {
            const string sProjectName = "monkey";
            string       sFile        = LcmFileHelper.GetXmlDataFileName(sProjectName);

            m_mockFileOs.AddExistingFile(GetXmlProjectFilename(sProjectName));
            ProjectId proj = new ProjectId(null, sFile);

            Assert.AreEqual(BackendProviderType.kXML, proj.Type);
            Assert.IsTrue(proj.IsValid);
        }
Exemple #13
0
        internal static List <DictionaryConfigurationModel> GetConfigsNeedingMigration(LcmCache cache, int targetVersion)
        {
            var configSettingsDir      = LcmFileHelper.GetConfigSettingsDir(cache.ProjectId.ProjectFolder);
            var dictionaryConfigLoc    = Path.Combine(configSettingsDir, DictionaryConfigurationListener.DictionaryConfigurationDirectoryName);
            var reversalIndexConfigLoc = Path.Combine(configSettingsDir, DictionaryConfigurationListener.ReversalIndexConfigurationDirectoryName);
            var projectConfigPaths     = new List <string>(ConfigFilesInDir(dictionaryConfigLoc));

            projectConfigPaths.AddRange(ConfigFilesInDir(reversalIndexConfigLoc));
            return(projectConfigPaths.Select(path => new DictionaryConfigurationModel(path, null))
                   .Where(model => model.Version < targetVersion).ToList());
        }
Exemple #14
0
        public void CleanUpNameForType_XML_onlyNameWithExtension()
        {
            string expectedPath = GetXmlProjectFilename("monkey");

            m_mockFileOs.AddExistingFile(expectedPath);

            var proj = new ProjectId(LcmFileHelper.GetXmlDataFileName("monkey"));

            Assert.AreEqual(expectedPath, proj.Path);
            Assert.AreEqual(BackendProviderType.kXML, proj.Type);
            Assert.IsTrue(proj.IsValid);
        }
Exemple #15
0
        public void CleanUpNameForType_XML_FullPath()
        {
            string expectedPath = Path.Combine(FwDirectoryFinder.ProjectsDirectory, LcmFileHelper.GetXmlDataFileName("monkey"));

            m_mockFileOs.AddExistingFile(expectedPath);

            var proj = new ProjectId(expectedPath);

            Assert.AreEqual(expectedPath, proj.Path);
            Assert.AreEqual(BackendProviderType.kXML, proj.Type);
            Assert.IsTrue(proj.IsValid);
        }
Exemple #16
0
 public void GetValidConfigurationForPublication_PublicationThatMatchesNoConfigReturnsNull()
 {
     using (var helper = new UndoableUnitOfWorkHelper(Cache.ActionHandlerAccessor, "doit", "undoit"))
     {
         var testPubItem = Cache.ServiceLocator.GetInstance <ICmPossibilityFactory>().Create();
         int enId        = Cache.WritingSystemFactory.GetWsFromStr("en");
         var testPubName = TsStringUtils.MakeString("NotTheTestPub", enId);
         Cache.LangProject.LexDbOA.PublicationTypesOA.PossibilitiesOS.Add(testPubItem);
         testPubItem.Name.set_String(enId, testPubName);
         var configSansTestPub = ConfigurationTemplate.Replace("</Publications>",
                                                               "<Publication>NotTheTestPub</Publication></Publications>");
         var overrideFiles = new List <TempFile>();
         using (var docView = new TestXhtmlDocView())
         {
             docView.SetConfigObjectName("Dictionary");
             docView.SetMediator(m_mediator);
             docView.SetPropertyTable(m_propertyTable);
             var projConfigs = Path.Combine(LcmFileHelper.GetConfigSettingsDir(Cache.ProjectId.ProjectFolder),
                                            "Dictionary");
             Directory.CreateDirectory(projConfigs);
             // override every shipped config with a config that does not have the TestPub publication
             var shippedFileList = Directory.EnumerateFiles(Path.Combine(FwDirectoryFinder.DefaultConfigurations, "Dictionary"),
                                                            "*" + DictionaryConfigurationModel.FileExtension);
             var overrideCount = 0;
             foreach (var shippedFile in shippedFileList)
             {
                 ++overrideCount;
                 var tempFileName   = Path.Combine(projConfigs, overrideCount + DictionaryConfigurationModel.FileExtension);
                 var tempConfigFile = TempFile.WithFilename(tempFileName);
                 overrideFiles.Add(tempConfigFile);
                 using (var stream = new FileStream(shippedFile, FileMode.Open))
                 {
                     var doc = new XmlDocument();
                     doc.Load(stream);
                     var node        = doc.SelectSingleNode("DictionaryConfiguration");
                     var shippedName = node.Attributes["name"].Value;
                     File.WriteAllText(tempConfigFile.Path,
                                       configSansTestPub.Replace("name='AConfigPubtest'", "name='" + shippedName + "'"));
                 }
             }
             // SUT
             var result = docView.GetValidConfigurationForPublication("TestPub");
             // Delete all our temp files before asserting so they are sure to go away
             foreach (var tempFile in overrideFiles)
             {
                 tempFile.Dispose();
             }
             Assert.IsNull(result, "When no configurations have the publication null should be returned.");
         }
     }
 }
Exemple #17
0
        public void CleanUpNameForType_Default_onlyName()
        {
            m_defaultBepType = BackendProviderType.kXML;
            string expectedPath = Path.Combine(Path.Combine(FwDirectoryFinder.ProjectsDirectory, "ape"),
                                               LcmFileHelper.GetXmlDataFileName("ape"));

            m_mockFileOs.AddExistingFile(expectedPath);

            ProjectId proj = new ProjectId("ape");

            Assert.AreEqual(expectedPath, proj.Path);
            Assert.AreEqual(BackendProviderType.kXML, proj.Type);
            Assert.IsTrue(proj.IsValid);
        }
Exemple #18
0
        public void AssertValid_Invalid_FileNotFound()
        {
            var proj = new ProjectId(LcmFileHelper.GetXmlDataFileName("notfound"));

            try
            {
                proj.AssertValid();
                Assert.Fail("FwStartupException expected");
            }
            catch (StartupException exception)
            {
                Assert.IsTrue(exception.ReportToUser);
            }
        }
Exemple #19
0
        public void AssertValid_InvalidProjectType()
        {
            var proj = new ProjectId(BackendProviderType.kInvalid, LcmFileHelper.GetXmlDataFileName("invalid"));

            try
            {
                proj.AssertValid();
                Assert.Fail("FwStartupException expected");
            }
            catch (StartupException exception)
            {
                Assert.IsTrue(exception.ReportToUser);
            }
        }
Exemple #20
0
        public void CleanUpNameForType_XML_NameWithPeriod_FilesWithAndWithoutExtensionExist()
        {
            string myMonkeyProjectFolder = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "my.monkey");
            string expectedPath          = Path.Combine(myMonkeyProjectFolder, LcmFileHelper.GetXmlDataFileName("my.monkey"));

            m_mockFileOs.AddExistingFile(expectedPath);
            m_mockFileOs.AddExistingFile(Path.Combine(myMonkeyProjectFolder, "my.monkey"));

            var proj = new ProjectId("my.monkey");

            Assert.AreEqual(expectedPath, proj.Path);
            Assert.AreEqual(BackendProviderType.kXML, proj.Type);
            Assert.IsTrue(proj.IsValid);
        }
Exemple #21
0
        public void AssertValid_Invalid_SharedFolderNotFound()
        {
            var proj = new ProjectId(LcmFileHelper.GetXmlDataFileName("monkey"), FwLinkArgs.kLocalHost);

            try
            {
                proj.AssertValid();
                Assert.Fail("FwStartupException expected");
            }
            catch (StartupException exception)
            {
                Assert.IsTrue(exception.ReportToUser);
            }
        }
        /// <summary>
        /// Displays a dialog that asks the user how to handle a situation where non-standard location linked files
        /// cannot be restored to their previous position.
        /// </summary>
        /// <param name="linkedFilesPathPersisted"></param>
        /// <param name="filesContainedInLinkdFilesFolder"></param>
        protected virtual void CouldNotRestoreLinkedFilesToOriginalLocation(string linkedFilesPathPersisted, Dictionary <string, DateTime> filesContainedInLinkdFilesFolder)
        {
            YesNoCancel userSelection = m_ui.CannotRestoreLinkedFilesToOriginalLocation();

            if (userSelection == YesNoCancel.OkYes)
            {
                m_sLinkDirChangedTo = LcmFileHelper.GetDefaultLinkedFilesDir(m_restoreSettings.ProjectPath);
                //Restore the files to the project folder.
                UncompressLinkedFiles(filesContainedInLinkdFilesFolder, m_sLinkDirChangedTo, linkedFilesPathPersisted);
            }
            else if (userSelection == YesNoCancel.OkNo)
            {
                //Do nothing. Do not restore any LinkedFiles.
            }
        }
Exemple #23
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the <see cref="BackupFileSettings"/> class from an
 /// existing BackupProjectSettings object
 /// </summary>
 /// <param name="settings">The BackupProjectSettings.</param>
 /// ------------------------------------------------------------------------------------
 private BackupFileSettings(BackupProjectSettings settings)
 {
     m_backupTime              = settings.BackupTime;
     m_comment                 = settings.Comment;
     m_configurationSettings   = settings.IncludeConfigurationSettings;
     m_supportingFiles         = settings.IncludeSupportingFiles;
     m_linkedFiles             = settings.IncludeLinkedFiles;
     m_projectName             = settings.ProjectName;
     m_projectPathPersisted    = LcmFileHelper.GetPathWithoutRoot(settings.ProjectPath);
     m_spellCheckAdditions     = settings.IncludeSpellCheckAdditions;
     m_dbVersion               = settings.DbVersion;
     m_fwVersion               = settings.FwVersion;
     m_linkedFilesPathRelative = LinkedFilesRelativePathHelper.GetLinkedFilesRelativePathFromFullPath(settings.ProjectsRootFolder, settings.LinkedFilesPath, settings.ProjectPath, settings.ProjectName);
     m_linkedFilesPathActual   = settings.LinkedFilesPath;
 }
        private BackendStartupParameter GenerateBackendStartupParameters(bool isTarget, BackendProviderType type)
        {
            var    nameSuffix = (isTarget ? "_New" : "") + m_random.Next(1000);
            string name       = null;

            switch (type)
            {
            case BackendProviderType.kXMLWithMemoryOnlyWsMgr:
                name = Path.Combine(m_projectsFolder.Path, LcmFileHelper.GetXmlDataFileName("TLP" + nameSuffix));
                break;
                //case BackendProviderType.kMemoryOnly: name = null;
            }

            return(new BackendStartupParameter(true, BackendBulkLoadDomain.All, new TestProjectId(type, name)));
        }
Exemple #25
0
        public void GetProjectConfigurationDirectory_ReportsCorrectlyForDictionaryAndReversal()
        {
            {
                string projectConfigDir;

                m_propertyTable.SetProperty("currentContentControl", "lexiconEdit", true);
                projectConfigDir = Path.Combine(LcmFileHelper.GetConfigSettingsDir(Cache.ProjectId.ProjectFolder), "Dictionary");
                Assert.That(DictionaryConfigurationListener.GetProjectConfigurationDirectory(m_propertyTable), Is.EqualTo(projectConfigDir), "did not return expected directory");

                m_propertyTable.SetProperty("currentContentControl", "reversalToolEditComplete", true);
                projectConfigDir = Path.Combine(LcmFileHelper.GetConfigSettingsDir(Cache.ProjectId.ProjectFolder), "ReversalIndex");
                Assert.That(DictionaryConfigurationListener.GetProjectConfigurationDirectory(m_propertyTable), Is.EqualTo(projectConfigDir), "did not return expected directory");

                m_propertyTable.SetProperty("currentContentControl", "somethingElse", true);
                Assert.IsNull(DictionaryConfigurationListener.GetProjectConfigurationDirectory(m_propertyTable), "Other areas should cause null return");
            }
        }
Exemple #26
0
        /// <summary>
        /// Stores the configuration name as the key, and the file path as the value
        /// User configuration files with the same name as a shipped configuration will trump the shipped
        /// </summary>
        /// <seealso cref="DictionaryConfigurationController.ListDictionaryConfigurationChoices()"/>
        public static SortedDictionary <string, string> GatherBuiltInAndUserConfigurations(LcmCache cache, string configObjectName)
        {
            var configurations = new SortedDictionary <string, string>();
            var defaultConfigs = Directory.EnumerateFiles(Path.Combine(FwDirectoryFinder.DefaultConfigurations, configObjectName), "*" + DictionaryConfigurationModel.FileExtension);

            // for every configuration file in the DefaultConfigurations folder add an entry
            AddOrOverrideConfiguration(defaultConfigs, configurations);
            var projectConfigPath = Path.Combine(LcmFileHelper.GetConfigSettingsDir(cache.ProjectId.ProjectFolder), configObjectName);

            if (Directory.Exists(projectConfigPath))
            {
                var projectConfigs = Directory.EnumerateFiles(projectConfigPath, "*" + DictionaryConfigurationModel.FileExtension);
                // for every configuration in the projects configurations folder either override a shipped configuration or add an entry
                AddOrOverrideConfiguration(projectConfigs, configurations);
            }
            return(configurations);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Persists the dialog settings as an XML file.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private void PersistBackupFileSettings()
        {
            string backupSettingsFile = Path.Combine(LcmFileHelper.GetBackupSettingsDir(
                                                         m_settings.ProjectPath), LcmFileHelper.ksBackupSettingsFilename);

            string settingsDir = Path.GetDirectoryName(backupSettingsFile);

            if (!Directory.Exists(settingsDir))
            {
                Directory.CreateDirectory(settingsDir);
            }

            using (FileStream fs = new FileStream(backupSettingsFile, FileMode.Create))
            {
                BackupFileSettings.SaveToStream(m_settings, fs);
            }
        }
        private void RestoreFrom7_0AndNewerBackup(BackupFileSettings fileSettings)
        {
            // Get rid of any saved settings, since they may not be consistent with something about the data
            // or settings we are restoring. (This extension is also known to RecordView.GetClerkPersistPathname()).
            var tempDirectory = Path.Combine(m_restoreSettings.ProjectPath, LcmFileHelper.ksSortSequenceTempDir);

            if (Directory.Exists(tempDirectory))
            {
                foreach (var sortSeqFile in Directory.GetFiles(tempDirectory, "*.fwss"))
                {
                    File.Delete(sortSeqFile);
                }
            }

            UncompressDataFiles();

            // We can't use Path.Combine here, because the zip files stores all file paths with '/'s
            UncompressFilesMatchingPath(LcmFileHelper.ksWritingSystemsDir + "/", m_restoreSettings.WritingSystemStorePath);
            UncompressFilesMatchingPath(LexiconSettingsFileHelper.SharedSettingsFolder + "/", m_restoreSettings.SharedSettingsPath);

            if (m_restoreSettings.IncludeSupportingFiles)
            {
                Debug.Assert(fileSettings.IncludeSupportingFiles,
                             "The option to include supporting files should not be allowed if they aren't available in the backup settings");
                var zipEntryStartsWith = LcmFileHelper.ksSupportingFilesDir;
                UncompressFilesContainedInFolderandSubFolders(LcmFileHelper.GetZipfileFormattedPath(zipEntryStartsWith),
                                                              m_restoreSettings.ProjectSupportingFilesPath);
            }
            if (m_restoreSettings.IncludeConfigurationSettings)
            {
                UncompressFilesMatchingPath(LcmFileHelper.ksConfigurationSettingsDir + "/", m_restoreSettings.FlexConfigurationSettingsPath);
            }

            if (m_restoreSettings.IncludeLinkedFiles)
            {
                RestoreLinkedFiles(fileSettings);
            }

            if (m_restoreSettings.IncludeSpellCheckAdditions)
            {
                UncompressFilesMatchingPath(BackupSettings.ksSpellingDictionariesDir + "/", m_restoreSettings.SpellingDictionariesPath);

                CopySpellingOverrideFilesFromBackupToLocal();
            }
        }
        /// <summary>
        /// patthernToMatch is used to distinguish files bases on the folder they are from in the zipFile.
        /// For example some files from the ...ProjectName/WritingSystemStore/ folder.
        /// Other files come from the ProjectName/ConfigurationsSettings/ folder.
        /// </summary>
        /// <param name="patternToMatch">The pattern to match.</param>
        /// <param name="destinationDirectory">The destination directory.</param>
        private void UncompressFilesMatchingPath(String patternToMatch, String destinationDirectory)
        {
            using (ZipInputStream zipIn = OpenFWBackupZipfile())
            {
                ZipEntry entry;

                RemoveAllFilesFromFolder(destinationDirectory);                  //Do we want some files to remain if they were not part of the backup project
                //This could be dangerous.
                Directory.CreateDirectory(destinationDirectory);
                while ((entry = zipIn.GetNextEntry()) != null)
                {
                    var fileName = Path.GetFileName(entry.Name);

                    //Code to use for restoring files with new file structure.
                    if (!String.IsNullOrEmpty(fileName) && !entry.Name.EndsWith("/") && entry.Name.Contains(patternToMatch))
                    {
                        //first make sure the new file created has the new project name in it if the restored project is being
                        //renamed.
                        var strbldr = new StringBuilder(fileName);
                        if (m_restoreSettings.CreateNewProject)
                        {
                            strbldr.Replace(m_restoreSettings.Backup.ProjectName, m_restoreSettings.ProjectName);
                        }

                        //Contruct the path where the file will be unzipped too.
                        var    zipFileLinkFilesPath   = LcmFileHelper.GetZipfileFormattedPath(patternToMatch.Replace("/", ""));
                        var    filenameWithSubFolders = entry.Name.Substring(zipFileLinkFilesPath.Length);
                        String pathForFileSubFolders  = "";
                        if (!fileName.Equals(filenameWithSubFolders))                         //if they are equal the file is in the root of LinkedFiles
                        {
                            pathForFileSubFolders = GetPathForSubFolders(filenameWithSubFolders, fileName.Length);
                        }
                        var destFolderZipFilePath = LcmFileHelper.GetZipfileFormattedPath(destinationDirectory);
                        var pathRoot         = Path.GetPathRoot(destinationDirectory);
                        var pathforfileunzip = Path.Combine(pathRoot, destFolderZipFilePath, pathForFileSubFolders);

                        //then restore the file to the temp directory and copy it to the final location
                        UnzipFileToRestoreFolder(zipIn, strbldr.ToString(), entry.Size, pathforfileunzip, entry.DateTime);
                    }
                }
            }
        }
Exemple #30
0
        public void MigrateOldConfigurationsIfNeeded_BringsPreHistoricFileToCurrentVersion()
        {
            var configSettingsDir = LcmFileHelper.GetConfigSettingsDir(Path.GetDirectoryName(Cache.ProjectId.Path));
            var newConfigFilePath = Path.Combine(configSettingsDir, DictionaryConfigurationListener.DictionaryConfigurationDirectoryName,
                                                 "Lexeme" + DictionaryConfigurationModel.FileExtension);

            Assert.False(File.Exists(newConfigFilePath), "should not yet be migrated");
            Directory.CreateDirectory(configSettingsDir);
            File.WriteAllLines(Path.Combine(configSettingsDir, "Test.fwlayout"), new[] {
                @"<layoutType label='Lexeme-based (complex forms as main entries)' layout='publishStem'><configure class='LexEntry' label='Main Entry' layout='publishStemEntry' />",
                @"<configure class='LexEntry' label='Minor Entry' layout='publishStemMinorEntry' hideConfig='true' /></layoutType>'"
            });
            var migrator = new DictionaryConfigurationMigrator(m_propertyTable, m_mediator);

            migrator.MigrateOldConfigurationsIfNeeded();             // SUT
            var updatedConfigModel = new DictionaryConfigurationModel(newConfigFilePath, Cache);

            Assert.AreEqual(DictionaryConfigurationMigrator.VersionCurrent, updatedConfigModel.Version);
            RobustIO.DeleteDirectoryAndContents(configSettingsDir);
        }