Ejemplo n.º 1
0
        public void EnchantDictionaryMigrated()
        {
            // make temp folder with enchant dictionary in it
            var outputFolder = Path.Combine(Path.GetTempPath(), "EnchantDictionaryMigrationTestOut");
            var inputFolder  = Path.Combine(Path.GetTempPath(), "EnchantDictionaryMigrationTestIn");

            DirectoryUtilities.DeleteDirectoryRobust(outputFolder);
            DirectoryUtilities.DeleteDirectoryRobust(inputFolder);
            Directory.CreateDirectory(outputFolder);
            Directory.CreateDirectory(inputFolder);
            File.AppendAllText(Path.Combine(inputFolder, "test.dic"), "nil");
            File.AppendAllText(Path.Combine(inputFolder, "test.exc"), "nil");
            // SUT
            Assert.DoesNotThrow(() => SpellingHelper.AddAnySpellingExceptionsFromBackup(inputFolder, outputFolder));
            // Verify that the correct files were copied
            Assert.True(File.Exists(Path.Combine(outputFolder, "test.exc")), "The exception file should have been copied.");
            Assert.False(File.Exists(Path.Combine(outputFolder, "test.dic")), "The .dic file should not have been copied.");
        }
Ejemplo n.º 2
0
        public Assembly Install(string originalPath)
        {
            TryClean();

            AddAssembly(originalPath);
            Save();

            var tempPath = DirectoryUtilities.GetFileCopyFromTempWithOtherFiles(originalPath, GetTempDirectory());
            var assembly = Assembly.LoadFrom(tempPath);

            var toFolder   = GetAssemblyFolder(assembly);
            var fromFolder = assembly.GetFolder();
            var paths      = assembly.GetDllPaths();

            foreach (var path in paths)
            {
                if (Directory.Exists(path))
                {
                    var directoryName = Path.GetFileName(path);
                    DirectoryUtilities.Copy(path, Path.Combine(toFolder, directoryName));
                    continue;
                }

                var directory = Path.GetFileName(Path.GetDirectoryName(path));
                var name      = Path.GetFileName(path) ?? throw new Exception("Invalid file name");

                // TODO: only for Emgu.CV.World. Or add special checkbox
                if (string.Equals(directory, "x86", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(directory, "x64", StringComparison.OrdinalIgnoreCase))
                {
                    name = Path.Combine(directory, name);
                }

                var fromPath = File.Exists(path) ? path : Path.Combine(fromFolder, name);
                var toPath   = Path.Combine(toFolder, name);

                Directory.CreateDirectory(Path.GetDirectoryName(toPath) ?? "");
                File.Copy(fromPath, toPath, true);
            }

            Load();

            return(assembly);
        }
Ejemplo n.º 3
0
        public string SetupEpubControlContent()
        {
            // This gets called on a background thread but one step needs to happen on the UI thread,
            // so the Maker needs a control to Invoke on. An Api class doesn't naturally have one to give it,
            // so we arrange that this class is given the Bloom main window by the PublishView when the preview
            // window first comes up. In production, this is roughly equivalent to just using
            // Form.ActiveForms.Last(), but that fails when debugging; this is more robust.
            EpubMaker.ControlForInvoke = ControlForInvoke;
            EpubMaker.StageEpub(_progress);
            if (StagingDirectory == null)
            {
                return(null);                // aborted, hopefully already reported.
            }
            var fileLocator = _bookSelection.CurrentSelection.GetFileLocator();
            var root        = fileLocator.LocateDirectoryWithThrow("Readium");
            var tempFolder  = Path.GetDirectoryName(StagingDirectory);

            // This is kludge. I hope it can be improved. To make a preview we currently need all the Readium
            // files in a folder that is a parent of the staging folder containing the book content.
            // This allows us to tell Readium about the book by passing the name of the folder using the ?ePUB=
            // URL parameter. It doesn't work to use the original Readium file and make the parameter a full path.
            // It's possible that there is some variation that would work, e.g., make the param a full file:/// url
            // to the book folder. It's also possible we could get away with only copying the HTML file itself,
            // if we modified it to have localhost: links to the JS and CSS. Haven't tried this yet. The current
            // approach at least works.
            // Note October 2018: upgraded to Readium 0.3.2. Doc indicates this definitely should support
            // using any url (that doesn't involve a cross-domain problem) in the ?epub= param.
            // So we could probably now rewrite this to not copy the Readium files over. Not sure it's worth the effort.
            DirectoryUtilities.CopyDirectoryContents(root, tempFolder);

            // Not sure if we will need this. The current UI does not appear to have a way to indicate whether
            // we have a talking book, a book without audio, or one that has audio but it is not being published.
            //var audioSituationClass = "noAudioAvailable";
            //if (EpubMaker.PublishWithoutAudio)
            //	audioSituationClass = "haveAudioButNotMakingTalkingBook";
            //else if (BookHasAudio)
            //	audioSituationClass = "isTalkingBook";

            var targetFile = Path.Combine(tempFolder, "index.html");

            var iframeSource = targetFile.ToLocalhost() + "?epub=" + Path.GetFileName(StagingDirectory);

            return(iframeSource);
        }
Ejemplo n.º 4
0
        private ExecutionEnvironment()
        {
            Env = new T();
            EnvironmentFilePath = Path.Combine(Define.ConfDirPath, $"{typeof(T).Name}.json");

            // 환경설정 폴더 없으면 생성
            DirectoryUtilities.CreateDirectory(Define.ConfDirPath);

            // 설정파일 확인
            if (File.Exists(EnvironmentFilePath))
            {
                Env = Env.Read(EnvironmentFilePath);
            }
            else
            {
                Env.Initialize();
                Env = Env.Save(EnvironmentFilePath);
            }
        }
Ejemplo n.º 5
0
        public void IsDirectoryWritable_WritablePath_True()
        {
            var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                Directory.CreateDirectory(tempDir);

                var writable = DirectoryUtilities.IsDirectoryWritable(tempDir);
                Assert.True(writable);
            }
            finally
            {
                if (Directory.Exists(tempDir))
                {
                    Directory.Delete(tempDir, true);
                }
            }
        }
Ejemplo n.º 6
0
        public void Constructor_MetadataContainsAvailableBookThatDoesNotExist_SpuriousBookRemovedFromMetadata()
        {
            var sampleMetadata = new GlyssenDblTextMetadata();

            sampleMetadata.AvailableBooks = new List <Book>();
            sampleMetadata.AvailableBooks.Insert(0, new Book {
                Code = "GEN"
            });
            sampleMetadata.AvailableBooks.Insert(0, new Book {
                Code = "PSA"
            });
            sampleMetadata.AvailableBooks.Insert(0, new Book {
                Code = "MAT"
            });

            sampleMetadata.FontFamily       = "Times New Roman";
            sampleMetadata.FontSizeInPoints = 12;
            sampleMetadata.Id       = "~~funkyFrogLipsAndStuff";
            sampleMetadata.Language = new GlyssenDblMetadataLanguage {
                Iso = "~~funkyFrogLipsAndStuff"
            };
            sampleMetadata.Identification = new DblMetadataIdentification {
                Name = "~~funkyFrogLipsAndStuff"
            };

            var sampleWs = new WritingSystemDefinition();

            try
            {
                var project = new Project(sampleMetadata, new List <UsxDocument>(), SfmLoader.GetUsfmStylesheet(), sampleWs);
                WaitForProjectInitializationToFinish(project, ProjectState.ReadyForUserInteraction);
                Assert.False(project.AvailableBooks.Any());
            }
            finally
            {
                var testProjFolder = Path.Combine(Program.BaseDataFolder, "~~funkyFrogLipsAndStuff");
                if (Directory.Exists(testProjFolder))
                {
                    DirectoryUtilities.DeleteDirectoryRobust(testProjFolder);
                }
            }
        }
Ejemplo n.º 7
0
        private static void Cleanup()
        {
            string cleanupMarkerFile = Path.Combine(SupportFileDirBase, "CleanupNeeded");
            var    dirs = Directory.GetDirectories(SupportFileDirBase, "VER.*");

            if (dirs.Length > 1)
            {
                // We will assume we should come and check again on our next launch.
                File.WriteAllText(cleanupMarkerFile, "");
                foreach (string dir in Directory.GetDirectories(s_supportFileDirBase))
                {
                    // Don't clean up myself
                    if (string.Compare(dir, s_supportFileDir, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        continue;
                    }

                    // We first try to move the directory and only delete it if that succeeds.
                    // That way directories that are in use don't get cleaned up.
                    try
                    {
                        var deletingName = dir + ".deleting";
                        if (dir.EndsWith(".deleting"))
                        {
                            deletingName = dir;
                        }
                        else
                        {
                            Directory.Move(dir, deletingName);
                        }

                        DirectoryUtilities.Clean(deletingName);
                    }
                    catch (Exception) { }
                }
            }
            else
            {
                // No cleanup needed, mark that fact
                FileUtilities.ForceDelete(cleanupMarkerFile);
            }
        }
Ejemplo n.º 8
0
        public void MigrateOldConfigurationsIfNeeded_BringsPreHistoricFileToCurrentVersion()
        {
            var configSettingsDir = FdoFileHelper.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_mediator);

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

            Assert.AreEqual(DictionaryConfigurationMigrator.VersionCurrent, updatedConfigModel.Version);
            DirectoryUtilities.DeleteDirectoryRobust(configSettingsDir);
        }
Ejemplo n.º 9
0
        public void CopyDirectoryToTempDirectory_SourceFolderExists_MakesCopyInTempFolder()
        {
            string srcFolder2 = Path.Combine(_srcFolder, "copyFrom");

            Directory.CreateDirectory(srcFolder2);

            try
            {
                var returnPath = DirectoryUtilities.CopyDirectoryToTempDirectory(srcFolder2);
                Assert.IsNotNull(returnPath);
                Assert.IsTrue(Directory.Exists(returnPath));
            }
            finally
            {
                if (Directory.Exists(srcFolder2))
                {
                    Directory.Delete(srcFolder2, true);
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Import the files using the given options.
        /// </summary>
        /// <param name="options">Parsed CLI arguments.</param>
        private static void Import(ImportOptions options)
        {
            if (options.Files == null || !options.Files.Any())
            {
                throw new ArgumentException($"No files were specified");
            }

            IEnumerable <string> files = options.Files.SelectMany(f => DirectoryUtilities.FindFiles(f, options.Recursive));

            if (!files.Any())
            {
                files = options.Files;
            }

            foreach (string file in files)
            {
                var importer = new Importer();
                importer.ProcessFile(file);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Save a copy of the log to the users desired location or a default location
        /// if this feature is enabled in options.
        /// </summary>
        /// <param name="destination">
        /// The Destination File Path
        /// </param>
        /// <param name="isPreview">
        /// The is Preview.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public string ProcessLogs(string destination, bool isPreview, HBConfiguration configuration)
        {
            try
            {
                string logDir = DirectoryUtilities.GetLogDirectory();
                string encodeDestinationPath = Path.GetDirectoryName(destination);
                string destinationFile       = Path.GetFileName(destination);
                string encodeLogFile         = destinationFile + " " + DateTime.Now.ToString(CultureInfo.InvariantCulture).Replace("/", "-").Replace(":", "-") + ".txt";
                ILog   log        = LogService.GetLogger();
                string logContent = log.ActivityLog;

                // Make sure the log directory exists.
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                // Copy the Log to HandBrakes log folder in the users applciation data folder.
                this.WriteFile(logContent, Path.Combine(logDir, encodeLogFile));

                // Save a copy of the log file in the same location as the enocde.
                if (configuration.SaveLogWithVideo)
                {
                    this.WriteFile(logContent, Path.Combine(encodeDestinationPath, encodeLogFile));
                }

                // Save a copy of the log file to a user specified location
                if (Directory.Exists(configuration.SaveLogCopyDirectory) && configuration.SaveLogToCopyDirectory)
                {
                    this.WriteFile(logContent, Path.Combine(configuration.SaveLogCopyDirectory, encodeLogFile));
                }

                return(Path.Combine(logDir, encodeLogFile));
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc); // This exception doesn't warrant user interaction, but it should be logged
            }

            return(null);
        }
Ejemplo n.º 12
0
        public async Task CreateCopyAsync(ITestTask test = null)
        {
            var directory = DirectoryUtilities.CreateTemporaryDirectory(test?.TestName ?? System.IO.Path.GetFileNameWithoutExtension(Path));

            Directory.CreateDirectory(directory);
            var original_path = Path;

            Path = System.IO.Path.Combine(directory, System.IO.Path.GetFileName(Path));

            await Task.Yield();

            XmlDocument doc;

            doc = new XmlDocument();
            doc.LoadWithoutNetworkAccess(original_path);
            var original_name = System.IO.Path.GetFileName(original_path);

            if (original_name.Contains("GuiUnit_NET") || original_name.Contains("GuiUnit_xammac_mobile"))
            {
                // The GuiUnit project files writes stuff outside their project directory using relative paths,
                // but override that so that we don't end up with multiple cloned projects writing stuff to
                // the same location.
                doc.SetOutputPath("bin\\$(Configuration)");
                doc.SetNode("DocumentationFile", "bin\\$(Configuration)\\nunitlite.xml");
            }
            doc.ResolveAllPaths(original_path);

            var projectReferences = new List <TestProject> ();

            foreach (var pr in doc.GetProjectReferences())
            {
                var tp = new TestProject(pr.Replace('\\', '/'));
                await tp.CreateCopyAsync(test);

                doc.SetProjectReferenceInclude(pr, tp.Path.Replace('/', '\\'));
                projectReferences.Add(tp);
            }
            this.ProjectReferences = projectReferences;

            doc.Save(Path);
        }
        private void SetupEpubControlContent()
        {
            _model.EpubMaker.StageEpub();

            var fileLocator = _model.BookSelection.CurrentSelection.GetFileLocator();
            var root        = fileLocator.LocateDirectoryWithThrow("Readium");
            var tempFolder  = Path.GetDirectoryName(_model.StagingDirectory);

            // This is kludge. I hope it can be improved. To make a preview we currently need all the Readium
            // files in a folder that is a parent of the staging folder containing the book content.
            // This allows us to tell Readium about the book by passing the name of the folder using the ?ePUB=
            // URL parameter. It doesn't work to use the original Readium file and make the parameter a full path.
            // It's possible that there is some variation that would work, e.g., make the param a full file:/// url
            // to the book folder. It's also possible we could get away with only copying the HTML file itself,
            // if we modified it to have localhost: links to the JS and CSS. Haven't tried this yet. The current
            // approach at least works.
            DirectoryUtilities.CopyDirectoryContents(root, tempFolder);

            var englishTemplatePath   = fileLocator.LocateFileWithThrow("ePUB" + Path.DirectorySeparatorChar + "bloomEpubPreview-en.html");
            var localizedTemplatePath = BloomFileLocator.GetBestLocalizedFile(englishTemplatePath);

            var audioSituationClass = "noAudioAvailable";

            if (_model.EpubMaker.PublishWithoutAudio)
            {
                audioSituationClass = "haveAudioButNotMakingTalkingBook";
            }
            else if (_model.BookHasAudio)
            {
                audioSituationClass = "isTalkingBook";
            }

            var htmlContents = RobustFile.ReadAllText(localizedTemplatePath)
                               .Replace("{EPUBFOLDER}", Path.GetFileName(_model.StagingDirectory))
                               .Replace("_AudioSituationClass_", audioSituationClass);

            var previewHtmlInstancePath = Path.Combine(tempFolder, "bloomEpubPreview.htm");

            RobustFile.WriteAllText(previewHtmlInstancePath, htmlContents);
            _epubPreviewBrowser.Navigate(previewHtmlInstancePath.ToLocalhost(), false);
        }
Ejemplo n.º 14
0
        private void HandleOkButtonClick(object sender, EventArgs e)
        {
            if (m_model.RecordingProjectName != RecordingProjectName && File.Exists(Project.GetProjectFilePath(IsoCode, PublicationId, RecordingProjectName)))
            {
                var msg = string.Format(LocalizationManager.GetString("DialogBoxes.ProjectSettingsDlg.OverwriteProjectPrompt",
                                                                      "A {0} project with an ID of {1} and a Recording Project Name of {2} already exists for this language. Do you want to overwrite it?"),
                                        ProductName, m_txtPublicationId.Text, RecordingProjectName);
                if (MessageBox.Show(this, msg, ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                {
                    DialogResult = DialogResult.None;
                    return;
                }
                DirectoryUtilities.DeleteDirectoryRobust(Project.GetProjectFolderPath(IsoCode, PublicationId, RecordingProjectName));
            }

            m_model.RecordingProjectName = RecordingProjectName;

            m_model.Project.ProjectSettingsStatus = ProjectSettingsStatus.Reviewed;
            DialogResult = DialogResult.OK;
            Close();
        }
Ejemplo n.º 15
0
        public void SafeFoldersOmitSystemAndHiddenFolders()
        {
            using (var tempDir = new TemporaryFolder("TempRootDir"))
            {
                var sysDir = Directory.CreateDirectory(Path.Combine(tempDir.Path, "SysDir"));
                sysDir.Attributes |= FileAttributes.System;
                var hiddenDir = Directory.CreateDirectory(Path.Combine(tempDir.Path, "HiddenDir"));
                hiddenDir.Attributes |= FileAttributes.Hidden;
                var hiddenSysDir = Directory.CreateDirectory(Path.Combine(tempDir.Path, "HiddenSysDir"));
                hiddenSysDir.Attributes |= FileAttributes.System;
                hiddenSysDir.Attributes |= FileAttributes.Hidden;
                var ordinaryDir = Directory.CreateDirectory(Path.Combine(tempDir.Path, "OrdinaryDir"));

                Assert.AreEqual(4, Directory.GetDirectories(tempDir.Path).Length);

                var safeDirectories = DirectoryUtilities.GetSafeDirectories(tempDir.Path);

                Assert.AreEqual(1, safeDirectories.Length);
                Assert.AreEqual(ordinaryDir.FullName, safeDirectories[0]);
            }
        }
Ejemplo n.º 16
0
        private static void CleanupFiles(List <string> removeFiles)
        {
            string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());

            // Cleanup old/unused queue files for now.
            foreach (string file in removeFiles)
            {
                Match m = Regex.Match(file, @"([0-9]+).xml");
                if (m.Success)
                {
                    int processId = int.Parse(m.Groups[1].ToString());
                    if (GeneralUtilities.IsPidACurrentHandBrakeInstance(processId))
                    {
                        continue;
                    }
                }

                string fullPath = Path.Combine(appDataPath, file);
                File.Delete(fullPath);
            }
        }
Ejemplo n.º 17
0
        private void ClearAbandonedObjects(
            string originDirectory,
            string targetDirectory)
        {
            // Removes abandoned directories.
            DirectoryUtilities.ForeachFolderAt(targetDirectory, (string childPath) =>
            {
                string targetName = Path.GetFileName(childPath);

                string allegedOriginPath = Path.Combine(originDirectory, targetName);
                if (!Directory.Exists(allegedOriginPath))
                {
                    // recursively deletes all files within folder.
                    DirectoryUtilities.ReversedForeachFolderIn(childPath, (string f) =>
                    {
                        DirectoryUtilities.ReversedForeachFileAt(f, (FileInfo i) =>
                        {
                            File.SetAttributes(i.FullName, FileAttributes.Normal);
                            File.Delete(i.FullName);
                        });
                        Directory.Delete(f);
                    });
                }
                else
                {
                    ClearAbandonedObjects(allegedOriginPath, childPath);
                }
            });

            // Removes abandoned files.
            DirectoryUtilities.ForeachFileAt(targetDirectory, (FileInfo file) =>
            {
                string allegedOriginPath = Path.Combine(originDirectory, file.Name);

                if (!File.Exists(allegedOriginPath))
                {
                    File.Delete(file.FullName);
                }
            });
        }
Ejemplo n.º 18
0
    /// <summary>
    /// DirectoryUtilities.GetFiles is basicaly the same as Directory.GetFiles
    /// however it returns IEnumerator, which means that it lazy.  This is very important
    /// for large directory trees.  A searchPattern can be specified (Windows wildcard conventions)
    /// that can be used to filter the set of archiveFile names returned.
    ///
    /// Suggested Usage
    ///
    ///     foreach(string fileName in DirectoryUtilities.GetFiles("c:\", "*.txt")){
    ///         Console.WriteLine(fileName);
    ///     }
    ///
    /// </summary>
    /// <param variable="directoryPath">The base directory to enumerate</param>
    /// <param variable="searchPattern">A pattern to filter the names (windows filename wildcards * ?)</param>
    /// <param variable="searchOptions">Indicate if the search is recursive or not.  </param>
    /// <returns>The enumerator for all archiveFile names in the directory (recursively). </returns>
    public static IEnumerable <string> GetFiles(string directoryPath, string searchPattern, SearchOption searchOptions)
    {
        string[] fileNames = Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
        Array.Sort <string>(fileNames, StringComparer.OrdinalIgnoreCase);
        foreach (string fileName in fileNames)
        {
            yield return(fileName);
        }

        if (searchOptions == SearchOption.AllDirectories)
        {
            string[] subDirNames = Directory.GetDirectories(directoryPath);
            Array.Sort <string>(subDirNames);
            foreach (string subDir in subDirNames)
            {
                foreach (string fileName in DirectoryUtilities.GetFiles(subDir, searchPattern, searchOptions))
                {
                    yield return(fileName);
                }
            }
        }
    }
Ejemplo n.º 19
0
        public void CopyDirectoryToTempDirectory_SourceFolderExists_ReturnsCorrectFolderPath()
        {
            string srcFolder2 = Path.Combine(_srcFolder, "copyFrom");

            Directory.CreateDirectory(srcFolder2);

            try
            {
                var returnPath = DirectoryUtilities.CopyDirectoryToTempDirectory(srcFolder2);
                Assert.IsNotNull(returnPath);
                Assert.IsTrue(Directory.Exists(returnPath));
                var folderName = Path.GetFileName(srcFolder2);
                Assert.AreEqual(Path.Combine(Path.GetTempPath(), folderName), returnPath);
            }
            finally
            {
                if (Directory.Exists(srcFolder2))
                {
                    Directory.Delete(srcFolder2, true);
                }
            }
        }
Ejemplo n.º 20
0
        public void CreateBookOnDiskFromTemplate_OriginalCC0_LicenseRemoved()
        {
            var originalSource = BloomFileLocator.GetFactoryBookTemplateDirectory("Basic Book");

            using (var tempFolder = new TemporaryFolder("BasicBookCc0"))
                using (var destFolder = new TemporaryFolder("OriginalCC0_BookIsBy"))
                {
                    var source = Path.Combine(tempFolder.Path, "Basic Book");
                    if (Directory.Exists(source))
                    {
                        Directory.Delete(source, true);
                    }
                    DirectoryUtilities.CopyDirectory(originalSource, tempFolder.Path);
                    var htmPath = Path.Combine(source, "Basic Book.html");
                    var content = RobustFile.ReadAllText(htmPath);
                    // insert cc0 stuff in data div
                    var replacement = @"<div id='bloomDataDiv'><div data-book='licenseUrl' lang='*'>
            http://creativecommons.org/publicdomain/zero/1.0/
        </div>
		<div data-book='licenseUrl' lang='en'>
            http://creativecommons.org/publicdomain/zero/1.0/
        </div>
		<div data-book='licenseUrl'>
            http://creativecommons.org/publicdomain/zero/1.0/
        </div>
        <div data-book='licenseDescription' lang='en'>
            You can copy, modify, and distribute this work, even for commercial purposes, all without asking permission.
        </div>
		<div data-book='licenseNotes'>This should be removed too</div>"        .Replace("'", "\"");
                    var patched     = content.Replace("<div id=\"bloomDataDiv\">", replacement);
                    RobustFile.WriteAllText(htmPath, patched);
                    var bookPath       = GetPathToHtml(_starter.CreateBookOnDiskFromTemplate(source, destFolder.Path));
                    var assertThatBook = AssertThatXmlIn.HtmlFile(bookPath);
                    assertThatBook.HasNoMatchForXpath("//div[@data-book='licenseUrl']");
                    assertThatBook.HasNoMatchForXpath("//div[@data-book='licenseDescription']");
                    assertThatBook.HasNoMatchForXpath("//div[@data-book='licenseNotes']");
                }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Builds the source folder. First it copies all the sources into the template folder and then build the
        /// project file.
        /// </summary>
        /// <returns>The build directory</returns>
        private Task <string> Build(string sourceFolder)
        {
            var buildDirectory = Path.Combine(TemplateDirectory, "Build");

            if (Directory.Exists(buildDirectory))
            {
                Directory.Delete(buildDirectory, true);
            }
            DirectoryUtilities.CopyDirectory(sourceFolder, buildDirectory);

            var projectFile = Directory.GetFiles(buildDirectory, "*.csproj").Single();

            TraceSource.TraceEvent(TraceEventType.Verbose, "{0}\t Building \"{1}\"", item, projectFile);

            // create a MS project instance and configure it to build 'Release'
            Project project = new Project(projectFile);

            project.SetProperty("Configuration", "ReleaseSigned");

            bool success = project.Build("Build", new[] { new ConsoleLogger(LoggerVerbosity.Quiet) });

            if (success)
            {
                TraceSource.TraceEvent(TraceEventType.Information, "{0}\t \"{1}\" was built successfully!", item,
                                       projectFile);
            }
            else
            {
                TraceSource.TraceEvent(TraceEventType.Error, "{0}\t \"{1}\" ERROR IN BUILDING THE PROJECT!", item,
                                       projectFile);
                buildDirectory = null;
            }

            TaskCompletionSource <string> tcs = new TaskCompletionSource <string>();

            tcs.SetResult(buildDirectory);
            return(tcs.Task);
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <returns>true if client should wait for hg to notice</returns>
        public bool PrepareToReceiveRepository(string name, string id)
        {
            var jsonStrings = GetRepositoryInformation(string.Empty);
            var hubInfo     = ImitationHubJSONService.ParseJsonStringsToChorusHubRepoInfos(jsonStrings);

            if (hubInfo.Any(info => info.RepoID == id))
            {
                return(false);
            }

            // since the repository doesn't exist, create it
            var directory = Path.Combine(ChorusHubOptions.RootDirectory, name);
            var uniqueDir = DirectoryUtilities.GetUniqueFolderPath(directory);

            //EventLog.WriteEntry("Application", string.Format("PrepareToReceiveRepository() is preparing a place for '{0}'.", name), EventLogEntryType.Information);
            if (uniqueDir != directory)
            {
                //EventLog.WriteEntry("Application", string.Format("{0} already exists! Creating repository for {1} at {2}.", directory, name, uniqueDir), EventLogEntryType.Warning);
            }
            Directory.CreateDirectory(uniqueDir);
            HgRepository.CreateRepositoryInExistingDir(uniqueDir, new ConsoleProgress());
            return(true);
        }
Ejemplo n.º 23
0
        // ReSharper disable once InconsistentNaming
        private static void CheckR2APIMonomodPatch()
        {
            // This type is injected by the R2API MonoMod patch with MonoModRules
            const string R2APIMonoModPatchWasHereName = "R2API.R2APIMonoModPatchWasHere";
            var          isHere = typeof(RoR2Application).Assembly.GetType(R2APIMonoModPatchWasHereName, false) != null;

            if (!isHere)
            {
                var message = new List <string> {
                    "The Monomod patch of R2API seems to be missing",
                    "Please make sure that a file called:",
                    "Assembly-CSharp.R2API.mm.dll",
                    "is present in the Risk of Rain 2\\BepInEx\\monomod\\ folder",
                    "or",
                    "You are missing the monomod loader that is normally located in,",
                    "the Risk of Rain 2\\BepInEx\\patchers\\BepInEx.MonoMod.Loader folder.",
                    "If you don't have this folder, please download BepInEx again from the",
                    "thunderstore and make sure to follow the installation instructions."
                };
                Logger.LogBlockError(message);
                DirectoryUtilities.LogFolderStructureAsTree(Paths.GameRootPath);
            }
        }
Ejemplo n.º 24
0
        public bool IsPathWritable(string directory)
        {
            try
            {
                if (DirectoryUtilities.IsDirectoryWritable(directory))
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                DisplayMessage(e.Message, MessageType.Warning);
                return(false);
            }

            var msg = LocalizationManager.GetString(
                "DialogBoxes.ArchivingDlg.PathNotWritableMsg",
                "The path is not writable: {0}");

            DisplayMessage(string.Format(msg, directory), MessageType.Warning);

            return(false);
        }
Ejemplo n.º 25
0
        public void BackupQueue(string exportPath)
        {
            lock (this.queueFileLock)
            {
                try
                {
                    string appDataPath = DirectoryUtilities.GetUserStoragePath(HandBrakeVersionHelper.IsNightly());
                    string tempPath    = !string.IsNullOrEmpty(exportPath)
                        ? exportPath
                        : Path.Combine(appDataPath, string.Format(this.queueFile, string.Empty));

                    // Make a copy of the file before we replace it. This way, if we crash we can recover.
                    if (File.Exists(tempPath))
                    {
                        File.Copy(tempPath, tempPath + ".last", true);
                    }

                    using (StreamWriter writer = new StreamWriter(tempPath))
                    {
                        List <QueueTask> tasks = this.queue.Where(item => item.Status != QueueItemStatus.Completed)
                                                 .ToList();

                        string queueJson = JsonSerializer.Serialize(tasks, JsonSettings.Options);
                        writer.Write(queueJson);
                    }

                    if (File.Exists(tempPath + ".last"))
                    {
                        File.Delete(tempPath + ".last");
                    }
                }
                catch (Exception exc)
                {
                    this.logService.LogMessage(string.Format("{1} # {0}{1} {2}{1}", "Queue Backup Failed!", Environment.NewLine, exc));
                }
            }
        }
Ejemplo n.º 26
0
        public void MigrateOldConfigurationsIfNeeded_PreservesOrderOfBibliographies()
        {
            var configSettingsDir = FdoFileHelper.GetConfigSettingsDir(Path.GetDirectoryName(Cache.ProjectId.Path));
            var newConfigFilePath = Path.Combine(configSettingsDir, DictionaryConfigurationListener.ReversalIndexConfigurationDirectoryName,
                                                 "AllReversalIndexes" + 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='All Reversal Indexes' layout='publishReversal'>",
                @"<configure class='ReversalIndexEntry' label='Reversal Entry' layout='publishReversalEntry' /></layoutType>'"
            });
            var migrator = new DictionaryConfigurationMigrator(m_mediator);

            migrator.MigrateOldConfigurationsIfNeeded();             // SUT
            var updatedConfigModel = new DictionaryConfigurationModel(newConfigFilePath, Cache);
            var refdSenseChildren  = updatedConfigModel.Parts[0].Children.Find(n => n.Label == "Referenced Senses").Children;
            var bibCount           = 0;

            for (var i = 0; i < refdSenseChildren.Count; i++)
            {
                var bibNode = refdSenseChildren[i];
                if (!bibNode.Label.StartsWith("Bibliography"))
                {
                    continue;
                }
                StringAssert.StartsWith("Bibliography (", bibNode.Label, "Should specify (entry|sense), lest we never know");
                Assert.False(bibNode.IsCustomField, bibNode.Label + " should not be custom.");
                // Rough test to ensure Bibliography nodes aren't bumped to the end of the list. In the defaults, the later Bibliography
                // node is a little more than five nodes from the end
                Assert.LessOrEqual(i, refdSenseChildren.Count - 5, "Bibliography nodes should not have been bumped to the end of the list");
                ++bibCount;
            }
            Assert.AreEqual(2, bibCount, "Should be exactly two Bibliography nodes (sense and entry)");
            DirectoryUtilities.DeleteDirectoryRobust(configSettingsDir);
        }
Ejemplo n.º 27
0
        /// <summary>Constructor</summary>
        /// <param name="pathAndFileSpec">Path and file specification for finding files.</param>
        /// <param name="ignorePaths">Ignore these paths when looking for files to run.</param>
        /// <param name="recurse">Recurse into child folder?</param>
        /// <param name="runTests">Run tests?</param>
        /// <param name="runType">How should the simulations be run?</param>
        /// <param name="wait">Wait until all simulations are complete?</param>
        /// <param name="numberOfProcessors">Number of CPU processes to use. -1 indicates all processes.</param>
        /// <param name="simulationNamePatternMatch">A regular expression used to match simulation names to run.</param>
        public Runner(string pathAndFileSpec,
                      List <string> ignorePaths = null,
                      bool recurse                      = true,
                      bool runTests                     = true,
                      RunTypeEnum runType               = RunTypeEnum.MultiThreaded,
                      bool wait                         = true,
                      int numberOfProcessors            = -1,
                      string simulationNamePatternMatch = null)
        {
            this.runType            = runType;
            this.wait               = wait;
            this.numberOfProcessors = numberOfProcessors;

            string[] files = DirectoryUtilities.FindFiles(pathAndFileSpec, recurse);
            foreach (string fileName in files)
            {
                if (!DoIgnoreFile(fileName, ignorePaths))
                {
                    var simulationGroup = new SimulationGroup(fileName, runTests, simulationNamePatternMatch);
                    simulationGroup.Completed += OnSimulationGroupCompleted;
                    jobs.Add(simulationGroup);
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Load the User Settings
        /// </summary>
        private void Load()
        {
            try
            {
                // Load up the users current settings file.
                if (File.Exists(this.settingsFile))
                {
                    using (StreamReader reader = new StreamReader(this.settingsFile))
                    {
                        Collections.SerializableDictionary <string, object> data = (Collections.SerializableDictionary <string, object>) this.serializer.Deserialize(reader);
                        this.userSettings = data;
                    }
                }
                else if (VersionHelper.IsNightly() && File.Exists(Path.Combine(DirectoryUtilities.GetUserStoragePath(false), "settings.xml")))
                {
                    // Port the release versions config to the nightly.
                    string releasePresetFile = Path.Combine(DirectoryUtilities.GetUserStoragePath(false), "settings.xml");

                    if (!Directory.Exists(DirectoryUtilities.GetUserStoragePath(true)))
                    {
                        Directory.CreateDirectory(DirectoryUtilities.GetUserStoragePath(true));
                    }

                    File.Copy(releasePresetFile, Path.Combine(DirectoryUtilities.GetUserStoragePath(true), "settings.xml"));

                    using (StreamReader reader = new StreamReader(this.settingsFile))
                    {
                        Collections.SerializableDictionary <string, object> data = (Collections.SerializableDictionary <string, object>) this.serializer.Deserialize(reader);
                        this.userSettings = data;
                    }
                }
                else
                {
                    this.userSettings = new Collections.SerializableDictionary <string, object>();
                }

                // Add any missing / new settings
                Collections.SerializableDictionary <string, object> defaults = this.GetDefaults();
                foreach (var item in defaults.Where(item => !this.userSettings.Keys.Contains(item.Key)))
                {
                    this.userSettings.Add(item.Key, item.Value);
                    this.Save();
                }
            }
            catch (Exception exc)
            {
                try
                {
                    this.userSettings = this.GetDefaults();
                    if (File.Exists(this.settingsFile))
                    {
                        File.Delete(this.settingsFile);
                    }
                    this.Save();

                    throw new GeneralApplicationException(Resources.UserSettings_YourSettingsHaveBeenReset, Resources.UserSettings_YourSettingsAreCorrupt, exc);
                }
                catch (Exception)
                {
                    throw new GeneralApplicationException(string.Format(Resources.UserSettings_UnableToLoad, this.settingsFile), Resources.UserSettings_UnableToLoadSolution, exc);
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Check if the queue recovery file contains records.
        /// If it does, it means the last queue did not complete before HandBrake closed.
        /// So, return a boolean if true.
        /// </summary>
        /// <param name="filterQueueFiles">
        /// The filter Queue Files.
        /// </param>
        /// <returns>
        /// True if there is a queue to recover.
        /// </returns>
        public static List <string> CheckQueueRecovery(List <string> filterQueueFiles)
        {
            try
            {
                // Check for any Corrupted Backup Files and try recover them
                RecoverFromBackupFailure();

                // Now check for all available recovery files. (There may be more than 1 for multi-instance support)
                string                 tempPath   = DirectoryUtilities.GetUserStoragePath(HandBrakeVersionHelper.IsNightly());
                DirectoryInfo          info       = new DirectoryInfo(tempPath);
                IEnumerable <FileInfo> foundFiles = info.GetFiles("*.json").Where(f => f.Name.StartsWith(QueueFileName));
                var queueFiles = GetFilesExcludingActiveProcesses(foundFiles, filterQueueFiles);

                if (!queueFiles.Any())
                {
                    return(queueFiles);
                }

                List <string> removeFiles   = new List <string>();
                List <string> acceptedFiles = new List <string>();


                foreach (string file in queueFiles)
                {
                    try
                    {
                        using (StreamReader stream = new StreamReader(file))
                        {
                            List <QueueTask> list = list = JsonSerializer.Deserialize <List <QueueTask> >(stream.ReadToEnd(), JsonSettings.Options);
                            if (list != null && list.Count == 0)
                            {
                                removeFiles.Add(file);
                            }

                            if (list != null && list.Count != 0)
                            {
                                List <QueueTask> tasks = list.Where(l => l.Status != QueueItemStatus.Completed).ToList();
                                if (tasks.Count != 0)
                                {
                                    acceptedFiles.Add(Path.GetFileName(file));
                                }
                                else
                                {
                                    removeFiles.Add(file);
                                }
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Debug.WriteLine(exc);
                    }
                }

                CleanupFiles(removeFiles, false);

                return(acceptedFiles);
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc);
                return(new List <string>()); // Keep quiet about the error.
            }
        }
Ejemplo n.º 30
0
 public void CopyDirectoryContents_DestinationFolderDoesNotExist_CreatesItAndReturnsTrue()
 {
     Assert.IsFalse(Directory.Exists(_dstFolder));
     Assert.IsTrue(DirectoryUtilities.CopyDirectoryContents(_srcFolder, _dstFolder));
     Assert.IsTrue(Directory.Exists(_dstFolder));
 }