private string DetermineOutfileBody(string outputFilenameTemplate) { var outputDir = PathSafe.GetDirectoryName(outputFilenameTemplate) ?? ""; var filenameBase = PathSafe.GetFileNameWithoutExtension(outputFilenameTemplate) ?? "output"; return(PathSafe.Combine(outputDir, filenameBase)); }
private string RemoveExtension(string filePath) { var directory = PathSafe.GetDirectoryName(filePath); var fileWithoutExtension = PathSafe.GetFileNameWithoutExtension(filePath); return(Path.Combine(directory, fileWithoutExtension)); }
public string GetAssemblyDirectory() { var assemblyPath = GetAssemblyPath(_assembly); var dir = Path.GetDirectoryName(assemblyPath); return(PathSafe.GetDirectoryName(assemblyPath)); }
/// <summary> /// Creates a directory that does not exist yet. It takes a path and appends a counting number (_2, _3, etc) to ensure /// this in a readable way. /// </summary> /// <returns>The uniqified directory path</returns> public string MakeUniqueDirectory(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Argument may not be empty string", nameof(path)); } var directory = PathSafe.GetDirectoryName(path) ?? ""; var fileBody = PathSafe.GetFileName(path); var i = 2; while (_directoryWrap.Exists(path) || _fileWrap.Exists(path)) { path = PathSafe.Combine(directory, fileBody + "_" + i); i++; } return(path); }
public override void MoveOutputFiles() { string outputDir = PathSafe.GetDirectoryName(Job.OutputFilenameTemplate) ?? ""; string filenameBase = PathSafe.GetFileNameWithoutExtension(Job.OutputFilenameTemplate) ?? "output"; string outfilebody = PathSafe.Combine(outputDir, filenameBase); Job.OutputFiles = new string[TempOutputFiles.Count]; //reserve space foreach (string tempoutputfile in TempOutputFiles) { string extension = PathSafe.GetExtension(TempOutputFiles[0]); string tempFileBase = PathSafe.GetFileNameWithoutExtension(tempoutputfile) ?? "output"; string num = tempFileBase.Replace(Job.JobTempFileName, ""); int numValue; if (int.TryParse(num, out numValue)) { int numDigits = (int)Math.Floor(Math.Log10(TempOutputFiles.Count) + 1); num = numValue.ToString("D" + numDigits); } string outputfile; if (num == "1") { outputfile = outfilebody + extension; } else { outputfile = outfilebody + num + extension; } lock (_lockObject) { var uniqueFilename = new UniqueFilename(outputfile, DirectoryWrap, FileWrap); if (Job.Profile.AutoSave.Enabled && Job.Profile.AutoSave.EnsureUniqueFilenames) { outputfile = EnsureUniqueFilename(uniqueFilename); } if (!CopyFile(tempoutputfile, outputfile)) { outputfile = EnsureUniqueFilename(uniqueFilename); if (!CopyFile(tempoutputfile, outputfile)) { //Throw exception after second attempt to copy failes. throw new DeviceException("Error while copying to target file in second attempt. Process gets canceled.", 2); } } } DeleteFile(tempoutputfile); Job.OutputFiles[Convert.ToInt32(num) - 1] = outputfile; } }
public void ShowSaveFileDialog_SetValuesFromUserInput_SetFilepathAndOutputFormatInJob() { var skipPrintDialogCommand = BuildCommand(); var job = BuildJob(_pdfProfile); skipPrintDialogCommand.Execute(job); var result = _saveFileQuery .GetFileName(PathSafe.GetDirectoryName(job.OutputFileTemplate), PathSafe.GetFileName(job.OutputFileTemplate), job.Profile.OutputFormat); Assert.AreEqual(result.Data.Filepath, job.OutputFileTemplate); Assert.AreEqual(result.Data.OutputFormat, job.Profile.OutputFormat); }
/// <summary> /// Creates a directory that does not exist yet. It takes a path and appends a counting number (_2, _3, etc) to ensure /// this in a readable way. /// </summary> /// <returns>The uniqified directory path</returns> public string MakeUniqueDirectory() { var directory = PathSafe.GetDirectoryName(_path) ?? ""; var fileBody = PathSafe.GetFileName(_path); var i = 2; while (_directoryWrap.Exists(_path) || _fileWrap.Exists(_path)) { _path = PathSafe.Combine(directory, fileBody + "_" + i); i++; } return(_path); }
private IList <HistoricFile> CreateHistoricFiles(Job job) { var historicFiles = new List <HistoricFile>(); foreach (var file in job.OutputFiles) { var fileName = PathSafe.GetFileName(file); var directory = PathSafe.GetDirectoryName(file); var hash = BuildHash(file); var historicFile = new HistoricFile(file, fileName, directory, hash); historicFiles.Add(historicFile); } return(historicFiles); }
public void ShowSaveFileDialog_SetValuesFromUserInput_FilepathAndOutputFormatHasChanged() { var skipPrintDialogCommand = BuildCommand(); var job = BuildJob(_pdfProfile); var diffFilenameTemplate = job.OutputFileTemplate; var diffOutputFormat = job.Profile.OutputFormat; skipPrintDialogCommand.Execute(job); _saveFileQuery .GetFileName(PathSafe.GetDirectoryName(job.OutputFileTemplate), PathSafe.GetFileName(job.OutputFileTemplate), job.Profile.OutputFormat); Assert.AreNotEqual(job.OutputFileTemplate, diffFilenameTemplate); Assert.AreNotEqual(job.Profile.OutputFormat, diffOutputFormat); }
public void Save(Job job) { if (!IsEnabled(job)) { return; } var directory = PathSafe.GetDirectoryName(job.OutputFileTemplate); if (IsTemp(directory)) { return; } _settingsProvider.Settings.CreatorAppSettings.LastSaveDirectory = directory; _settingsManager.SaveCurrentSettings(); }
public void Execute(object parameter) { var job = parameter as Job; var folder = PathSafe.GetDirectoryName(job.OutputFileTemplate) ?? ""; var filename = PathSafe.GetFileName(job.OutputFileTemplate) ?? ""; var result = _saveFileQuery.GetFileName(folder, filename, job.Profile.OutputFormat); if (!result.Success) { throw new AbortWorkflowException("User cancelled in SaveFileDialog"); } job.OutputFileTemplate = result.Data.Filepath; job.Profile.OutputFormat = result.Data.OutputFormat; }
/// <summary> /// Sets the location where the job should be converted to and the jobs full name /// </summary> /// <param name="fileName">Specifies the location and the name of the converted file</param> private string DetermineOutputFilename(string fileName) { if (fileName == null) { throw new COMException("The output filename was not set"); } var tmpPath = PathSafe.GetDirectoryName(fileName); if (tmpPath == null || !_directory.Exists(tmpPath)) { throw new COMException("Invalid path. Please check if the directory exists."); } Logger.Trace("COM: Setting the full name of the job:" + fileName); return(_outputFormatHelper.EnsureValidExtension(fileName, Job.Profile.OutputFormat)); }
private void AddTokensFromOriginalFilePath(SourceFileInfo sfi, Metadata metadata, JobInfo.JobInfo jobInfo) { var originalFileName = metadata.PrintJobName; var originalDirectory = ""; if (!string.IsNullOrEmpty(jobInfo.OriginalFilePath)) { originalFileName = PathSafe.GetFileNameWithoutExtension(jobInfo.OriginalFilePath); originalDirectory = PathSafe.GetDirectoryName(jobInfo.OriginalFilePath); } else if (_pathUtil.IsValidRootedPath(sfi.DocumentTitle)) { originalFileName = PathSafe.GetFileNameWithoutExtension(sfi.DocumentTitle); originalDirectory = PathSafe.GetDirectoryName(sfi.DocumentTitle); } _tokenReplacer.AddStringToken("InputFilename", originalFileName); _tokenReplacer.AddStringToken("InputDirectory", originalDirectory); _tokenReplacer.AddStringToken("InputFilePath", originalDirectory); }
/// <param name="originalFilename">Original file name</param> public UniqueFilenameBase(string originalFilename, IPathUtil pathUtil) { if (originalFilename == null) { throw new ArgumentNullException(); } if (string.IsNullOrWhiteSpace(originalFilename)) { throw new ArgumentException(nameof(originalFilename)); } _pathUtil = pathUtil; OriginalFilename = originalFilename; LastUniqueFilename = originalFilename; _directory = PathSafe.GetDirectoryName(OriginalFilename) ?? ""; _fileBody = PathSafe.GetFileNameWithoutExtension(OriginalFilename); _extension = PathSafe.GetExtension(OriginalFilename); }
/// <summary> /// Adds ellipsis to a path with a length longer than 255. /// </summary> /// <param name="filePath">full path to file</param> /// <param name="maxLength">maximum length of the string. This must be between 10 and MAX_PATH (260)</param> /// <returns>file path with ellipsis to ensure length under the max length </returns> public string EllipsisForFilename(string filePath, int maxLength) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } if (filePath.EndsWith("\\")) { throw new ArgumentException("The path has to be a file", nameof(filePath)); } if (maxLength < 10 || maxLength > MAX_PATH) { throw new ArgumentException($"The desired length must be between 10 and {MAX_PATH}", nameof(maxLength)); } if (filePath.Length > maxLength) { int minUsefulFileLength = 4; var directory = PathSafe.GetDirectoryName(filePath) ?? ""; var file = PathSafe.GetFileNameWithoutExtension(filePath); var extension = PathSafe.GetExtension(filePath); var remainingLengthForFile = maxLength - directory.Length - extension.Length - ELLIPSIS.Length - 1; // substract -1 to account for the slash between path and filename if (remainingLengthForFile < minUsefulFileLength) { throw new ArgumentException("The path is too long", nameof(filePath)); //! } var partLength = remainingLengthForFile / 2; file = file.Substring(0, partLength) + ELLIPSIS + file.Substring(file.Length - partLength, partLength); filePath = PathSafe.Combine(directory, file + extension); } return(filePath); }
private async Task <MacroCommandIsDoneEventArgs> BrowseFileWithNotificationForTooLongInput(object arg) { var job = _getJob(); var inputFilePath = job.OutputFileTemplate; var inputDirectory = PathSafe.GetDirectoryName(inputFilePath); var inputFilename = PathSafe.GetFileName(inputFilePath); _directoryHelper.CreateDirectory(inputDirectory); var result = await GetFileOrRetry(inputDirectory, inputFilename, job.Profile.OutputFormat); if (result.Success) { job.OutputFileTemplate = result.Data.Filepath; job.Profile.OutputFormat = result.Data.OutputFormat; _updateUi(); _setLastConfirmedPath(result.Data.Filepath); return(new MacroCommandIsDoneEventArgs(ResponseStatus.Success)); } _setLastConfirmedPath(""); return(new MacroCommandIsDoneEventArgs(ResponseStatus.Cancel)); }
/// <summary> /// Calls the script /// </summary> /// <param name="job">The current job</param> /// <returns>An ActionResult to determine the success and a list of errors</returns> public ActionResult ProcessJob(Job job) { _logger.Debug("Launched Script-Action"); ApplyPreSpecifiedTokens(job); var actionResult = Check(job.Profile, job.Accounts, CheckLevel.Job); if (!actionResult) { return(actionResult); } var scriptFile = job.Profile.Scripting.ScriptFile; _logger.Debug("Script-File: " + scriptFile); IProcess process = _processStarter.CreateProcess(scriptFile); var parameters = ComposeScriptParameters(job.Profile.Scripting.ParameterString, job.OutputFiles, job.TokenReplacer); process.StartInfo.Arguments = parameters; if (job.Profile.Scripting.Visible == false) { process.StartInfo.ProcessStartInfoInstance.WindowStyle = ProcessWindowStyle.Hidden; } _logger.Debug("Script-Parameters: " + parameters); var scriptDir = PathSafe.GetDirectoryName(scriptFile); if (scriptDir != null) { process.StartInfo.WorkingDirectory = scriptDir; } _logger.Debug("Script-Working Directory: " + scriptDir); process.EnableRaisingEvents = true; process.Exited += (sender, args) => process.Close(); try { _logger.Debug("Launching script..."); process.Start(); if (job.Profile.Scripting.WaitForScript) { _logger.Debug("Waiting for script to end"); process.WaitForExit(); _logger.Debug("Script execution ended"); } else { _logger.Debug("The script is executed in the background"); } return(new ActionResult()); } catch (Exception ex) { _logger.Error(ex, "Exception while running the script file \"" + scriptFile); return(new ActionResult(ErrorCode.Script_GenericError)); } }
/// <summary> /// Renames and moves all files from TempOutputFiles to their destination according to /// the FilenameTemplate and stores them in the OutputFiles list. /// For multiple files the FilenameTemplate gets an appendix. /// </summary> public async Task MoveOutputFiles(Job job) { Logger.Trace("Moving output files to final location"); if (!PathUtil.IsValidRootedPath(job.OutputFileTemplate)) { var result = await HandleInvalidRootedPath(job.OutputFileTemplate, job.Profile.OutputFormat); if (result.Success == false) { throw new AbortWorkflowException("User cancelled retyping invalid rooted path."); } job.OutputFileTemplate = result.Data; } _outfilebody = DetermineOutfileBody(job.OutputFileTemplate); var outputDirectory = PathSafe.GetDirectoryName(job.OutputFileTemplate); DirectoryHelper.CreateDirectory(outputDirectory); //Ensure the the first file is the first in TempOutputFiles job.TempOutputFiles = job.TempOutputFiles.OrderBy(x => x).ToList(); int fileNumber = 0; foreach (var tempOutputFile in job.TempOutputFiles) { fileNumber++; var extension = Path.GetExtension(tempOutputFile); var numberSuffix = DetermineNumWithDigits(job, tempOutputFile); var currentOutputFile = _outfilebody + numberSuffix + extension; await SemaphoreSlim.WaitAsync(); try { var uniqueFilename = new UniqueFilename(currentOutputFile, Directory, File, PathUtil); if (ApplyUniqueFilename(job)) { currentOutputFile = EnsureUniqueFilename(uniqueFilename); } if (!CopyFile(tempOutputFile, currentOutputFile)) { var action = QueryHandleCopyError(fileNumber); switch (action) { case HandleCopyErrorResult.Requery: currentOutputFile = await RequeryFilename(job, tempOutputFile, numberSuffix, extension); break; default: currentOutputFile = EnsureUniqueFilename(uniqueFilename); if (!CopyFile(tempOutputFile, currentOutputFile)) { throw new ProcessingException("Error while copying to target file in second attempt. Process gets canceled.", ErrorCode.Conversion_ErrorWhileCopyingOutputFile); } break; } } } finally { SemaphoreSlim.Release(); } DeleteFile(tempOutputFile); job.OutputFiles.Add(currentOutputFile); } job.OutputFiles = job.OutputFiles.OrderBy(x => x).ToList(); }
private void SetOutputFilenameAndFolder(string filenameTemplate) { OutputFilename = PathSafe.GetFileName(filenameTemplate); OutputFolder = PathSafe.GetDirectoryName(filenameTemplate); }