コード例 #1
0
ファイル: GrepCoreTest.cs プロジェクト: zer/dnGrep
        public void TestSearchAndReplaceXPathWithMissingXmlDeclaration(bool useLongPath)
        {
            string destFolder = useLongPath ? GetLongPathDestination(Guid.NewGuid().ToString()) : destinationFolder;

            Utils.CopyFiles(Path.Combine(sourceFolder, "TestCase4"), Path.Combine(destFolder, "TestCase4"), null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(Path.Combine(destFolder, "TestCase4"), "books_no_decl.xml"),
                                                          SearchType.XPath, "(//@category)[2]", GrepSearchOption.None, -1);

            Assert.Single(results);
            Assert.Single(results[0].Matches);

            // mark all matches for replace
            foreach (var match in results[0].Matches)
            {
                match.ReplaceMatch = true;
            }

            string            testFile = Path.Combine(destinationFolder, "TestCase4", "books_no_decl.xml");
            List <ReplaceDef> files    = new List <ReplaceDef>
            {
                new ReplaceDef(testFile, results[0].Matches)
            };

            core.Replace(files, SearchType.XPath, "(//@category)[2]", "general", GrepSearchOption.None, -1);

            var fileContent = File.ReadAllLines(testFile, Encoding.UTF8);

            Assert.Equal(37, fileContent.Length);
            Assert.Equal("<bookstore>", fileContent[0]);
            Assert.Equal("  <book category=\"general\">", fileContent[7]);
        }
コード例 #2
0
        private static void Export_Directories_Authors(Library library, string base_path, Dictionary <string, PDFDocumentExportItem> pdf_document_export_items)
        {
            WshShell shell = new WshShell();

            string authors_base_path = Path.GetFullPath(Path.Combine(base_path, @"authors"));

            Directory.CreateDirectory(authors_base_path);

            foreach (var item in pdf_document_export_items.Values)
            {
                try
                {
                    List <NameTools.Name> names = NameTools.SplitAuthors(item.pdf_document.AuthorsCombined);
                    foreach (var name in names)
                    {
                        string author_base_path = Path.GetFullPath(Path.Combine(authors_base_path, name.LastName_Initials));
                        Directory.CreateDirectory(author_base_path);
                        string filename = Path.GetFullPath(Path.Combine(author_base_path, FileTools.MakeSafeFilename(item.pdf_document.TitleCombined) + ".lnk"));
                        CreateShortcut(shell, item.filename, filename);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error creating shortcut for " + item.filename);
                }
            }
        }
コード例 #3
0
        private void ReviewDirsInDownloadDirectory(string dirPath)
        {
            try
            {
                foreach (string subDirPath in Directory.GetDirectories(dirPath, "*",
                                                                       SearchOption.AllDirectories).Where(Directory.Exists))
                {
                    if (currentSettings.Token.IsCancellationRequested)
                    {
                        return;
                    }

                    ReviewDirInDownloadDirectory(subDirPath);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                LOGGER.Warn(ex, $"Could not access subdirectories of {dirPath}");
            }
            catch (DirectoryNotFoundException ex)
            {
                LOGGER.Warn(ex, $"Could not access subdirectories of {dirPath}");
            }
            catch (IOException ex)
            {
                LOGGER.Warn(ex, $"Could not access subdirectories of {dirPath}");
            }
        }
コード例 #4
0
 public void Dispose()
 {
     if (Directory.Exists(destinationFolder))
     {
         Utils.DeleteFolder(destinationFolder);
     }
 }
コード例 #5
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string _path = value as string;

            if (File.Exists(_path))
            {
                if (_path.Length > 240)  // 规避文件名和路径名过长问题
                {
                    if (!Directory.Exists("./temp"))
                    {
                        Directory.CreateDirectory("./temp");
                    }
                    FileInfo fi   = new FileInfo(_path);
                    string   _tmp = Path.GetFileName(_path);
                    if (!File.Exists("./temp/" + _tmp))
                    {
                        fi.CopyTo("./temp/" + _tmp, true);
                    }
                    return(new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + @"./temp/" + _tmp, UriKind.RelativeOrAbsolute)));
                }
                else
                {
                    return(new BitmapImage(new Uri(_path, UriKind.RelativeOrAbsolute)));
                }
            }
            else
            {
                return(null);
            }
        }
コード例 #6
0
        private static void Export_Directories_AutoTags(WebLibraryDetail web_library_detail, string base_path, Dictionary <string, PDFDocumentExportItem> pdf_document_export_items)
        {
            WshShell shell = new WshShell();

            string tags_base_path = Path.GetFullPath(Path.Combine(base_path, @"autotags"));

            Directory.CreateDirectory(tags_base_path);

            foreach (var item in pdf_document_export_items.Values)
            {
                try
                {
                    foreach (string tag in web_library_detail.Xlibrary.AITagManager.AITags.GetTagsWithDocument(item.pdf_document.Fingerprint))
                    {
                        string tag_base_path = Path.GetFullPath(Path.Combine(tags_base_path, FileTools.MakeSafeFilename(tag)));
                        Directory.CreateDirectory(tag_base_path);
                        string filename = Path.GetFullPath(Path.Combine(tag_base_path, FileTools.MakeSafeFilename(item.pdf_document.TitleCombined) + ".lnk"));
                        CreateShortcut(shell, item.filename, filename);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error creating shortcut for {0}", item.filename);
                }
            }
        }
コード例 #7
0
        public void TestReplaceWithPattern(SearchType type, bool useLongPath)
        {
            string destFolder = useLongPath ? GetLongPathDestination(Guid.NewGuid().ToString()) : destinationFolder;

            Utils.CopyFiles(sourceFolder + "\\TestCase9", destFolder + "\\TestCase9", null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(destFolder + "\\TestCase9", "test.txt"), type, "here", GrepSearchOption.None, -1);

            Assert.Equal(results.Count, 1);
            Assert.Equal(results[0].SearchResults.Count, 6);

            string testFile = Path.Combine(destFolder, @"TestCase9\test.txt");
            Dictionary <string, string> files = new Dictionary <string, string>
            {
                { testFile, Guid.NewGuid().ToString() + ".txt" }
            };

            core.Replace(files, type, "here", "$(guid)", GrepSearchOption.None, -1);
            string fileContent = File.ReadAllText(destFolder + "\\TestCase9\\test.txt", Encoding.ASCII).Trim();

            Assert.Equal(6, guidPattern.Matches(fileContent).Count);
            HashSet <string> uniqueGuids = new HashSet <string>();

            foreach (Match match in guidPattern.Matches(fileContent))
            {
                if (!uniqueGuids.Contains(match.Value))
                {
                    uniqueGuids.Add(match.Value);
                }
                else
                {
                    Assert.True(false, "All guides should be unique.");
                }
            }
        }
コード例 #8
0
        public static void Test()
        {
            string[] filenames = Directory.GetFiles(@"C:\temp");
            foreach (string filename in filenames)
            {
                string hash1, hash2;

                try
                {
                    Logging.Info(".NET");
                    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 1024))
                    {
                        hash2 = FromStream_DOTNET(fs);
                    }
                    Logging.Info("Bouncy");
                    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 1024))
                    {
                        hash1 = FromStream_BOUNCY(fs);
                    }

                    if (hash1 != hash2)
                    {
                        Logging.Error("Non matching hash for " + filename);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Exception for " + filename);
                }
            }
        }
コード例 #9
0
        private static void AddPathToSevenZip(Dictionary <string, System.IO.Stream> files, IList <System.IO.Stream> streams, string snapshotPath, int volumePathLength, string vmPath)
        {
            var srcPath = Path.Combine(snapshotPath, vmPath.Substring(volumePathLength));

            if (Directory.Exists(srcPath))
            {
                foreach (var srcChildPath in Directory.GetFileSystemEntries(srcPath))
                {
                    var srcChildPathRel = srcChildPath.Substring(snapshotPath.EndsWith(Path.PathSeparator.ToString(), StringComparison.CurrentCultureIgnoreCase) ? snapshotPath.Length : snapshotPath.Length + 1);
                    var childPath       = Path.Combine(vmPath.Substring(0, volumePathLength), srcChildPathRel);
                    AddPathToSevenZip(files, streams, snapshotPath, volumePathLength, childPath);
                }
            }
            else if (File.Exists(srcPath))
            {
                var s = File.OpenRead(srcPath);
                files.Add(vmPath.Substring(volumePathLength), s);
                streams.Add(s);
            }
            else
            {
                var lowerPath   = srcPath.ToLowerInvariant();
                var isIgnorable = lowerPath.EndsWith(".avhdx") || lowerPath.EndsWith(".vmrs") ||
                                  lowerPath.EndsWith(".bin") || lowerPath.EndsWith(".vsv");

                if (!isIgnorable)
                {
                    throw new Exception($"Entry \"{srcPath}\" not found in snapshot");
                }
            }
        }
コード例 #10
0
ファイル: GrepCoreTest.cs プロジェクト: zer/dnGrep
        public void TestRegexCaptureReplace(bool useLongPath)
        {
            string destFolder = useLongPath ? GetLongPathDestination(Guid.NewGuid().ToString()) : destinationFolder;

            Utils.CopyFiles(Path.Combine(sourceFolder, "TestCase3"), Path.Combine(destinationFolder, "TestCase3"), null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(Path.Combine(destFolder, "TestCase3"), "test-file-code.cs"),
                                                          SearchType.Regex, @"-(\d)", GrepSearchOption.None, -1);

            Assert.Single(results);
            Assert.Single(results[0].SearchResults.Where(r => !r.IsContext));

            // mark all matches for replace
            foreach (var match in results[0].Matches)
            {
                match.ReplaceMatch = true;
            }

            string            testFile = Path.Combine(destFolder, @"TestCase3\test-file-code.cs");
            List <ReplaceDef> files    = new List <ReplaceDef>
            {
                new ReplaceDef(testFile, results[0].Matches)
            };

            core.Replace(files, SearchType.Regex, @"-(\d)", @"$1", GrepSearchOption.None, -1);
            string content = File.ReadAllText(testFile, Encoding.ASCII);

            Assert.DoesNotContain("= -1;", content);
            Assert.Contains("= 1;", content);

            core.Undo(files);
            content = File.ReadAllText(testFile, Encoding.ASCII);
            Assert.DoesNotContain("= 1;", content);
            Assert.Contains("= -1;", content);
        }
コード例 #11
0
ファイル: GrepApplicationSettings.cs プロジェクト: zer/dnGrep
        /// <summary>
        /// Saves settings to location specified
        /// </summary>
        /// <param name="path">Path to settings file</param>
        public void Save(string path)
        {
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                lock (this)
                {
                    // Create temp file in case save crashes
                    using (FileStream stream = File.OpenWrite(path + "~"))
                        using (XmlWriter xmlStream = XmlWriter.Create(stream, new XmlWriterSettings {
                            Indent = true
                        }))
                        {
                            if (xmlStream == null)
                            {
                                return;
                            }
                            XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
                            serializer.Serialize(xmlStream, this);
                        }
                    File.Copy(path + "~", path, true);
                    Utils.DeleteFile(path + "~");
                }
            }
            catch (Exception ex)
            {
                logger.Log <Exception>(LogLevel.Error, "Failed to load settings", ex);
            }
        }
コード例 #12
0
ファイル: GrepCoreTest.cs プロジェクト: zer/dnGrep
        public void TestSearchAndFilteredReplace(SearchType type, GrepSearchOption option, string searchFor, string replaceWith)
        {
            Utils.CopyFiles(Path.Combine(sourceFolder, "TestCase15"), Path.Combine(destinationFolder, "TestCase15"), null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(Path.Combine(destinationFolder, "TestCase15"), "books.xml"),
                                                          type, searchFor, option, -1);

            Assert.Single(results);
            Assert.Equal(2, results[0].Matches.Count);

            // mark only the second match for replace
            results[0].Matches[1].ReplaceMatch = true;

            string            testFile = Path.Combine(destinationFolder, "TestCase15", "books.xml");
            List <ReplaceDef> files    = new List <ReplaceDef>
            {
                new ReplaceDef(testFile, results[0].Matches)
            };

            core.Replace(files, type, searchFor, replaceWith, option, -1);

            var fileContent = File.ReadAllText(testFile, Encoding.UTF8);

            Assert.Contains("<year>2003</year>", fileContent);
            Assert.Single(Regex.Matches(fileContent, "2002"));
            Assert.Single(Regex.Matches(fileContent, "2003"));
        }
コード例 #13
0
ファイル: GrepCoreTest.cs プロジェクト: zer/dnGrep
        public void TestReplaceWithNewLineWorks(bool useLongPath)
        {
            string destFolder = useLongPath ? GetLongPathDestination(Guid.NewGuid().ToString()) : destinationFolder;

            Utils.CopyFiles(Path.Combine(sourceFolder, "TestCase8"), Path.Combine(destFolder, "TestCase8"), null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(Path.Combine(destFolder, "TestCase8"), "test.txt"), SearchType.Regex, "here", GrepSearchOption.None, -1);

            Assert.Single(results);
            Assert.Single(results[0].SearchResults);

            // mark all matches for replace
            foreach (var match in results[0].Matches)
            {
                match.ReplaceMatch = true;
            }

            string            testFile = Path.Combine(destFolder, @"TestCase8\test.txt");
            List <ReplaceDef> files    = new List <ReplaceDef>
            {
                new ReplaceDef(testFile, results[0].Matches)
            };

            core.Replace(files, SearchType.Regex, "here", "\\\\n", GrepSearchOption.None, -1);
            Assert.Equal(2, File.ReadAllText(testFile, Encoding.ASCII).Trim().Split('\n').Length);
        }
コード例 #14
0
ファイル: GrepCoreTest.cs プロジェクト: zer/dnGrep
        public void TestSearchAndFilteredReplaceXPathWithMissingXmlDeclaration(bool useLongPath)
        {
            string destFolder = useLongPath ? GetLongPathDestination(Guid.NewGuid().ToString()) : destinationFolder;

            Utils.CopyFiles(Path.Combine(sourceFolder, "TestCase4"), Path.Combine(destFolder, "TestCase4"), null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(Path.Combine(destFolder, "TestCase4"), "books_no_decl.xml"),
                                                          SearchType.XPath, "(//@currency)", GrepSearchOption.None, -1);

            Assert.Single(results);
            Assert.Equal(5, results[0].Matches.Count);

            // mark 2nd and 4th matches for replace
            results[0].Matches[1].ReplaceMatch = true;
            results[0].Matches[3].ReplaceMatch = true;

            string            testFile = Path.Combine(destinationFolder, "TestCase4", "books_no_decl.xml");
            List <ReplaceDef> files    = new List <ReplaceDef>
            {
                new ReplaceDef(testFile, results[0].Matches)
            };

            core.Replace(files, SearchType.XPath, "(//@currency)", "EUR", GrepSearchOption.None, -1);

            var fileContent = File.ReadAllText(testFile, Encoding.UTF8);

            Assert.Equal(2, Regex.Matches(fileContent, "EUR").Count);
        }
コード例 #15
0
ファイル: VirtualFile.cs プロジェクト: AliceDTRH/JackedPatch
        public static async Task <VirtualFile> Analyze(Context context, VirtualFile parent, string abs_path,
                                                       string rel_path)
        {
            var fi   = new FileInfo(abs_path);
            var self = new VirtualFile
            {
                Context      = context,
                Name         = rel_path,
                Parent       = parent,
                Size         = fi.Length,
                LastModified = fi.LastWriteTimeUtc.Ticks,
                LastAnalyzed = DateTime.Now.Ticks,
                Hash         = abs_path.FileHash()
            };

            if (FileExtractor.CanExtract(abs_path))
            {
                using (var tempFolder = context.GetTemporaryFolder())
                {
                    await FileExtractor.ExtractAll(context.Queue, abs_path, tempFolder.FullName);

                    var list = await Directory.EnumerateFiles(tempFolder.FullName, "*", SearchOption.AllDirectories)
                               .PMap(context.Queue, abs_src => Analyze(context, self, abs_src, abs_src.RelativeTo(tempFolder.FullName)));

                    self.Children = list.ToImmutableList();
                }
            }

            return(self);
        }
コード例 #16
0
        public static Boolean IsDirLocked(String path)
        {
            try {
                // UGLY hack to determine whether we have write access
                // to a specific directory

                var r        = new Random();
                var tempName = path + "deltest";

                var counter = 0;

                while (Directory.Exists(tempName))
                {
                    tempName = path + "deltest" + r.Next(0, 9999);

                    if (counter > 100)
                    {
                        return(true); // Something strange is going on... stop here...
                    }

                    counter++;
                }

                Directory.Move(path, tempName);
                Directory.Move(tempName, path);

                return(false);
            }
            catch //(Exception ex)
            {
                // Could not rename -> probably we have no
                // write access to the directory
                return(true);
            }
        }
コード例 #17
0
        public void StartMonitor()
        {
            foreach (string efi in TVSettings.Instance.DownloadFolders)
            {
                if (!Directory.Exists(efi)) //Does not exist
                {
                    continue;
                }

                if ((File.GetAttributes(efi) & FileAttributes.Directory) != (FileAttributes.Directory))  // not a folder
                {
                    continue;
                }

                FileSystemWatcher watcher = new FileSystemWatcher(efi);
                watcher.Changed += watcher_Changed;
                watcher.Created += watcher_Changed;
                watcher.Renamed += watcher_Changed;
                //watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
                //watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.CreationTime;
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents   = true;
                watchers.Add(watcher);
                Logger.Trace("Starting logger for {0}", efi);
            }
        }
コード例 #18
0
 public string GetDllPath()
 {
     //Assembly thisAssembly = Assembly.GetAssembly(typeof(TestBase));
     //return Path.GetDirectoryName(thisAssembly.Location);
     //return @"D:\Sandbox\dnGrep\Tests";
     return(Directory.GetCurrentDirectory());
 }
コード例 #19
0
        public string GetLongPathDestination(string leafFolder)
        {
            var parts = new string[]
            {
                destinationFolder,
                new string('a', 50),
                new string('b', 50),
                new string('c', 50),
                new string('d', 50),
                new string('e', 50),
                new string('f', 50),
                new string('g', 50),
                new string('h', 50),
                leafFolder
            };

            destinationFolder = Path.Combine(parts);

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

            return(destinationFolder);
        }
コード例 #20
0
        public Action Stage(IEnumerable <VirtualFile> files)
        {
            var grouped = files.SelectMany(f => f.FilesInPath)
                          .Distinct()
                          .Where(f => f.ParentArchive != null)
                          .GroupBy(f => f.ParentArchive)
                          .OrderBy(f => f.Key == null ? 0 : f.Key.Paths.Length)
                          .ToList();

            var Paths = new List <string>();

            foreach (var group in grouped)
            {
                var tmp_path = Path.Combine(_stagedRoot, Guid.NewGuid().ToString());
                FileExtractor.ExtractAll(group.Key.StagedPath, tmp_path);
                Paths.Add(tmp_path);
                foreach (var file in group)
                {
                    file._stagedPath = Path.Combine(tmp_path, file.Paths[group.Key.Paths.Length]);
                }
            }

            return(() =>
            {
                Paths.Do(p =>
                {
                    if (Directory.Exists(p))
                    {
                        DeleteDirectory(p);
                    }
                });
            });
        }
コード例 #21
0
        public void TestReplaceAndUndoWorks(bool useLongPath)
        {
            string destFolder = useLongPath ? GetLongPathDestination(Guid.NewGuid().ToString()) : destinationFolder;

            Utils.CopyFiles(sourceFolder + "\\TestCase3", destinationFolder + "\\TestCase3", null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(destFolder + "\\TestCase3", "test-file-code.cs"), SearchType.PlainText, "body", GrepSearchOption.None, -1);

            Assert.Equal(1, results.Count);
            Assert.Equal(2, results[0].SearchResults.Where(r => r.IsContext).Count());

            string testFile = Path.Combine(destFolder, @"TestCase3\test-file-code.cs");
            Dictionary <string, string> files = new Dictionary <string, string>
            {
                { testFile, Guid.NewGuid().ToString() + ".cs" }
            };

            core.Replace(files, SearchType.PlainText, "body", "text", GrepSearchOption.None, -1);
            string content = File.ReadAllText(testFile, Encoding.ASCII);

            Assert.False(content.Contains("body"));
            Assert.True(content.Contains("text"));

            core.Undo(files);
            content = File.ReadAllText(testFile, Encoding.ASCII);
            Assert.False(content.Contains("text"));
            Assert.True(content.Contains("body"));
        }
コード例 #22
0
        internal static void Install(BundleLibraryManifest manifest, string library_bundle_filename)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            WebLibraryDetail web_library_detail = WebLibraryManager.Instance.GetLibrary(manifest.Id);

            if (null != web_library_detail)
            {
                MessageBoxes.Info("You already have a version of this Bundle Library.  Please ensure you close all windows that use this library after the latest has been downloaded.");
            }

            string library_directory = WebLibraryDetail.GetLibraryBasePathForId(manifest.Id);

            Directory.CreateDirectory(library_directory);

            // Unzip the bundle
            string parameters = String.Format("-y x \"{0}\" -o\"{1}\"", library_bundle_filename, library_directory);

            using (Process process = ProcessSpawning.SpawnChildProcess(ConfigurationManager.Instance.Program7ZIP, parameters))
            {
                using (ProcessOutputReader process_output_reader = new ProcessOutputReader(process))
                {
                    process.WaitForExit();

                    Logging.Info("7ZIP Log Bundle Install progress:\n{0}", process_output_reader.GetOutputsDumpStrings());
                }
            }

            // Reflect this new bundle
            WebLibraryDetail new_web_library_detail = WebLibraryManager.Instance.UpdateKnownWebLibraryFromBundleLibraryManifest(manifest, suppress_flush_to_disk: false);

            WPFDoEvents.InvokeInUIThread(() => {
                MainWindowServiceDispatcher.Instance.OpenLibrary(new_web_library_detail);
            });
        }
コード例 #23
0
        public static void GenerateLibraryList()
        {
            if (File.Exists(Definitions.Global.Uplay.ConfigFilePath))
            {
                foreach (var line in File.ReadAllLines(Definitions.Global.Uplay.ConfigFilePath))
                {
                    if (!line.Contains("game_installation_path"))
                    {
                        continue;
                    }

                    var newLine = line.Split(new[] { "  game_installation_path: " }, StringSplitOptions.RemoveEmptyEntries);

                    if (newLine.Length > 0)
                    {
                        if (Directory.Exists(newLine[0]))
                        {
                            AddNewLibraryAsync(newLine[0], true);
                        }
                        else
                        {
                            Logger.Info($"Directory set in the Uplay config file does not exists.\nDirectory path: {newLine[0]}");
                        }
                    }
                    else
                    {
                        Logger.Info("Couldn't parse Uplay config file for 'game_installation_path' - If you can find the value in the file, fill an issue form on github.");
                    }
                }
            }
            else
            {
                Logger.Info("Uplay config file is not found, skipping main uplay library detection.");
            }
        }
コード例 #24
0
        private void IgnoredItems_ButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (var junk in Definitions.List.IgnoredJunkItems.ToList())
                {
                    switch ((string)(sender as Button)?.Tag)
                    {
                    case "remove":

                        break;

                    case "delete":
                        if (File.Exists(junk))
                        {
                            File.Delete(junk);
                        }
                        else if (Directory.Exists(junk))
                        {
                            Directory.Delete(junk, true);
                        }
                        break;
                    }

                    Definitions.List.IgnoredJunkItems.Remove(junk);
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
        }
コード例 #25
0
 private static int PathsMixCollisionComparer(string a, string b)
 {
     // check which of them exists: that one wins
     if (Directory.Exists(a) || File.Exists(a))
     {
         if (!Directory.Exists(b) && !File.Exists(b))
         {
             return(-1);
         }
         else
         {
             Logging.Warn("Both paths exist: '{0}' and '{1}'; taking the longest one: '{2}'.", a, b, (b.CompareTo(a) > 0 ? b : a));
             return(b.CompareTo(a));
         }
     }
     else
     {
         if (Directory.Exists(b) || File.Exists(b))
         {
             return(1);
         }
         else
         {
             Logging.Warn("Both paths DO NOT exist: '{0}' and '{1}'; taking the longest one: '{2}'.", a, b, (b.CompareTo(a) > 0 ? b : a));
             return(b.CompareTo(a));
         }
     }
 }
コード例 #26
0
        private static void DoPostUpgrade()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // NB NB NB NB: You CANT USE ANYTHING IN THE USER CONFIG AT THIS POINT - it is not yet decided until LOGIN has completed...

            WPFDoEvents.InvokeInUIThread(() =>
            {
                StatusManager.Instance.UpdateStatus("AppStart", "Loading themes");
                Theme.Initialize();
                DualTabbedLayout.GetWindowOverride = delegate() { return(new StandardWindow()); };

                // Force tooltips to stay open
                ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(3600000));
            });

            // Make sure the data directories exist...
            if (!Directory.Exists(ConfigurationManager.Instance.BaseDirectoryForUser))
            {
                Directory.CreateDirectory(ConfigurationManager.Instance.BaseDirectoryForUser);
            }

            // and kick off the Login Dialog to start the application proper:
            WPFDoEvents.InvokeAsyncInUIThread(() => ShowLoginDialog());

            // NB NB NB NB: You CANT USE ANYTHING IN THE USER CONFIG AT THIS POINT - it is not yet decided until LOGIN has completed...
        }
コード例 #27
0
        private static void Export_Directories_Tags(Library library, string base_path, Dictionary <string, PDFDocumentExportItem> pdf_document_export_items)
        {
            WshShell shell = new WshShell();

            string tags_base_path = Path.GetFullPath(Path.Combine(base_path, @"tags"));

            Directory.CreateDirectory(tags_base_path);

            foreach (var item in pdf_document_export_items.Values)
            {
                try
                {
                    foreach (string tag in TagTools.ConvertTagBundleToTags(item.pdf_document.Tags))
                    {
                        string tag_base_path = Path.GetFullPath(Path.Combine(tags_base_path, FileTools.MakeSafeFilename(tag)));
                        Directory.CreateDirectory(tag_base_path);
                        string filename = Path.GetFullPath(Path.Combine(tag_base_path, FileTools.MakeSafeFilename(item.pdf_document.TitleCombined) + ".lnk"));
                        CreateShortcut(shell, item.filename, filename);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error creating shortcut for " + item.filename);
                }
            }
        }
コード例 #28
0
        private void ValidateFolder()
        {
            string base_path = "???";

            try
            {
                ButtonJoinCreate.Caption = "Create";

                base_path = TxtPath.Text;
                if (Directory.Exists(base_path))
                {
                    string library_detail_path = IntranetLibraryTools.GetLibraryDetailPath(base_path);
                    if (File.Exists(library_detail_path))
                    {
                        IntranetLibraryDetail library_detail = IntranetLibraryDetail.Read(library_detail_path);
                        TxtTitle.Text            = library_detail.Title;
                        TxtDescription.Text      = library_detail.Description;
                        ButtonJoinCreate.Caption = "Join";
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Warn(ex, "There was an exception while validating the selected Intranet Library path {0}.", base_path);
            }
        }
コード例 #29
0
        public bool OpenConfig(out string errorMessage)
        {
            errorMessage = default;
            try
            {
                if (string.IsNullOrEmpty(this._basePath) || !Directory.Exists(this._basePath))
                {
                    errorMessage = $"{this._basePath} is invalid";
                    return(false);
                }

                var info = new ProcessStartInfo
                {
                    Arguments        = this._basePath,
                    FileName         = "explorer.exe",
                    WorkingDirectory = this._basePath,
                    UseShellExecute  = false
                };
                Process.Start(info);
            }
            catch (Exception e)
            {
                this.Log().Error(e);
                errorMessage = e.Message;
                return(false);
            }

            return(true);
        }
コード例 #30
0
 public static void CreateDirectory(string path)
 {
     if (!Directory.Exists(path))
     {
         Directory.CreateDirectory(path);
     }
 }