Esempio n. 1
0
 /// <summary>
 /// ctor is responsible for parsing the file
 /// </summary>
 protected FileImporter(WebLibraryDetail web_library_detail, string fileName)
 {
     Entries          = new List <BibTeXEntry>();
     ImportLibrary    = web_library_detail;
     ExportFileName   = fileName;
     _exportDirectory = Path.GetDirectoryName(fileName);
 }
Esempio n. 2
0
        public static void Export(Library library, List <PDFDocument> pdf_documents)
        {
            FeatureTrackingManager.Instance.UseFeature(Features.Library_Export);

            // Get the directory
            string initial_directory = null;

            if (null == initial_directory)
            {
                initial_directory = Path.GetDirectoryName(ConfigurationManager.Instance.ConfigurationRecord.System_LastLibraryExportFolder);
            }
            if (null == initial_directory)
            {
                initial_directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }

            using (FolderBrowserDialog dlg = new FolderBrowserDialog
            {
                Description = "Please select the folder to which you wish to export your entire Qiqqa library.",
                SelectedPath = initial_directory,
                ShowNewFolderButton = true
            })
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    // Remember the filename for next time
                    string base_path = dlg.SelectedPath;
                    ConfigurationManager.Instance.ConfigurationRecord.System_LastLibraryExportFolder = base_path;
                    ConfigurationManager.Instance.ConfigurationRecord_Bindable.NotifyPropertyChanged(() => ConfigurationManager.Instance.ConfigurationRecord.System_LastLibraryExportFolder);

                    SafeThreadPool.QueueUserWorkItem(o => Export(library, pdf_documents, base_path));
                }
            }
        }
        private static string ConvertNormalFilenameToZoteroFilename(string bibtex_base_filename, string filename)
        {
            string bibtex_base_path = Path.GetDirectoryName(bibtex_base_filename);

            string file = Path.GetFileName(filename);
            string path = filename;

            /// Try shrink it to a relative path
            if (path.StartsWith(bibtex_base_path))
            {
                path = path.Substring(bibtex_base_path.Length + 1);
            }
            else
            {
                Logging.Warn("Unable to convert path to Zotero form: {0}", path);
            }

            // Replace the slashes
            path = path.Replace('\\', '/');

            // Concatenate
            string export_string =
                ""
                + file
                + ":"
                + path
                + ":"
                + "application/pdf";

            return(export_string);
        }
Esempio n. 4
0
 /// <summary>
 /// ctor is responsible for parsing the file
 /// </summary>
 protected FileImporter(Library library, string fileName)
 {
     Entries          = new List <BibTeXEntry>();
     ImportLibrary    = library;
     ExportFileName   = fileName;
     _exportDirectory = Path.GetDirectoryName(fileName);
 }
        public IntranetLibraryDB(string base_path)
        {
            this.base_path = base_path;
            library_path   = IntranetLibraryTools.GetLibraryMetadataPath(base_path);

            // Copy a library into place...
            if (!File.Exists(library_path))
            {
                Logging.Warn("Intranet Library metadata db does not exist so copying the template to {0}", library_path);
                string library_metadata_template_path = Path.GetFullPath(Path.Combine(ConfigurationManager.Instance.StartupDirectoryForQiqqa, @"DocumentLibrary/IntranetLibraryStuff/IntranetLibrary.Metadata.Template.s3db"));
                if (!File.Exists(library_metadata_template_path))
                {
                    throw new Exception($"Sync template file '{library_metadata_template_path}' does not exist!");
                }
                string basedir = Path.GetDirectoryName(library_path);
                if (!Directory.Exists(basedir))
                {
                    throw new Exception($"Sync target directory '{basedir}' for Qiqqa database '{library_path}' does not exist!");
                }
                try
                {
                    File.Copy(library_metadata_template_path, library_path);
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error 0x{2:08X}: Failed to write the sync template '{0}' to sync target directory '{1}'", library_metadata_template_path, basedir, ex.HResult);
                    throw;
                }
            }
        }
        public static void Export(WebLibraryDetail web_library_detail, List <PDFDocument> pdf_documents)
        {
            FeatureTrackingManager.Instance.UseFeature(Features.Library_Export);

            // Get the directory
            string initial_directory = null;

            if (null == initial_directory)
            {
                initial_directory = Path.GetDirectoryName(ConfigurationManager.Instance.ConfigurationRecord.System_LastLibraryExportFolder);
            }
            if (null == initial_directory)
            {
                initial_directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }

            using (CommonOpenFileDialog dialog = new CommonOpenFileDialog())
            {
                dialog.IsFolderPicker   = true;
                dialog.Title            = "Please select the folder to which you wish to export your entire Qiqqa library.";
                dialog.DefaultDirectory = initial_directory;
                CommonFileDialogResult result = dialog.ShowDialog();
                if (result == CommonFileDialogResult.Ok)
                {
                    // Remember the filename for next time
                    string base_path = dialog.FileName;
                    ConfigurationManager.Instance.ConfigurationRecord.System_LastLibraryExportFolder = base_path;
                    ConfigurationManager.Instance.ConfigurationRecord_Bindable.NotifyPropertyChanged(nameof(ConfigurationManager.Instance.ConfigurationRecord.System_LastLibraryExportFolder));

                    SafeThreadPool.QueueUserWorkItem(o => Export(web_library_detail, pdf_documents, base_path));
                }
            }
        }
Esempio n. 7
0
        /// <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);
            }
        }
        private void ChooseCSLFile(CSLFileSource csl_file_source)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter          = "CSL style files|*.csl" + "|" + "All files|*.*";
            dialog.CheckFileExists = true;
            dialog.Multiselect     = false;

            string filename  = null;
            string directory = null;

            // Decide what we want to use as the CSL file location
            if (CSLFileSource.TEXTBOX == csl_file_source)
            {
                try
                {
                    CorrectStyleFilenameForNewDirectoryLocation();
                    directory = Path.GetDirectoryName(ConfigurationManager.Instance.ConfigurationRecord.InCite_LastStyleFile);
                    filename  = Path.GetFileName(ConfigurationManager.Instance.ConfigurationRecord.InCite_LastStyleFile);

                    // If the directory no longer exists, kill our memory of it.  We will pick the default directory again.
                    if (!Directory.Exists(directory))
                    {
                        directory = null;
                    }
                }
                catch { }
            }
            if (null == directory)
            {
                directory = PDFDocumentCitingTools.BASE_STYLE_DIRECTORY;
            }

            // Set the dialog defaults
            dialog.FileName         = filename;
            dialog.InitialDirectory = directory;

            // Get the user response
            if (true == dialog.ShowDialog())
            {
                ConfigurationManager.Instance.ConfigurationRecord.InCite_LastStyleFile = dialog.FileName;
                ConfigurationManager.Instance.ConfigurationRecord_Bindable.NotifyPropertyChanged(() => ConfigurationManager.Instance.ConfigurationRecord.InCite_LastStyleFile);

                // Check if it is a dependent style
                string style_xml_filename  = ConfigurationManager.Instance.ConfigurationRecord.InCite_LastStyleFile;
                string root_style_filename = DependentStyleDetector.GetRootStyleFilename(style_xml_filename);
                if (root_style_filename != style_xml_filename)
                {
                    if (null != root_style_filename)
                    {
                        MessageBoxes.Info("This style is dependent on another style, so InCite will be using this file instead:\n" + root_style_filename);
                    }
                    else
                    {
                        MessageBoxes.Info("This style is dependent on another style that is not available on your computer.  Please download it before proceeding.");
                    }
                }
            }
        }
Esempio n. 9
0
        public void WriteMasterList()
        {
            Logging.Info("+WriteMasterList");

            string filename_temp = Path.GetTempFileName();

            Utilities.LockPerfTimer l1_clk = Utilities.LockPerfChecker.Start();
            lock (locker)
            {
                l1_clk.LockPerfTimerStop();
                FlushAllWords_LOCK();
                PurgeAllWords_LOCK();

                using (FileStream fs = File.Open(filename_temp, FileMode.Create))
                {
                    Headers headers = new Headers();

                    // First the documents
                    {
                        headers.documents = new List <DocumentMapHeader>();
                        foreach (var pair in fingerprint_to_document_ids)
                        {
                            DocumentMapHeader header = new DocumentMapHeader
                            {
                                Fingerprint = pair.Key,
                                DocumentId  = pair.Value
                            };
                            headers.documents.Add(header);
                        }
                    }

                    // Then the words
                    {
                        headers.words = new List <WordMapHeader>();
                        foreach (WordInWordIndex word_in_word_index in word_in_word_indexes)
                        {
                            WordMapHeader header = new WordMapHeader
                            {
                                Word     = word_in_word_index.Word,
                                WordId   = word_in_word_index.WordId,
                                DocCount = word_in_word_index.DocumentCount
                            };
                            headers.words.Add(header);
                        }
                    }

                    Serializer.Serialize <Headers>(fs, headers);
                }
            }

            Logging.Info("-WriteMasterList");

            // Move the temp file over the library filename
            Directory.CreateDirectory(Path.GetDirectoryName(GetFilename_MasterList()));
            FileTools.MoveSafelyWithOverwriting(filename_temp, GetFilename_MasterList());

            // Write the version of the index
            File.WriteAllText(VersionFilename, INDEX_VERSION);
        }
        public void SaveTempLocaleTable(string locale, LocaleTable locale_table)
        {
            string filename = GetFilenameForTempLocale(locale);

            Directory.CreateDirectory(Path.GetDirectoryName(filename));
            locale_table.Save(filename);
            Logging.Info("Saved locale {0}", locale);
        }
Esempio n. 11
0
        public async Task TestUpdating()
        {
            var profile   = utils.AddProfile();
            var mod       = utils.AddMod();
            var unchanged = utils.AddModFile(mod, @"Data\scripts\unchanged.pex", 10);
            var deleted   = utils.AddModFile(mod, @"Data\scripts\deleted.pex", 10);
            var modified  = utils.AddModFile(mod, @"Data\scripts\modified.pex", 10);

            utils.Configure();

            utils.AddManualDownload(
                new Dictionary <string, byte[]>
            {
                { "/baz/unchanged.pex", File.ReadAllBytes(unchanged) },
                { "/baz/deleted.pex", File.ReadAllBytes(deleted) },
                { "/baz/modified.pex", File.ReadAllBytes(modified) },
            });

            await CompileAndInstall(profile);

            utils.VerifyInstalledFile(mod, @"Data\scripts\unchanged.pex");
            utils.VerifyInstalledFile(mod, @"Data\scripts\deleted.pex");
            utils.VerifyInstalledFile(mod, @"Data\scripts\modified.pex");

            var unchanged_path = utils.PathOfInstalledFile(mod, @"Data\scripts\unchanged.pex");
            var deleted_path   = utils.PathOfInstalledFile(mod, @"Data\scripts\deleted.pex");
            var modified_path  = utils.PathOfInstalledFile(mod, @"Data\scripts\modified.pex");

            var extra_path = utils.PathOfInstalledFile(mod, @"something_i_made.foo");

            File.WriteAllText(extra_path, "bleh");

            var extra_folder = Path.Combine(Path.GetDirectoryName(utils.PathOfInstalledFile(mod, @"something_i_made.foo")), "folder_i_made");

            Directory.CreateDirectory(extra_folder);

            Assert.IsTrue(Directory.Exists(extra_folder));


            var unchanged_modified = File.GetLastWriteTime(unchanged_path);
            var modified_modified  = File.GetLastWriteTime(modified_path);

            File.WriteAllText(modified_path, "random data");
            File.Delete(deleted_path);

            Assert.IsTrue(File.Exists(extra_path));

            await CompileAndInstall(profile);

            utils.VerifyInstalledFile(mod, @"Data\scripts\unchanged.pex");
            utils.VerifyInstalledFile(mod, @"Data\scripts\deleted.pex");
            utils.VerifyInstalledFile(mod, @"Data\scripts\modified.pex");

            Assert.AreEqual(unchanged_modified, File.GetLastWriteTime(unchanged_path));
            Assert.AreNotEqual(modified_modified, File.GetLastWriteTime(modified_path));
            Assert.IsFalse(File.Exists(extra_path));
            Assert.IsFalse(Directory.Exists(extra_folder));
        }
Esempio n. 12
0
        /// <summary>
        /// Saves settings to location specified
        /// </summary>
        /// <param name="path">Path to settings file</param>
        public void Save(string path)
        {
            using (var mutex = new Mutex(false, mutexId))
            {
                bool hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(5000, false);
                        if (hasHandle == false)
                        {
                            logger.Info("Timeout waiting for exclusive access to save app settings.");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // The mutex was abandoned in another process,
                        // it will still get acquired
                        hasHandle = true;
                    }

                    // Perform work here.
                    if (!Directory.Exists(Path.GetDirectoryName(path)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                    }

                    // 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 save app settings: " + ex.Message, ex);
                }
                finally
                {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
        public ZoteroImporter(Library library, string filename)
            : base(library, filename)
        {
            FeatureTrackingManager.Instance.UseFeature(Features.Library_ImportFromZotero);

            // For Zotero export, the files all live under \Files,
            // e.g. if export is c:\temp\bla.bib, a file might be c:\temp\files\20\foo.pdf
            _importBasePath = Path.GetDirectoryName(filename);
        }
        internal static string GetRootStyleFilename(string style_xml_filename)
        {
            string parent_filename;
            string parent_url;

            if (IsDependentStyle(style_xml_filename, out parent_filename, out parent_url))
            {
                // Check that we have the dependent style - if we don't prompt to download it
                string full_parent_filename = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(style_xml_filename), parent_filename));
                if (!File.Exists(full_parent_filename))
                {
                    string message = String.Format(
                        "Can't find parent style for this dependent style" +
                        "\n\n" +
                        "Your style depends on a parent style named {0}, which needs to be saved in the same directory.\n\n" +
                        "It appears to be available from {1}.\n" +
                        "Shall we try to download it automatically?  If you choose NO, Qiqqa will open the website for you so you can download it manually.",
                        parent_filename, parent_url
                        );

                    if (MessageBoxes.AskQuestion(message))
                    {
                        try
                        {
                            using (MemoryStream ms = UrlDownloader.DownloadWithBlocking(parent_url))
                            {
                                File.WriteAllBytes(full_parent_filename, ms.ToArray());
                            }
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            Logging.Error(ex, "You don't seem to have permission to write the new style to the directory '{0}'.\nPlease copy the original style file '{1}' to a folder where you can write (perhaps alongside your Word document), and try again.", full_parent_filename, style_xml_filename);
                            MessageBoxes.Warn("You don't seem to have permission to write the new style to the directory '{0}'.\nPlease copy the original style file '{1}' to a folder where you can write (perhaps alongside your Word document), and try again.", full_parent_filename, style_xml_filename);
                        }
                    }
                    else
                    {
                        MainWindowServiceDispatcher.Instance.OpenUrlInBrowser(parent_url, true);
                    }
                }

                // Check again if the parent file exists, and if it does, recurse the dependency check
                if (File.Exists(full_parent_filename))
                {
                    return(GetRootStyleFilename(full_parent_filename));
                }
                else
                {
                    // We need the parent style, but haven't managed to download it, so return nothing...
                    return(null);
                }
            }
            else // Not a dependent style, so use this filename
            {
                return(style_xml_filename);
            }
        }
Esempio n. 15
0
        internal string StorePageTextGroup(int page, string source_filename)
        {
            string filename = MakeFilename_TextGroup(page);

            Directory.CreateDirectory(Path.GetDirectoryName(filename));
            File.Copy(source_filename, filename, true);
            File.Delete(source_filename);
            return(filename);
        }
Esempio n. 16
0
        internal void StorePageTextSingle(int page, string source_filename)
        {
            string filename = MakeFilename_TextSingle(page);

            Directory.CreateDirectory(Path.GetDirectoryName(filename));
            File.Copy(source_filename, filename, true);
            File.Delete(source_filename);

            OnPageTextAvailable?.Invoke(page, page);
        }
Esempio n. 17
0
        public override void OpenFile(OpenFileArgs args)
        {
            string tempFolder    = Path.Combine(Utils.GetTempFolder(), "dnGREP-Archive", Utils.GetHash(args.SearchResult.FileNameReal));
            string innerFileName = args.SearchResult.FileNameDisplayed.Substring(args.SearchResult.FileNameReal.Length).TrimStart(Path.DirectorySeparatorChar);
            string filePath      = Path.Combine(tempFolder, innerFileName);

            if (!File.Exists(filePath))
            {
                // use the directory name to also include folders within the archive
                string directory = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string zipFile = args.SearchResult.FileNameReal;
                if (zipFile.Length > 260 && !zipFile.StartsWith(@"\\?\"))
                {
                    zipFile = @"\\?\" + zipFile;
                }

                using (SevenZipExtractor extractor = new SevenZipExtractor(zipFile))
                {
                    if (extractor.ArchiveFileData.Where(r => r.FileName == innerFileName && !r.IsDirectory).Any())
                    {
                        using (FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            try
                            {
                                extractor.ExtractFile(innerFileName, stream);
                            }
                            catch
                            {
                                args.UseBaseEngine = true;
                            }
                        }
                    }
                }
            }

            if (Utils.IsPdfFile(filePath) || Utils.IsWordFile(filePath) || Utils.IsExcelFile(filePath))
            {
                args.UseCustomEditor = false;
            }

            GrepSearchResult newResult = new GrepSearchResult
            {
                FileNameReal      = args.SearchResult.FileNameReal,
                FileNameDisplayed = args.SearchResult.FileNameDisplayed
            };
            OpenFileArgs newArgs = new OpenFileArgs(newResult, args.Pattern, args.LineNumber, args.FirstMatch, args.ColumnNumber, args.UseCustomEditor, args.CustomEditor, args.CustomEditorArgs);

            newArgs.SearchResult.FileNameDisplayed = filePath;
            Utils.OpenFile(newArgs);
        }
Esempio n. 18
0
        static VirtualFileSystem()
        {
            VFS = new VirtualFileSystem();
            var entry = Assembly.GetEntryAssembly();

            if (entry != null && !string.IsNullOrEmpty(entry.Location))
            {
                RootFolder  = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                _stagedRoot = Path.Combine(RootFolder, "vfs_staged_files");
            }
        }
Esempio n. 19
0
        public static void SaveObject(string filename, object obj)
        {
            // Make sure the path exists
            string pathname = Path.GetDirectoryName(filename);

            Directory.CreateDirectory(pathname);

            using (FileStream fs = File.OpenWrite(filename))
            {
                SaveObject(fs, obj);
            }
        }
Esempio n. 20
0
        internal static void DaemonPut(Library library, string fingerprint)
        {
            string filename_full  = PDFDocumentFileLocations.DocumentPath(library, fingerprint, "pdf");
            string filename_short = Path.GetFileName(filename_full);
            string pdf_path       = IntranetLibraryTools.GetLibraryPDFPath(library.WebLibraryDetail.IntranetPath, filename_short);

            DirectoryTools.CreateDirectory(Path.GetDirectoryName(pdf_path));

            Logging.Info("+Copying up {0}", fingerprint);
            File.Copy(filename_full, pdf_path);
            Logging.Info("-Copying up {0}", fingerprint);
        }
Esempio n. 21
0
        /// <summary>
        /// Adds a file to the given mod with a given path in the mod. Fills it with random data unless
        /// random_fill == 0;
        /// </summary>
        /// <param name="mod_name"></param>
        /// <param name="path"></param>
        /// <param name="random_fill"></param>
        /// <returns></returns>
        public string AddModFile(string mod_name, string path, int random_fill = 128)
        {
            byte[] bytes = new byte[0];
            if (random_fill != 0)
            {
                bytes = new byte[random_fill];
                RNG.NextBytes(bytes);
            }

            var full_path = Path.Combine(ModsFolder, mod_name, path);

            Directory.CreateDirectory(Path.GetDirectoryName(full_path));
            File.WriteAllBytes(full_path, bytes);
            return(full_path);
        }
Esempio n. 22
0
        public void Dispose()
        {
            // if long path, delete folder from the top of the long path
            string folder = destinationFolder;

            while (folder.Contains("aaaaaaaaaaaaaaaaaaaa"))
            {
                folder = Path.GetDirectoryName(folder);
            }

            if (Directory.Exists(folder))
            {
                Utils.DeleteFolder(folder);
            }
        }
Esempio n. 23
0
 private bool CheckHidden(FileFilter filter, string fileName, List <string> hiddenDirectories)
 {
     if (!filter.IncludeHidden && hiddenDirectories.Count > 0)
     {
         string path = Path.GetDirectoryName(fileName);
         foreach (var dir in hiddenDirectories)
         {
             if (path.Contains(dir))
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Esempio n. 24
0
        /// </summary>
        // Iterates through each file entry within the supplied tar,
        // extracting them to the nominated folder.
        /// </summary>
        public static void ExtractTarByEntry(TarInputStream tarIn, string targetDir)
        {
            TarEntry tarEntry;

            while ((tarEntry = tarIn.GetNextEntry()) != null)
            {
                // Converts the unix forward slashes in the filenames to windows backslashes
                string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar);

                // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine
                if (Path.IsPathRooted(name))
                {
                    name = name.Substring(System.IO.Path.GetPathRoot(name).Length);
                }

                // Apply further name transformations here as necessary
                string outName = Path.Combine(targetDir, name);

                string directoryName = Path.GetDirectoryName(outName);

                try {
                    if (tarEntry.IsDirectory)
                    {
                        Directory.CreateDirectory(outName);
                        continue;
                    }

                    // Does nothing if directory exists
                    Directory.CreateDirectory(directoryName);

                    try {
                        using (var outStr = File.Open(outName, FileMode.Create)) {
                            tarIn.CopyEntryContents(outStr);
                        }

                        // Set the modification date/time. This approach seems to solve timezone issues.
                        DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc);
                        File.SetLastWriteTime(outName, myDt);
                    } catch (NotSupportedException) {
                        Console.WriteLine($"[!] invalid file name: {outName}");
                    } catch (PathTooLongException) {
                        Console.WriteLine($"[!] file name too long?! {outName}");
                    }
                } catch (NotSupportedException) {
                    Console.WriteLine($"[!] invalid directory name: {directoryName}");
                }
            }
        }
Esempio n. 25
0
        private static void DoDirectCopy(string vmBackupPath, 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);
                    DoDirectCopy(vmBackupPath, snapshotPath, volumePathLength, childPath);
                }
            }
            else if (File.Exists(srcPath))
            {
                var outputName = Path.Combine(vmBackupPath, vmPath.Substring(volumePathLength));
                using (var s = File.OpenRead(srcPath))
                {
                    var folder = Path.GetDirectoryName(outputName);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    using (var ns = File.Create(outputName))
                    {
                        s.CopyTo(ns);
                    }
                }
            }
            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");
                }
            }
        }
Esempio n. 26
0
        internal void StorePageTextGroup(int page, int TEXT_PAGES_PER_GROUP, string source_filename)
        {
            string filename = MakeFilename_TextGroup(page);

            Directory.CreateDirectory(Path.GetDirectoryName(filename));
            File.Copy(source_filename, filename, true);
            File.Delete(source_filename);

            if (null != OnPageTextAvailable)
            {
                int page_range_start = ((page - 1) / TEXT_PAGES_PER_GROUP) * TEXT_PAGES_PER_GROUP + 1;
                int page_range_end   = page_range_start + TEXT_PAGES_PER_GROUP - 1;
                page_range_end = Math.Min(page_range_end, PageCount);

                OnPageTextAvailable?.Invoke(page_range_start, page_range_end);
            }
        }
Esempio n. 27
0
        public string ExtractToTempFile(GrepSearchResult searchResult)
        {
            string tempFolder    = Path.Combine(Utils.GetTempFolder(), "dnGREP-Archive", Utils.GetHash(searchResult.FileNameReal));
            string innerFileName = searchResult.FileNameDisplayed.Substring(searchResult.FileNameReal.Length).TrimStart(Path.DirectorySeparatorChar);
            string filePath      = Path.Combine(tempFolder, innerFileName);

            if (!File.Exists(filePath))
            {
                // use the directory name to also include folders within the archive
                string directory = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string zipFile = searchResult.FileNameReal;
                if (zipFile.Length > 260 && !zipFile.StartsWith(@"\\?\"))
                {
                    zipFile = @"\\?\" + zipFile;
                }

                using (SevenZipExtractor extractor = new SevenZipExtractor(zipFile))
                {
                    if (extractor.ArchiveFileData.Where(r => r.FileName == innerFileName && !r.IsDirectory).Any())
                    {
                        using (FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            try
                            {
                                extractor.ExtractFile(innerFileName, stream);
                            }
                            catch (Exception ex)
                            {
                                logger.Log <Exception>(LogLevel.Error, string.Format("Failed extract file {0} from archive '{1}'", innerFileName, searchResult.FileNameReal), ex);
                            }
                        }
                    }
                }
            }

            return(filePath);
        }
Esempio n. 28
0
        public static string ExtractToTempFile(GrepSearchResult searchResult)
        {
            if (searchResult == null)
            {
                throw new ArgumentNullException(nameof(searchResult));
            }

            string tempFolder = Path.Combine(Utils.GetTempFolder(), "dnGREP-Archive", Utils.GetHash(searchResult.FileNameReal));

            string[] parts = searchResult.FileNameDisplayed.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (!searchResult.FileNameDisplayed.Contains(ArchiveSeparator) || parts.Length < 2)
            {
                return(string.Empty);
            }
            string innerFileName = parts.Last();

            string[] intermediateFiles = parts.Skip(1).Take(parts.Length - 2).ToArray();
            string   filePath          = Path.Combine(tempFolder, innerFileName);

            if (!File.Exists(filePath))
            {
                // use the directory name to also include folders within the archive
                string directory = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string zipFile = searchResult.FileNameReal;
                if (zipFile.Length > 260 && !zipFile.StartsWith(@"\\?\", StringComparison.InvariantCulture))
                {
                    zipFile = @"\\?\" + zipFile;
                }

                using (FileStream input = File.Open(zipFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    ExtractToTempFile(input, filePath, searchResult.FileNameReal, innerFileName, intermediateFiles);
                }
            }

            return(filePath);
        }
Esempio n. 29
0
        internal static void DaemonGet(Library library, string fingerprint)
        {
            string filename_full  = PDFDocumentFileLocations.DocumentPath(library, fingerprint, "pdf");
            string filename_short = Path.GetFileName(filename_full);
            string pdf_path       = IntranetLibraryTools.GetLibraryPDFPath(library.WebLibraryDetail.IntranetPath, filename_short);

            DirectoryTools.CreateDirectory(Path.GetDirectoryName(filename_full));

            Logging.Info("+Copying down {0}", fingerprint);
            File.Copy(pdf_path, filename_full);
            Logging.Info("-Copying down {0}", fingerprint);

            // Write the audit
            if (true)
            {
                string audit_filename  = IntranetLibraryTools.GetLibraryAuditFilename(library.WebLibraryDetail.IntranetPath);
                string audit_directory = Path.GetDirectoryName(audit_filename);

                if (Directory.Exists(audit_directory))
                {
                    string audit_data = String.Format(
                        "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\r\n"
                        , DateTime.UtcNow.ToString("yyyyMMdd.hhmmss")
                        , ConfigurationManager.Instance.ConfigurationRecord.Account_Username
                        , ConfigurationManager.Instance.ConfigurationRecord.Account_Nickname
                        , Environment.UserName
                        , filename_short
                        , pdf_path
                        );

                    try
                    {
                        File.AppendAllText(audit_filename, audit_data);
                    }
                    catch (Exception ex)
                    {
                        Logging.Warn(ex, "Unable to write intranet sync audit data.");
                    }
                }
            }
        }
Esempio n. 30
0
        public void RegenFolderRecords()
        {
            _folders = _files.GroupBy(f => Path.GetDirectoryName(f.Path.ToLowerInvariant()))
                       .Select(f => new FolderRecordBuilder(this, f.Key, f.ToList()))
                       .OrderBy(f => f._hash)
                       .ToList();

            var lnk = _files.Where(f => f.Path.EndsWith(".lnk")).FirstOrDefault();

            foreach (var folder in _folders)
            {
                foreach (var file in folder._files)
                {
                    file._folder = folder;
                }
            }

            _files = (from folder in _folders
                      from file in folder._files
                      orderby folder._hash, file._hash
                      select file).ToList();
        }