private static void RotateCacheFiles([NotNull] FileInfo cacheFile)
        {
            if (cacheFile.Exists)
            {
                double hours = 999.9;
                if (File.Exists(cacheFile.FullName + ".0"))
                {
                    // see when the last rotate was, and only rotate if its been at least an hour since the last save
                    DateTime dt = File.GetLastWriteTime(cacheFile.FullName + ".0");
                    hours = DateTime.Now.Subtract(dt).TotalHours;
                }

                if (hours >= 24.0) // rotate the save file daily
                {
                    for (int i = 8; i >= 0; i--)
                    {
                        string fn = cacheFile.FullName + "." + i;
                        if (File.Exists(fn))
                        {
                            string fn2 = cacheFile.FullName + "." + (i + 1);
                            if (File.Exists(fn2))
                            {
                                File.Delete(fn2);
                            }

                            File.Move(fn, fn2);
                        }
                    }

                    File.Copy(cacheFile.FullName, cacheFile.FullName + ".0");
                }
            }
        }
        private void GenericCustomiseChooser(string title, string filename)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter          = "Image files|*.jpeg;*.jpg;*.png;*.gif;*.bmp" + "|" + "All files|*.*";
            dialog.CheckFileExists = true;
            dialog.Multiselect     = false;
            dialog.Title           = title;
            //dialog.FileName = filename;
            if (true == dialog.ShowDialog())
            {
                // Copy the new file into place, if it is another file than the one we already have:
                filename = Path.GetFullPath(filename);
                string new_filename = Path.GetFullPath(dialog.FileName);
                if (0 != new_filename.CompareTo(filename))
                {
                    File.Delete(filename);
                    File.Copy(new_filename, filename);
                }
            }
            else
            {
                File.Delete(filename);
            }

            UpdateLibraryStatistics();
        }
        /// <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);
            }
        }
        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;
                }
            }
        }
        private void ButtonDocumentSave_Click(object sender, RoutedEventArgs e)
        {
            FeatureTrackingManager.Instance.UseFeature(Features.Document_Save);

            string filename = ExportingTools.MakeExportFilename(pdf_renderer_control_stats.pdf_document);

            //string desktop_directory = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            //filename = Path.GetFullPath(Path.Combine(desktop_directory, filename));

            SaveFileDialog save_file_dialog = new SaveFileDialog();

            save_file_dialog.AddExtension     = true;
            save_file_dialog.CheckPathExists  = true;
            save_file_dialog.DereferenceLinks = true;
            save_file_dialog.OverwritePrompt  = true;
            save_file_dialog.ValidateNames    = true;
            save_file_dialog.DefaultExt       = "pdf";
            save_file_dialog.Filter           = "PDF files|*.pdf" + "|" + "All files|*.*";
            save_file_dialog.FileName         = filename;

            if (true == save_file_dialog.ShowDialog())
            {
                Logging.Info("Saving PDF with fingerprint {1} file to {0}", save_file_dialog.FileName, pdf_renderer_control_stats.pdf_document.Fingerprint);
                File.Copy(pdf_renderer_control_stats.pdf_document.DocumentPath, save_file_dialog.FileName);
            }
        }
        /// <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();
                    }
                }
            }
        }
Exemple #7
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);
        }
Exemple #8
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);
        }
Exemple #9
0
        private async Task InstallManualGameFiles()
        {
            if (!ModList.Directives.Any(d => d.To.StartsWith(Consts.ManualGameFilesDir)))
            {
                return;
            }

            var result = await Utils.Log(new YesNoIntervention("Some mods from this ModList must be installed directly into " +
                                                               "the game folder. Do you want to do this manually or do you want Wabbajack " +
                                                               "to do this for you?", "Move mods into game folder?")).Task;

            if (result != ConfirmationIntervention.Choice.Continue)
            {
                return;
            }

            var manualFilesDir = Path.Combine(OutputFolder, Consts.ManualGameFilesDir);

            var gameFolder = GameInfo.GameLocation();

            Info($"Copying files from {manualFilesDir} " +
                 $"to the game folder at {gameFolder}");

            if (!Directory.Exists(manualFilesDir))
            {
                Info($"{manualFilesDir} does not exist!");
                return;
            }

            await Directory.EnumerateDirectories(manualFilesDir).PMap(Queue, dir =>
            {
                var dirInfo = new DirectoryInfo(dir);
                dirInfo.GetDirectories("*", SearchOption.AllDirectories).Do(d =>
                {
                    var destPath = d.FullName.Replace(manualFilesDir, gameFolder);
                    Status($"Creating directory {destPath}");
                    Directory.CreateDirectory(destPath);
                });

                dirInfo.GetFiles("*", SearchOption.AllDirectories).Do(f =>
                {
                    var destPath = f.FullName.Replace(manualFilesDir, gameFolder);
                    Status($"Copying file {f.FullName} to {destPath}");
                    try
                    {
                        File.Copy(f.FullName, destPath);
                    }
                    catch (Exception)
                    {
                        Info($"Could not copy file {f.FullName} to {destPath}. The file may already exist, skipping...");
                    }
                });
            });
        }
Exemple #10
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);
        }
        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"));
                File.Copy(library_metadata_template_path, library_path);
            }
        }
Exemple #12
0
        public SQLiteUpgrade_LibraryDB(string base_path)
        {
            this.base_path = base_path;
            library_path   = LibraryDB.GetLibraryDBPath(base_path);

            // Copy a library into place...
            if (!File.Exists(library_path))
            {
                Logging.Warn("Library db does not exist so copying the template to {0}", library_path);
                string library_template_path = LibraryDB.GetLibraryDBTemplatePath();
                File.Copy(library_template_path, library_path);
            }
        }
        public SQLiteUpgrade_LibraryDB(string base_path)
        {
            this.base_path = base_path;
            library_path   = Path.GetFullPath(Path.Combine(base_path, @"Qiqqa.library"));

            // Copy a library into place...
            if (!File.Exists(library_path))
            {
                Logging.Warn("Library db does not exist so copying the template to {0}", library_path);
                string library_template_path = Path.GetFullPath(Path.Combine(StartupDirectoryForQiqqa, @"DocumentLibrary/Library.Template.s3db"));
                File.Copy(library_template_path, library_path);
            }
        }
        public override ApprovalException Approve(string approvedPath, string receivedPath)
        {
            if (!File.Exists(approvedPath))
            {
                //return new ApprovalMissingException(receivedPath, approvedPath);

                // Auto-approve BEFORE BeyondCompare gets invoked: generate the approved file on the spot.
                File.Copy(receivedPath, approvedPath, overwrite: true);

                return(null);
            }

            return(base.Approve(approvedPath, receivedPath));
        }
        /// <summary>
        /// Executed as part of the `Approver` logic in
        ///
        /// ```
        /// public static void Verify(IApprovalApprover approver, IApprovalFailureReporter reporter)
        /// {
        ///     if (approver.Approve())
        ///     {
        ///         approver.CleanUpAfterSuccess(reporter);
        ///     }
        ///     else
        ///     {
        ///         approver.ReportFailure(reporter);
        ///
        ///         if (reporter is IReporterWithApprovalPower power && power.ApprovedWhenReported())
        ///                                                                   ^^^^^^^^^^^^^^^^^^^^^^
        ///         {
        ///             approver.CleanUpAfterSuccess(power);
        ///         }
        ///         else
        ///         {
        ///             approver.Fail();
        ///         }
        ///     }
        /// }
        /// ```
        /// </summary>
        /// <returns>Return `false` when NOT approved automatically after all; `true` when this code auto-approves the test output,
        /// e.g. when the `*.approved.*` reference file does not (yet) exist.</returns>
        bool IReporterWithApprovalPower.ApprovedWhenReported()
        {
            if (!File.Exists(received))
            {
                return(false);
            }
#if false
            File.Delete(this.approved);
#endif
            if (File.Exists(approved))
            {
                return(false);
            }
            File.Copy(received, approved);
            return(File.Exists(approved));
        }
Exemple #16
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);
            }
        }
        public LibraryDB(WebLibraryDetail web_library_detail)
        {
            base_path    = web_library_detail.LIBRARY_BASE_PATH;
            library_path = LibraryDB.GetLibraryDBPath(base_path);
            string db_syncref_path = IntranetLibraryTools.GetLibraryMetadataPath(base_path);

            // Copy a library into place...
            // but only if this is not a Internet sync directory/DB!
            if (File.Exists(db_syncref_path))
            {
                throw new Exception(String.Format("MUST NOT attempt to create a regular Qiqqa library in the Qiqqa Internet/Intranet Sync directory: '{0}'", base_path));
            }
            if (!File.Exists(library_path))
            {
                Logging.Warn($"Library db for '{web_library_detail.Id}' does not exist so copying the template to '{library_path}'");
                string library_template_path = LibraryDB.GetLibraryDBTemplatePath();
                File.Copy(library_template_path, library_path);
            }
        }
Exemple #18
0
        public LibraryDB(string base_path)
        {
            this.base_path = base_path;
            library_path   = LibraryDB.GetLibraryDBPath(base_path);
            string db_syncref_path = IntranetLibraryTools.GetLibraryMetadataPath(base_path);

            // Copy a library into place...
            // but only if this is not a Internet sync directory/DB!
            if (File.Exists(db_syncref_path))
            {
                throw new Exception(String.Format("MUST NOT attempt to create a regular Qiqqa library in the Qiqqa Internet/Intranet Sync directory: '{0}'", base_path));
            }
            if (!File.Exists(library_path))
            {
                Logging.Warn("Library db does not exist so copying the template to {0}", library_path);
                string library_template_path = LibraryDB.GetLibraryDBTemplatePath();
                File.Copy(library_template_path, library_path);
            }
        }
Exemple #19
0
        private static Dictionary <string, PDFDocumentExportItem> Export_Docs(Library library, List <PDFDocument> pdf_documents, string base_path)
        {
            // Where the original docs go
            string doc_base_path_original = Path.GetFullPath(Path.Combine(base_path, @"docs_original"));

            Directory.CreateDirectory(doc_base_path_original);

            // Where the modified docs go
            string doc_base_path = Path.GetFullPath(Path.Combine(base_path, @"docs"));

            Directory.CreateDirectory(doc_base_path);

            Dictionary <string, PDFDocumentExportItem> pdf_document_export_items = new Dictionary <string, PDFDocumentExportItem>();

            foreach (PDFDocument pdf_document in pdf_documents)
            {
                try
                {
                    if (File.Exists(pdf_document.DocumentPath))
                    {
                        // The original docs
                        string filename_original = Path.GetFullPath(Path.Combine(doc_base_path_original, ExportingTools.MakeExportFilename(pdf_document)));
                        File.Copy(pdf_document.DocumentPath, filename_original, true);

                        // The modified docs
                        string filename = Path.GetFullPath(Path.Combine(doc_base_path, ExportingTools.MakeExportFilename(pdf_document)));
                        File.Copy(pdf_document.DocumentPath, filename, true);

                        // And the ledger entry
                        PDFDocumentExportItem item = new PDFDocumentExportItem();
                        item.pdf_document = pdf_document;
                        item.filename     = filename;
                        pdf_document_export_items[item.pdf_document.Fingerprint] = item;
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Error copying file from {0}", pdf_document.DocumentPath);
                }
            }

            return(pdf_document_export_items);
        }
Exemple #20
0
 public static void Rotate(string filenameBase)
 {
     if (File.Exists(filenameBase))
     {
         for (int i = 8; i >= 0; i--)
         {
             string fn = filenameBase + "." + i;
             if (File.Exists(fn))
             {
                 string fn2 = filenameBase + "." + (i + 1);
                 if (File.Exists(fn2))
                 {
                     File.Delete(fn2);
                 }
                 File.Move(fn, fn2);
             }
         }
         File.Copy(filenameBase, filenameBase + ".0");
     }
 }
Exemple #21
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.");
                    }
                }
            }
        }
Exemple #22
0
        public async Task TestDuplicateFilesAreCopied()
        {
            var profile  = utils.AddProfile();
            var mod      = utils.AddMod();
            var test_pex = utils.AddModFile(mod, @"Data\scripts\test.pex", 10);

            // Make a copy to make sure it gets picked up and moved around.
            File.Copy(test_pex, test_pex + ".copy");

            utils.Configure();

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

            await CompileAndInstall(profile);

            utils.VerifyInstalledFile(mod, @"Data\scripts\test.pex");
            utils.VerifyInstalledFile(mod, @"Data\scripts\test.pex.copy");
        }
Exemple #23
0
 public override void Copy(string sourceFileName, string destFileName, bool overwrite)
 {
     AfsFile.Copy(sourceFileName, destFileName, overwrite);
 }