예제 #1
0
        public static void ValidateDataDirectory(string bundledDataDirectory, string dataDirectory)
        {
            if (!Directory.Exists(dataDirectory))
            {
                Directory.CreateDirectory(dataDirectory);
            }

            foreach (var bundledDataPath in Directory.GetFiles(bundledDataDirectory))
            {
                var data     = Path.GetFileName(bundledDataPath);
                var dataPath = Path.Combine(dataDirectory, data.NonNull());
                if (!File.Exists(dataPath))
                {
                    File.Copy(bundledDataPath, dataPath);
                }
                else
                {
                    var time1 = FileInfo.FromFileName(bundledDataPath).LastWriteTimeUtc;
                    var time2 = FileInfo.FromFileName(dataPath).LastWriteTimeUtc;
                    if (time1 != time2)
                    {
                        File.Copy(bundledDataPath, dataPath, true);
                    }
                }
            }
        }
            public void Refresh(ImportAssetOptions options = ImportAssetOptions.Default)
            {
                logger.Verbose("Refreshing assets...");

                foreach (var asset in importedAssets)
                {
                    string metaPath = Path.ChangeExtension(asset, ".meta");

                    if (!file.Exists(metaPath))
                    {
                        file.Copy(asset, metaPath);
                    }
                }
            }
        public void StoreVersion(IResource resource, string userName, string reason, Guid workSpaceId, string resourcePath)
        {
            if (workSpaceId == Guid.Empty)
            {
                if (string.IsNullOrEmpty(userName))
                {
                    userName = Thread.CurrentPrincipal.Identity.Name;
                }

                lock (LockObject)
                {
                    var old = _catalogue.GetResource(Guid.Empty, resource.ResourceID);
                    if (old != null)
                    {
                        var versions = GetVersions(resource.ResourceID).FirstOrDefault();
                        old.VersionInfo = _versionStrategy.GetCurrentVersion(resource, versions?.VersionInfo, userName, reason);
                        var folderPath = GetVersionFolderFromResource(old.GetResourcePath(workSpaceId));

                        var fileName = $"{old.VersionInfo.VersionId}_{old.VersionInfo.VersionNumber}_{GetDateString(old.VersionInfo.DateTimeStamp)}_{reason}.xml";
                        if (!_file.Exists(Path.Combine(folderPath, fileName))) //todo: remove this and stop save on workspace
                        {
                            var sourceFile = Path.Combine(GetFolderFromResource(old.GetResourcePath(workSpaceId)), old.ResourceName) + ".xml";
                            if (_file.Exists(sourceFile))
                            {
                                _file.Copy(sourceFile, Path.Combine(folderPath, fileName));
                            }
                        }

                        resource.VersionInfo = _versionStrategy.GetNextVersion(resource, old, userName, reason);
                    }
                }
            }
        }
예제 #4
0
        private void CopyFile(string sourceFile, string dest)
        {
            var copied   = false;
            var attempts = 0;

            while (!copied)
            {
                try
                {
                    var destFolder = Path.GetDirectoryName(dest);
                    if (!_directory.Exists(destFolder))
                    {
                        _directory.CreateDirectory(destFolder);
                    }
                    _file.Copy(sourceFile, dest, true);
                    copied = true;
                }
                catch (Exception ex)
                {
                    Thread.Sleep(500);
                    attempts++;
                    if (attempts >= 10)
                    {
                        _messenger.Send(
                            new LogMessage(string.Format("Failed to copy {0} to {1}: {2}", sourceFile, dest, ex.Message)));
                        break;
                    }
                }
            }
        }
예제 #5
0
        private void MoveLogFileIfOld()
        {
            var newFilePath = _detailedLogFile.GetNewFileName();

            _fileWrapper.Copy(_detailedLogFile.LogFilePath, Path.Combine(_detailedLogFile.LogFilePath, newFilePath));
            _fileWrapper.Delete(_detailedLogFile.LogFilePath);
        }
예제 #6
0
        public void StoreVersion(IResource resource, string userName, string reason, Guid workSpaceId)
        {
            if (workSpaceId == Guid.Empty)
            {
                lock (LockObject)
                {
                    var old = _catalogue.GetResource(Guid.Empty, resource.ResourceID);
                    if (old != null)
                    {
                        var versions = GetVersions(resource.ResourceID).FirstOrDefault();
                        old.VersionInfo = _versionStrategy.GetCurrentVersion(resource, versions == null? null :versions.VersionInfo, userName, reason);
                        var folderPath = GetVersionFolderFromResource(resource);

                        var fileName = string.Format("{0}_{1}_{2}_{3}.xml", old.VersionInfo.VersionId, old.VersionInfo.VersionNumber, GetDateString(old.VersionInfo.DateTimeStamp), reason);
                        if (!_file.Exists(Path.Combine(folderPath, fileName))) //todo: remove this and stop save on workspace
                        {
                            var sourceFile = Path.Combine(GetFolderFromResource(resource), old.ResourceName) + ".xml";
                            if (_file.Exists(sourceFile))
                            {
                                _file.Copy(sourceFile, Path.Combine(folderPath, fileName));
                            }
                        }

                        resource.VersionInfo = _versionStrategy.GetNextVersion(resource, old, userName, reason);
                    }
                }
            }
        }
        public SourceFileInfo Duplicate(SourceFileInfo sfi, string duplicateFolder, string profileGuid)
        {
            var duplicate = new SourceFileInfo();

            duplicate.SessionId           = sfi.SessionId;
            duplicate.WinStation          = sfi.WinStation;
            duplicate.Author              = sfi.Author;
            duplicate.ClientComputer      = sfi.ClientComputer;
            duplicate.PrinterName         = sfi.PrinterName;
            duplicate.JobCounter          = sfi.JobCounter;
            duplicate.JobId               = sfi.JobId;
            duplicate.DocumentTitle       = sfi.DocumentTitle;
            duplicate.OriginalFilePath    = sfi.OriginalFilePath;
            duplicate.Type                = sfi.Type;
            duplicate.TotalPages          = sfi.TotalPages;
            duplicate.Copies              = sfi.Copies;
            duplicate.UserTokenEvaluated  = sfi.UserTokenEvaluated;
            duplicate.UserToken           = sfi.UserToken;
            duplicate.OutputFileParameter = sfi.OutputFileParameter;

            duplicate.PrinterParameter = profileGuid == null ? sfi.PrinterParameter : "";
            duplicate.ProfileParameter = profileGuid ?? sfi.ProfileParameter;

            var duplicateFilename = PathSafe.GetFileNameWithoutExtension(sfi.Filename);
            var duplicateFilePath = PathSafe.Combine(duplicateFolder, duplicateFilename);

            duplicateFilePath = _uniqueFilePathBuilder.Build(duplicateFilePath).Unique;
            _file.Copy(sfi.Filename, duplicateFilePath);
            duplicate.Filename = duplicateFilePath;

            return(duplicate);
        }
예제 #8
0
        protected void InitializeSettingsFiles(string settingsConfigFile)
        {
            if (!_directoryWrapper.Exists(EnvironmentVariables.ServerSettingsFolder))
            {
                _directoryWrapper.CreateDirectory(EnvironmentVariables.ServerSettingsFolder);
            }

            if (_fileWrapper.Exists("Settings.config") && !_fileWrapper.Exists(EnvironmentVariables.ServerLogSettingsFile))
            {
                _fileWrapper.Copy("Settings.config", EnvironmentVariables.ServerLogSettingsFile);
            }
            if (_fileWrapper.Exists("secure.config") && !_fileWrapper.Exists(EnvironmentVariables.ServerSecuritySettingsFile))
            {
                _fileWrapper.Copy("secure.config", EnvironmentVariables.ServerSecuritySettingsFile);
            }
            if (!_fileWrapper.Exists(settingsConfigFile))
            {
                _fileWrapper.WriteAllText(settingsConfigFile, GlobalConstants.DefaultServerLogFileConfig);
            }
        }
예제 #9
0
        private string CopyFileToJobFolder(string jobFolder, string file)
        {
            var shortUniqueFilename = _path.GetRandomFileName();
            var extension           = PathSafe.GetExtension(file);
            var psFileInJobFolder   = PathSafe.Combine(jobFolder, shortUniqueFilename + extension);

            _file.Copy(file, psFileInJobFolder);
            Logger.Debug("Copied direct conversion file to spool folder: " + psFileInJobFolder);

            return(psFileInJobFolder);
        }
예제 #10
0
        private void BackupOriginFile()
        {
            // Using InvariantCulture since this is internal
            var timestamp  = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff", CultureInfo.InvariantCulture);
            var directory  = Path.GetDirectoryName(FilePath).NonNull();
            var originName = Path.GetFileNameWithoutExtension(FilePath);
            var backupName = $"{originName}-{timestamp}{FileSuffix}";
            var backupPath = Path.Combine(directory, backupName);

            File.Copy(FilePath, backupPath, true);

            // todo give user notification for the backup process
        }
예제 #11
0
 /// <summary>
 /// Copy file with logging and catching of ioException
 /// </summary>
 /// <returns>true if successfull</returns>
 protected bool CopyFile(string tempFile, string outputFile)
 {
     try
     {
         FileWrap.Copy(tempFile, outputFile, true);
         Logger.Debug("Copied output file \"{0}\" \r\nto \"{1}\"", tempFile, outputFile);
         return(true);
     }
     catch (IOException ioException)
     {
         Logger.Warn("Error while copying to target file.\r\nfrom\"{0}\" \r\nto \"{1}\"\r\n{2}", tempFile, outputFile, ioException.Message);
     }
     return(false);
 }
예제 #12
0
        private bool CopyMissingResources(string[] programDataIds, List <ResourceBuilderTO> programFilesBuilders, IDirectory directory, IFile fileWrapper)
        {
            var foundMissingResources = false;

            // NOTE: we have not filtered for files that are not
            programFilesBuilders.ForEach(programFileItem =>
            {
                XElement xml = null;
                try
                {
                    xml = XElement.Load(programFileItem._fileStream);
                }
                catch (Exception e)
                {
                    Dev2Logger.Error("Resource [ " + programFileItem._filePath + " ] caused " + e.Message, GlobalConstants.WarewolfError);
                }

                var id = xml?.Attribute("ID")?.Value ?? null;
                if (id != null && programDataIds.Any(programDataId => programDataId == id))
                { // resource already installed
                    return;
                }
                if (id is null) // invalid resource
                {
                    return;
                }

                // Only get here if the bite file does not exist in ProgramData directory
                foundMissingResources = true;
                programFileItem._fileStream.Close();
                var currentPath = programFileItem._filePath;

                var appResourcesPath       = Path.Combine(EnvironmentVariables.ApplicationPath, "Resources");
                var currentSubPath         = currentPath.Replace(appResourcesPath, "").Replace(".xml", ".bite");
                var MyNewInstalledFilePath = EnvironmentVariables.ResourcePath + $"{currentSubPath}";
                directory.CreateIfNotExists(fileWrapper.DirectoryName(MyNewInstalledFilePath));

                try
                {
                    fileWrapper.Copy(programFileItem._filePath, MyNewInstalledFilePath, false);
                }
                catch (Exception e)
                {
                    Dev2Logger.Warn("Failed to copy Examples resource to ProgramData, " + e.Message, GlobalConstants.WarewolfWarn);
                }
            });

            return(foundMissingResources);
        }
        public List <HistoricJob> Load()
        {
            var oldHistoryDir = PathSafe.Combine(_environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PDFCreator");
            var oldSavePath   = PathSafe.Combine(oldHistoryDir, "PDFCreatorHistory.json");

            if (!_file.Exists(_savePath))
            {
                if (_file.Exists(oldSavePath))
                {
                    _file.Copy(oldSavePath, _savePath);
                    _logger.Debug($"Migrated job history from '{oldSavePath}' to '{_savePath}'.");
                }
                else
                {
                    return(new List <HistoricJob>());
                }
            }

            return(ReadHistoryJobsFile());
        }
        public void StoreVersion(IResource resource, string userName, string reason, Guid workSpaceId, string resourcePath)
        {
            var versionFolder = GetVersionFolderPath(resource.ResourceID.ToString());
            var _userName     = userName;

            if (workSpaceId == Guid.Empty)
            {
                if (string.IsNullOrEmpty(_userName))
                {
                    _userName = Thread.CurrentPrincipal.Identity.Name;
                }

                lock (LockObject)
                {
                    var old = _catalogue.GetResource(Guid.Empty, resource.ResourceID);
                    if (old == null)
                    {
                        return;
                    }
                    var versions = GetVersions(resource.ResourceID).FirstOrDefault();
                    old.VersionInfo = _versionStrategy.GetCurrentVersion(resource, versions?.VersionInfo, _userName, reason);

                    var fileName = $"{old.VersionInfo.VersionNumber}_{GetDateString(old.VersionInfo.DateTimeStamp)}_{reason}.bite";
                    if (!_file.Exists(_filePath.Combine(versionFolder, fileName)))
                    {
                        var sourceFile = _filePath.Combine(GetFolderFromResource(old.GetResourcePath(workSpaceId)), old.ResourceName) + ".bite";
                        if (_file.Exists(sourceFile))
                        {
                            _directory.CreateIfNotExists(versionFolder);
                            _file.Copy(sourceFile, _filePath.Combine(versionFolder, fileName));
                        }
                    }

                    resource.VersionInfo = _versionStrategy.GetNextVersion(resource, old, _userName, reason);
                }
            }
        }
예제 #15
0
 public static void Copy(string source, string destination)
 {
     f.Copy(source, destination);
 }
        private void CopyMatchMetadata(TradeDetail trade)
        {
            var fileName = new FileInfo(trade.Match.WhoScoredData.MatchMetadataLocation).Name;

            _file.Copy(trade.Match.WhoScoredData.MatchMetadataLocation, @"C:/Users/Cobalt4/TradeDecisionData/" + fileName);
        }
예제 #17
0
 /// <inheritdoc />
 public void Copy(string newPath, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting) => _file.Copy(newPath, collisionOption);
        /// <summary>
        /// Optimizes a list of files using a given optimizer
        /// </summary>
        /// <param name="optimizer">The optimizer to use.</param>
        /// <param name="file">The file to optimze.</param>
        /// <param name="outputPath">The path of the optimized file.</param>
        /// <param name="configFiles">The config files to compare against.</param>
        public OptimizedFile Optimize(string optimizer, IFile file, FilePath outputPath, IList <OptimizedFile> configFiles)
        {
            //Check Config
            OptimizedFile config = configFiles.FirstOrDefault(o => o.Path.FullPath.ToLower() == file.Path.FullPath.ToLower());

            OptimizedFile optimizedFile = null;
            string        hash          = this.GetHash(file);

            try
            {
                if ((config == null) || config.RequiresOptimization(hash) || config.DifferentService(optimizer))
                {
                    //Optimize
                    ImageOptimizerResult result = _OptimizerFactory.Optimize(optimizer, file.Path, outputPath);

                    if ((result != null) && !result.HasError)
                    {
                        //Optimzed
                        optimizedFile = new OptimizedFile(file.Path, result.Service, result.ModifiedDate, hash, result.SizeBefore, result.SizeAfter);

                        _ImagesOptimized.Add(file.Path.FullPath);
                        _SizeBefore += result.SizeBefore;
                        _SizeAfter  += result.SizeAfter;

                        _Log.Information("Optimized:  " + file.Path + " - Saved: " + result.SavedSize + " bytes (" + result.SavedPercent.ToString("N0") + "%)");
                    }
                    else if ((result.ErrorMessage == "Unsupported File") ||
                             (result.ErrorMessage == "Invalid FileSize") ||
                             (result.ErrorMessage == "Matching FileSize"))
                    {
                        //Skipped
                        _ImagesSkipped++;

                        _SizeBefore += file.Length;
                        _SizeAfter  += file.Length;

                        // Copy to destination
                        if (file.Path.FullPath.ToLower() != outputPath.FullPath.ToLower())
                        {
                            IDirectory parent = _FileSystem.GetDirectory(outputPath.GetDirectory());

                            if (!parent.Exists)
                            {
                                parent.Create();
                            }

                            file.Copy(outputPath, true);
                        }

                        _Log.Information("Skipped:  " + file.Path + " - " + result.ErrorMessage);
                    }
                    else
                    {
                        //Errored
                        _ImagesErrored++;

                        _Log.Information("Errored:  " + file.Path + " - " + result.ErrorMessage);
                    }
                }
                else
                {
                    //Skipped
                    _ImagesSkipped++;

                    if (config != null)
                    {
                        optimizedFile = new OptimizedFile(file.Path, config.Service, config.OptimizedDate, hash, config.SizeBefore, config.SizeAfter);

                        _SizeBefore += config.SizeBefore;
                        _SizeAfter  += config.SizeAfter;
                    }
                    else
                    {
                        _SizeBefore += file.Length;
                        _SizeAfter  += file.Length;
                    }

                    _Log.Information("Skipped:  " + file.Path + " - Saved: " + config.SavedSize + " bytes (" + config.SavedPercent.ToString("N0") + "%)");
                }
            }
            catch (Exception ex)
            {
                //Errored
                _ImagesErrored++;

                _Log.Information("Errored:  " + file.Path + " - " + ex.Message);
            }

            this.OnProgress(optimizedFile);

            return(optimizedFile);
        }