public void CreateArgumentsCollectionAsNewWithOneArgumentAttachedTest() { string key = "key"; int value = 10; ArgumentCollection argumentCollection = ArgumentCollection.New().WithArgument(key, value); Assert.IsTrue(argumentCollection.Any()); Assert.IsTrue(argumentCollection.HasArgument(key)); Assert.AreEqual(value, argumentCollection[key]); }
public bool ValidateArguments(ArgumentCollection arguments) { if (!arguments.HasArgument(DeleteFilesActionExecutionArgs.FilesPaths)) { LoggingService.Error($"Missing mandatory argument {DeleteFilesActionExecutionArgs.FilesPaths}"); return(false); } return(true); }
public void CreateArgumentsCollectionWithOneArgumentAddedTest() { string key = "key"; int value = 10; Argument argument = new Argument(key, value); ArgumentCollection argumentCollection = new ArgumentCollection(); argumentCollection.Add(argument); Assert.IsTrue(argumentCollection.Any()); Assert.IsTrue(argumentCollection.HasArgument(argument.Key)); Assert.AreEqual(argument.Value, argumentCollection[argument.Key]); }
public ArgumentCollection Map(ArgumentCollection arguments) { if (!arguments.HasArgument(FilesWatcherResultArguments.Files) || !(arguments[FilesWatcherResultArguments.Files] is List <string>)) { return(null); } return(new ArgumentCollection( (DeleteFilesActionExecutionArgs.FilesPaths, arguments[FilesWatcherResultArguments.Files]) )); }
public ArgumentCollection Map(ArgumentCollection arguments) { if (!arguments.HasArgument(WinServiceWatcherResultArgs.ServiceName) || !(arguments[WinServiceWatcherResultArgs.ServiceName] is string)) { return(null); } return(ArgumentCollection.New() .WithArgument(WinServiceActionExecutionArgs.ServiceName, arguments.GetValue <string>(WinServiceWatcherResultArgs.ServiceName))); }
public ArgumentCollection Map(ArgumentCollection arguments) { ArgumentCollection argumentCollection = ArgumentCollection.New(); if (arguments.HasArgument(ProcessWatcherResultArgs.ProcessName)) { argumentCollection.Add(KillProcessByNameActionExecutionArgs.ProcessName, arguments[ProcessWatcherResultArgs.ProcessName]); } return(argumentCollection); }
public void CreateArgumentsCollectionFromDictionaryTest() { string key = "key"; int value = 10; Dictionary <string, object> arguments = new Dictionary <string, object>() { { key, value } }; ArgumentCollection argumentCollection = ArgumentCollection.FromDictionary(arguments); Assert.IsTrue(argumentCollection.Any()); Assert.IsTrue(argumentCollection.HasArgument(key)); Assert.AreEqual(value, argumentCollection[key]); }
public ActionResult Execute(ArgumentCollection arguments) { List <string> deletedFiles = new List <string>(); try { // Must provide arguments if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (!arguments.HasArgument(DeleteFilesActionExecutionArgs.FilesPaths)) { throw new MissingArgumentException(DeleteFilesActionExecutionArgs.FilesPaths); } if (!(arguments[DeleteFilesActionExecutionArgs.FilesPaths] is List <string> filePaths)) { throw new ArgumentsValidationException( $"unable to cast argument value into list of string. key({DeleteFilesActionExecutionArgs.FilesPaths})"); } foreach (var filePath in filePaths) { // File must exist if (!File.Exists(filePath)) { throw new FileNotFoundException("File not found", filePath); } File.Delete(filePath); LoggingService.Info($"File ({filePath}) deleted successfully"); deletedFiles.Add(filePath); } return(ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(DeleteFilesActionResultsArgs.DeletedFiles, deletedFiles) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(DeleteFilesActionResultsArgs.DeletedFiles, deletedFiles) )); } }
protected override IEnumerable <System.Diagnostics.Process> GetProcesses(ArgumentCollection arguments) { int processId = default; if (arguments.HasArgument(KillProcessByIdActionExecutionArgs.ProcessId)) { processId = arguments.GetValue <int>(KillProcessByIdActionExecutionArgs.ProcessId); } if (processId == default) { throw new MissingArgumentException(KillProcessByIdActionExecutionArgs.ProcessId); } var process = System.Diagnostics.Process.GetProcessById(processId); yield return(process); }
public ActionResult Execute(ArgumentCollection arguments) { string filePath = null; try { if (arguments.HasArgument(RenameFileActionArgs.SourceFilePath)) { if (arguments[RenameFileActionArgs.SourceFilePath] is List <string> castedFilePaths) { if (castedFilePaths.Count() > 1) { throw new Exception($"Operation not allowed: Got multiple files to be renamed."); } if (!castedFilePaths.Any()) { throw new Exception($"Operation not allowed: Got empty list of files to be renamed."); } filePath = castedFilePaths.Single(); } else { filePath = arguments.GetValue <string>(RenameFileActionArgs.SourceFilePath); } } else { if (!string.IsNullOrWhiteSpace(SourceFilePath)) { filePath = SourceFilePath; } } if (string.IsNullOrWhiteSpace(filePath)) { throw new MissingArgumentException(RenameFileActionArgs.SourceFilePath); } if (!Path.IsPathRooted(filePath)) { throw new FormatException($"Source file has incorrect format, expected Rooted Path: {filePath}"); } // Files must exist if (!File.Exists(filePath)) { throw new FileNotFoundException($"File not found {filePath}"); } if (string.IsNullOrWhiteSpace(DestinationFileName) && string.IsNullOrWhiteSpace(DestinationPrefix) && string.IsNullOrWhiteSpace(DestinationExtension)) { throw new MissingArgumentException(RenameFileActionArgs.DestinationFileName); } var directory = Path.GetDirectoryName(filePath); if (string.IsNullOrWhiteSpace(directory)) { throw new Exception($"Unable to get directory name from file {filePath}"); } var fileName = Path.GetFileName(filePath); if (!string.IsNullOrWhiteSpace(DestinationFileName)) { fileName = DestinationFileName; } else { if (!string.IsNullOrEmpty(DestinationExtension)) { fileName = Path.ChangeExtension(fileName, DestinationExtension); } if (!string.IsNullOrEmpty(DestinationPrefix)) { fileName = DestinationPrefix + fileName; } } if (string.IsNullOrWhiteSpace(fileName)) { throw new Exception($"FileName not resolved, Cannot rename file"); } var destinationPath = Path.Combine(directory, fileName); if (File.Exists(destinationPath)) { throw new Exception($"Another file with the same name already exists {destinationPath}"); } File.Move(filePath, destinationPath); LoggingService.Trace($"File ({filePath}) renamed successfully to path ({destinationPath})"); return(ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(RenameFileActionResultArgs.SourceFilePath, filePath) .WithArgument(RenameFileActionResultArgs.DestinationFilePath, destinationPath) )); } catch (Exception exception) { LoggingService.Error(exception); return(new ActionResult(false) { AttachedException = exception, AdditionalInformation = ArgumentCollection.New().WithArgument(RenameFileActionResultArgs.SourceFilePath, filePath) }); } }
public ActionResult Execute(ArgumentCollection arguments) { List <string> filePaths = new List <string>(); List <string> destinationPaths = new List <string>(); try { if (arguments.HasArgument(MoveFileActionExecutionArgs.SourceFilePaths)) { if (arguments[MoveFileActionExecutionArgs.SourceFilePaths] is List <string> castedFilePaths) { filePaths.AddRange(castedFilePaths); } else { throw new ArgumentsValidationException( $"unable to cast argument value into list of string. key({MoveFileActionExecutionArgs.SourceFilePaths})"); } } else { if (!string.IsNullOrWhiteSpace(SourceFilePath)) { filePaths.Add(SourceFilePath); } } // Files must exist if (filePaths.Any(f => !File.Exists(f))) { throw new FileNotFoundException("File not found", filePaths.First(e => !File.Exists(e))); } foreach (var sourcePath in filePaths) { var fileName = Path.GetFileName(sourcePath); var destinationPath = Path.Combine(DestinationDirectory, fileName); // File must not exist if (File.Exists(destinationPath)) { throw new Exception($"({destinationPath}) File already exist"); } File.Copy(sourcePath, destinationPath); destinationPaths.Add(destinationPath); LoggingService.Info($"File ({sourcePath}) copied successfully to path ({destinationPath})"); } return(ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(CopyFilesActionResultsArgs.SourceFilePaths, filePaths) .WithArgument(CopyFilesActionResultsArgs.CopiedFilesPaths, destinationPaths) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(CopyFilesActionResultsArgs.SourceFilePaths, filePaths) .WithArgument(CopyFilesActionResultsArgs.CopiedFilesPaths, destinationPaths) )); } }
public ActionResult Execute(ArgumentCollection arguments) { try { // Must provide arguments if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (!arguments.HasArgument(FtpDownloadActionExecutionArgs.RemoteFilesCollection)) { throw new MissingArgumentException(FtpDownloadActionExecutionArgs.RemoteFilesCollection); } if (!(arguments[FtpDownloadActionExecutionArgs.RemoteFilesCollection] is List <string> remotePaths)) { throw new ArgumentsValidationException( $"unable to cast argument value into list of string. key({FtpDownloadActionExecutionArgs.RemoteFilesCollection})"); } FtpLocalExists existMode = Overwrite ? FtpLocalExists.Overwrite : Append ? FtpLocalExists.Append : FtpLocalExists.Skip; LoggingService.Trace($"ExistMode: {existMode:G}"); var directoryPath = Environment.ExpandEnvironmentVariables(DirectoryPath); List <string> downloadedFiles = new List <string>(); List <string> skippedFiles = new List <string>(); List <string> failedFiles = new List <string>(); if (UseTemporaryName && existMode != FtpLocalExists.Append) { LoggingService.Warn($"Cannot use temporary name for download in mode Append."); } using (FtpClient ftpClient = new FtpClient(Host, Port, Username, Password)) { if (!string.IsNullOrWhiteSpace(RemoteWorkingDir)) { ftpClient.SetWorkingDirectory(RemoteWorkingDir); } foreach (var remotePath in remotePaths) { var remoteFileName = UriHelper.GetFileName(remotePath); var localPath = Path.Combine(directoryPath, remoteFileName); string temporaryPath = string.Empty; bool useTemporaryName = UseTemporaryName && existMode != FtpLocalExists.Append; if (useTemporaryName) { temporaryPath = Path.ChangeExtension(Path.Combine(directoryPath, Path.GetRandomFileName()), DEFAULT_TEMP_EXTENSION); } var downloadPath = useTemporaryName ? temporaryPath : localPath; LoggingService.Debug($"Downloading file {remotePath} to temporary path {downloadPath}"); var ftpStatus = ftpClient.DownloadFile(downloadPath, remotePath, existMode); LoggingService.Debug($"File download completed with status {ftpStatus:G}"); if (ftpStatus == FtpStatus.Success && useTemporaryName) { LoggingService.Trace($"Renaming file {downloadPath} to {localPath}"); File.Move(downloadPath, localPath, Overwrite); } if (ftpStatus == FtpStatus.Success) { downloadedFiles.Add(remotePath); } if (ftpStatus == FtpStatus.Skipped) { skippedFiles.Add(remotePath); } if (ftpStatus == FtpStatus.Failed) { failedFiles.Add(remotePath); } } if (MoveDownloaded || DeleteDownloaded || RenameDownloaded) { foreach (var downloadedFile in downloadedFiles) { if (DeleteDownloaded) { ftpClient.DeleteFile(downloadedFile); } else if (MoveDownloaded && !string.IsNullOrWhiteSpace(MoveDownloadedPath)) { ftpClient.MoveFile(downloadedFile, UriHelper.BuildPath(MoveDownloadedPath, Path.GetFileName(downloadedFile))); } else if (RenameDownloaded) { LoggingService.Debug($"Trying to rename remote file {downloadedFile}"); var remoteParentPath = UriHelper.GetParentUriString(downloadedFile); if (!string.IsNullOrWhiteSpace(RenameDownloadedNewName)) { LoggingService.Debug($"Renaming remote file {downloadedFile} to {RenameDownloadedNewName}"); var newName = UriHelper.BuildPath(remoteParentPath, RenameDownloadedNewName); ftpClient.Rename(downloadedFile, newName); LoggingService.Debug($"Renamed file {downloadedFile} to {newName}"); } else { LoggingService.Debug($"Trying to apply prefix or extension to remote file {downloadedFile}"); var fileName = Path.GetFileName(downloadedFile); if (!string.IsNullOrWhiteSpace(RenameDownloadedExtension)) { LoggingService.Debug($"Changing extension to {RenameDownloadedExtension}"); fileName = Path.ChangeExtension(fileName, RenameDownloadedExtension); } if (!string.IsNullOrWhiteSpace(RenameDownloadedPrefix)) { LoggingService.Debug($"Applying prefix to {RenameDownloadedPrefix}"); fileName = $"{RenameDownloadedPrefix}{fileName}"; } LoggingService.Debug($"Renaming remote file {downloadedFile} to {fileName}"); var newName = UriHelper.BuildPath(remoteParentPath, fileName); ftpClient.Rename(downloadedFile, newName); LoggingService.Debug($"Renamed file {downloadedFile} to {newName}"); } } } } } if (downloadedFiles.Any()) { return(ActionResult.Succeeded() .WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpDownloadActionResultArgs.DownloadedFiles, downloadedFiles) .WithArgument(FtpDownloadActionResultArgs.SkippedFiles, skippedFiles) .WithArgument(FtpDownloadActionResultArgs.FailedFiles, failedFiles) )); } return(ActionResult.Failed() .WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpDownloadActionResultArgs.DownloadedFiles, downloadedFiles) .WithArgument(FtpDownloadActionResultArgs.SkippedFiles, skippedFiles) .WithArgument(FtpDownloadActionResultArgs.FailedFiles, failedFiles) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception) .WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpDownloadActionResultArgs.DownloadedFiles, new List <string>()) .WithArgument(FtpDownloadActionResultArgs.SkippedFiles, new List <string>()) .WithArgument(FtpDownloadActionResultArgs.FailedFiles, new List <string>()) )); } }
/// <summary> /// Executes the specified arguments. /// </summary> /// <param name="arguments">The arguments.</param> /// <returns></returns> public ActionResult Execute(ArgumentCollection arguments) { List <string> sourceFiles = new List <string>(); List <string> uploadedFiles = new List <string>(); try { // Must provide arguments if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (!arguments.HasArgument(FtpUploadActionExecutionArgs.SourceFilesCollection)) { throw new MissingArgumentException(FtpUploadActionExecutionArgs.SourceFilesCollection); } if (!(arguments[FtpUploadActionExecutionArgs.SourceFilesCollection] is List <string> filePaths)) { throw new ArgumentsValidationException( $"unable to cast argument value into list of string. key({FtpUploadActionExecutionArgs.SourceFilesCollection})"); } sourceFiles = filePaths; foreach (var sourceFilePath in filePaths) { LoggingService.Debug($"Uploading file {sourceFilePath}"); string uploadFileName = null; try { if (!File.Exists(sourceFilePath)) { LoggingService.Error($"File doesn't not exist {sourceFilePath}"); continue; } if (string.IsNullOrWhiteSpace(Host)) { LoggingService.Error($"Missing Instance Argument {FtpUploadActionInstanceArgs.Host}"); continue; } if (string.IsNullOrWhiteSpace(Username)) { LoggingService.Error($"Missing Instance Argument {FtpUploadActionInstanceArgs.Username}"); continue; } if (string.IsNullOrWhiteSpace(Password)) { LoggingService.Error($"Missing Instance Argument {FtpUploadActionInstanceArgs.Password}"); continue; } uploadFileName = sourceFilePath; if (UseLocalTemporaryExtension && !string.IsNullOrWhiteSpace(LocalTemporaryExtension)) { LoggingService.Debug($"Renaming file with temporary extension {LocalTemporaryExtension} => From {sourceFilePath} to {uploadFileName}"); uploadFileName = Path.ChangeExtension(sourceFilePath, LocalTemporaryExtension.TrimStart('.')); if (File.Exists(uploadFileName)) { LoggingService.Error($"File with the same name already exist! {uploadFileName}"); continue; } File.Move(sourceFilePath, uploadFileName); LoggingService.Debug($"File renamed to {uploadFileName}"); } string uploadRemoteFileName = null; if (UseRemoteTemporaryExtension && !string.IsNullOrWhiteSpace(RemoteTemporaryExtension)) { LoggingService.Debug($"Setting a temporary remote filename extension to {RemoteTemporaryExtension}"); if (!string.IsNullOrWhiteSpace(DestinationFileName)) { LoggingService.Debug($"Using a static name for remote file name: {DestinationFileName}"); uploadRemoteFileName = $"{Path.ChangeExtension(DestinationFileName, null)}.{RemoteTemporaryExtension.TrimStart('.')}"; LoggingService.Debug($"Remote file name with Temporary extension and a static name {uploadRemoteFileName}"); } else { uploadRemoteFileName = $"{Path.GetFileNameWithoutExtension(sourceFilePath)}.{RemoteTemporaryExtension.TrimStart('.')}"; LoggingService.Debug($"Remote file name with Temporary extension {uploadRemoteFileName}"); } } LoggingService.Debug($"Connecting to Host {Host}"); using (FtpClient ftpClient = new FtpClient(Host, Port, Username, Password)) { var tempRemotePath = UriHelper.BuildPath(DestinationFolderPath, uploadRemoteFileName); LoggingService.Debug($"Uploading file with options : {FtpUploadActionInstanceArgs.Overwrite}={Overwrite} and {FtpUploadActionInstanceArgs.CreateRemoteDirectory}={CreateRemoteDirectory}"); // Upload the file var uploadStatus = ftpClient.UploadFile(uploadFileName, tempRemotePath, Overwrite ? FtpRemoteExists.Overwrite : FtpRemoteExists.NoCheck, CreateRemoteDirectory); LoggingService.Debug($"File Upload completed with status {uploadStatus:G}"); // Rename file after upload string finalFileName = string.IsNullOrWhiteSpace(DestinationFileName) ? Path.GetFileName(sourceFilePath) : DestinationFileName; LoggingService.Debug($"Renaming the uploaded remote file to its final name: {finalFileName}"); string finalRemotePath = UriHelper.BuildPath(DestinationFolderPath, finalFileName); ftpClient.Rename(tempRemotePath, finalRemotePath); uploadedFiles.Add(finalRemotePath); } } catch (Exception exception) { LoggingService.Error(exception, $"File: {sourceFilePath}"); } finally { // Rename source file to original extension if (UseLocalTemporaryExtension && !string.IsNullOrWhiteSpace(uploadFileName) && !string.IsNullOrWhiteSpace(sourceFilePath)) { LoggingService.Debug($"Renaming the local file to with its original extension"); if (!string.Equals(uploadFileName, sourceFilePath, StringComparison.CurrentCultureIgnoreCase)) { bool sourceFileExist = File.Exists(sourceFilePath); bool uploadFileExist = File.Exists(uploadFileName); if (uploadFileExist && !sourceFileExist) { File.Move(uploadFileName, sourceFilePath); } else { LoggingService.Error($"The file with temporary name was not found [{nameof(uploadFileExist)}={uploadFileExist}] or another file with the same original name was created during the upload process [{nameof(sourceFileExist)}={sourceFileExist}]."); } } } } } return(ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpUploadActionResultsArgs.SourceFilesPaths, filePaths) .WithArgument(FtpUploadActionResultsArgs.UploadedFiles, uploadedFiles) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed().WithException(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpUploadActionResultsArgs.SourceFilesPaths, sourceFiles) .WithArgument(FtpUploadActionResultsArgs.UploadedFiles, uploadedFiles) )); } }
/// <summary> /// Executes the specified arguments. /// </summary> /// <param name="arguments">The arguments.</param> /// <returns></returns> /// <exception cref="System.Exception"> /// Missing mandatory argument {ZipDirectoryActionExecutionArgs.Directory} /// or /// Directory to ZIP Not Found ({sourceDirectory}) /// or /// Unable to get the parent directory of SourceDirectory ({sourceDirectory}) /// </exception> public ActionResult Execute(ArgumentCollection arguments) { string outputZipPath = null; string sourceDirectory = null; try { // Check if Argument Directory exists if (string.IsNullOrWhiteSpace(SourceDirectory) && !arguments.HasArgument(ZipDirectoryActionExecutionArgs.Directory)) { throw new Exception($"Missing mandatory argument {ZipDirectoryActionExecutionArgs.Directory}"); } sourceDirectory = string.IsNullOrWhiteSpace(SourceDirectory) ? arguments[ZipDirectoryActionExecutionArgs.Directory].ToString() : SourceDirectory; // Check if directory exists if (!Directory.Exists(sourceDirectory)) { throw new Exception($"Directory to ZIP Not Found ({sourceDirectory})"); } var directoryName = new DirectoryInfo(sourceDirectory).Name; if (string.IsNullOrWhiteSpace(OutputDirectory)) { LoggingService.Info($"{ZipDirectoryActionInstanceArgs.OutputDirectory} is not set."); if (!UseLocationAsOutput) { LoggingService.Warn( $"[{ZipDirectoryActionInstanceArgs.UseLocationAsOutput}] is set to ({UseLocationAsOutput})"); throw new Exception( $"Output Directory not set and it's not allowed to use location as output."); } OutputDirectory = Directory.GetParent(sourceDirectory)?.FullName; if (string.IsNullOrWhiteSpace(OutputDirectory)) { throw new Exception( $"Unable to get the parent directory of SourceDirectory ({sourceDirectory})"); } } else { LoggingService.Info( $"[{ZipDirectoryActionInstanceArgs.CreateOutputDirectory}] is set to ({CreateOutputDirectory})"); if (!Directory.Exists(OutputDirectory) && CreateOutputDirectory) { LoggingService.Info($"Creating output directory at ({OutputDirectory})"); Directory.CreateDirectory(OutputDirectory); } } if (!Directory.Exists(OutputDirectory)) { throw new Exception( $"Output Directory not found ({OutputDirectory})"); } outputZipPath = Path.Combine(OutputDirectory, $"{directoryName}.zip"); if (File.Exists(outputZipPath)) { LoggingService.Warn( $"[{ZipDirectoryActionInstanceArgs.EraseOutputIfExists}]=({EraseOutputIfExists}) Another file with the same name already exists in the output folder ({outputZipPath})"); if (EraseOutputIfExists) { LoggingService.Info( $"[{ZipDirectoryActionInstanceArgs.EraseOutputIfExists}]=({EraseOutputIfExists}) Deleting the existing file from the output folder ({outputZipPath})"); File.Delete(outputZipPath); LoggingService.Info( $"Existing file deleted successfully from the output folder ({outputZipPath})"); } else { throw new Exception($"Another File with same file exists in output location ({outputZipPath})"); } } ZipFile.CreateFromDirectory(sourceDirectory, outputZipPath); return(ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(ZipDirectoryActionResultsArgs.SourceDirectory, sourceDirectory) .WithArgument(ZipDirectoryActionResultsArgs.OutputZipPath, outputZipPath) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(ZipDirectoryActionResultsArgs.SourceDirectory, sourceDirectory) .WithArgument(ZipDirectoryActionResultsArgs.OutputZipPath, outputZipPath) )); } }
public ActionResult Execute(ArgumentCollection arguments) { List <string> files = null; try { if (arguments.HasArgument(ZipFilesActionExecutionArgs.FilesPaths)) { if (!(arguments[ZipFilesActionExecutionArgs.FilesPaths] is List <string> filePaths)) { throw new ArgumentsValidationException( $"unable to cast argument value into list of string. key({ZipFilesActionExecutionArgs.FilesPaths})"); } files = filePaths; // arguments.GetValue<string[]>(ZipFilesActionExecutionArgs.FilesPaths); } else if (arguments.HasArgument(ZipFilesActionExecutionArgs.FilesInDirectoryPath)) { var directory = arguments.GetValue <string>(ZipFilesActionExecutionArgs.FilesInDirectoryPath); if (Directory.Exists(directory)) { files = Directory.GetFiles(directory).ToList(); } } if (files == null) { if (!string.IsNullOrWhiteSpace(FilePath)) { files = new List <string>() { FilePath }; } else if (!string.IsNullOrWhiteSpace(FilesInDirectoryPath) && Directory.Exists(FilesInDirectoryPath)) { if (Directory.Exists(FilesInDirectoryPath)) { files = Directory.GetFiles(FilesInDirectoryPath).ToList(); } } } if (files == null) { throw new MissingArgumentsException($"Not source files to zip are defined. " + $"at least one of the following arguments must be set [{ZipFilesActionInstanceArgs.FilePath}, {ZipFilesActionInstanceArgs.FilesInDirectoryPath}, {ZipFilesActionExecutionArgs.FilesInDirectoryPath}, {ZipFilesActionExecutionArgs.FilesPaths} ]"); } if (!files.Any()) { LoggingService.Warn($"No files found to zip"); return(ActionResult.Succeeded()); } var missingFiles = files.Where(f => !File.Exists(f)).ToList(); if (!IgnoreMissingFiles && missingFiles.Any()) { throw new Exception( $"Cannot execute action because the following files are not found : ({string.Join(",", missingFiles)})"); } else if (IgnoreMissingFiles && files.Count == 1 && missingFiles.Any()) { throw new Exception( $"Cannot execute action because the unique file to zip is not found ({files.Single()})"); } string zipPath = null; if (arguments.HasArgument(ZipFilesActionExecutionArgs.ArchivePath)) { zipPath = arguments.GetValue <string>(ZipFilesActionExecutionArgs.ArchivePath); } else if (!string.IsNullOrWhiteSpace(ArchivePath)) { zipPath = ArchivePath; } if (string.IsNullOrWhiteSpace(zipPath)) { throw new MissingArgumentsException( $"No archive path was specified in instance or executing arguments." + $" at least one of this arguments must be set Instance[{ZipFilesActionInstanceArgs.ArchivePath}] Execution[{ZipFilesActionExecutionArgs.ArchivePath}]"); } var results = ZipUtilities.AddFilesToArchive(zipPath, files); if (results) { if (DeleteZippedFiles) { LoggingService.Debug($"Deleting ({files.Count}) Zipped files"); foreach (var file in files) { try { LoggingService.Debug($"Deleting Zipped File {file}"); File.Delete(file); LoggingService.Debug($"Zipped File {file} deleted successfully"); } catch (Exception exception) { LoggingService.Error(exception); } } } else if (MoveZippedFiles && !string.IsNullOrWhiteSpace(MoveZippedFilesToPath)) { LoggingService.Debug($"Moving ({files.Count}) Zipped files to path {MoveZippedFilesToPath}"); if (!Directory.Exists(MoveZippedFilesToPath)) { Directory.CreateDirectory(MoveZippedFilesToPath); } foreach (var file in files) { try { var destinationFilePath = Path.Combine(MoveZippedFilesToPath, Path.GetFileName(file)); LoggingService.Debug($"Moving file {file} to {destinationFilePath}"); File.Move(file, destinationFilePath); LoggingService.Debug( $"Zipped file {Path.GetFileName(file)} moved successfully to {MoveZippedFilesToPath}"); } catch (Exception exception) { LoggingService.Error(exception); } } } } return(results? ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(ZipFilesActionResultArgs.ArchivePath, ArchivePath) .WithArgument(ZipFilesActionResultArgs.ZippedFiles, files) ) : ActionResult.Failed() .WithAdditionInformation(ArgumentCollection.New() .WithArgument(ZipFilesActionResultArgs.ArchivePath, ArchivePath) .WithArgument(ZipFilesActionResultArgs.ZippedFiles, files ?? new List <string>()) ) ); } catch (Exception exception) { return(ActionResult.Failed().WithException(exception) .WithAdditionInformation(ArgumentCollection.New() .WithArgument(ZipFilesActionResultArgs.ArchivePath, ArchivePath) .WithArgument(ZipFilesActionResultArgs.ZippedFiles, files ?? new List <string>()) ) ); } }
public ActionResult Execute(ArgumentCollection arguments) { string serviceName = null; try { if (arguments.HasArgument(WinServiceActionExecutionArgs.ServiceName)) { serviceName = arguments.GetValue <string>(WinServiceActionExecutionArgs.ServiceName); } if (serviceName == null && !string.IsNullOrWhiteSpace(ServiceName)) { serviceName = ServiceName; } if (string.IsNullOrWhiteSpace(serviceName)) { throw new Exception($"Missing Argument {WinServiceActionInstanceArgs.ServiceName}"); } if (!TryGetTargetStatus(out ServiceTargetStatus status)) { throw new Exception($"Unexpected Target Status Value ({Status}) Expected valid casting from ({typeof(ServiceTargetStatus)})"); } bool result = false; switch (status) { case ServiceTargetStatus.Start: { result = WinServiceUtilities.StartService(serviceName, Wait, WaitTimeout); break; } case ServiceTargetStatus.Stop: { result = WinServiceUtilities.StopService(serviceName, Wait, WaitTimeout); break; } case ServiceTargetStatus.Pause: { result = WinServiceUtilities.PauseService(serviceName, Wait, WaitTimeout); break; } case ServiceTargetStatus.Resume: { result = WinServiceUtilities.ResumeService(serviceName, Wait, WaitTimeout); break; } default: { throw new Exception("Unexpected ControlStatus when switching Control cases"); } } return(result ? ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(WinServiceActionResultsArgs.ServiceName, serviceName) .WithArgument(WinServiceActionResultsArgs.ActionTargetStatus, Status) ) : ActionResult.Failed().WithAdditionInformation(ArgumentCollection.New() .WithArgument(WinServiceActionResultsArgs.ServiceName, serviceName) .WithArgument(WinServiceActionResultsArgs.ActionTargetStatus, Status) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(WinServiceActionResultsArgs.ServiceName, serviceName) .WithArgument(WinServiceActionResultsArgs.ActionTargetStatus, Status) )); } }
public ActionResult Execute(ArgumentCollection arguments) { List <string> deletedFiles = new List <string>(); List <string> failedFiles = new List <string>(); try { // Must provide arguments if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (!arguments.HasArgument(FtpDeleteActionExecutionArgs.RemoteFilesCollection)) { throw new MissingArgumentException(FtpDeleteActionExecutionArgs.RemoteFilesCollection); } if (!(arguments[FtpDeleteActionExecutionArgs.RemoteFilesCollection] is List <string> remotePaths)) { throw new ArgumentsValidationException( $"unable to cast argument value into list of string. key({FtpDeleteActionExecutionArgs.RemoteFilesCollection})"); } using (FtpClient ftpClient = new FtpClient(Host, Port, Username, Password)) { if (!string.IsNullOrWhiteSpace(RemoteWorkingDir)) { ftpClient.SetWorkingDirectory(RemoteWorkingDir); } foreach (var remotePath in remotePaths) { try { LoggingService.Debug($"Deleting remote file {remotePath}"); ftpClient.DeleteFile(remotePath); deletedFiles.Add(remotePath); } catch (Exception exception) { LoggingService.Error(exception); failedFiles.Add(remotePath); } } } if (deletedFiles.Any()) { return(ActionResult.Succeeded() .WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpDeleteActionResultArgs.DeletedFiles, deletedFiles) .WithArgument(FtpDeleteActionResultArgs.FailedFiles, failedFiles) ) ); } return(ActionResult.Failed().WithAdditionInformation( ArgumentCollection.New() .WithArgument(FtpDeleteActionResultArgs.DeletedFiles, deletedFiles) .WithArgument(FtpDeleteActionResultArgs.FailedFiles, failedFiles) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception) .WithAdditionInformation(ArgumentCollection.New() .WithArgument(FtpDeleteActionResultArgs.DeletedFiles, deletedFiles) .WithArgument(FtpDeleteActionResultArgs.FailedFiles, failedFiles))); } }
public ActionResult Execute(ArgumentCollection arguments) { string outputDirPath = null; string sourceZipPath = null; try { if (arguments.HasArgument(UnzipArchiveActionExecutionArgs.OutputDirPath)) { outputDirPath = arguments.GetValue <string>(UnzipArchiveActionExecutionArgs.OutputDirPath); } if (arguments.HasArgument(UnzipArchiveActionExecutionArgs.SourceZipPath)) { sourceZipPath = arguments.GetValue <string>(UnzipArchiveActionExecutionArgs.SourceZipPath); } if (string.IsNullOrWhiteSpace(outputDirPath)) { if (!string.IsNullOrWhiteSpace(OutputDirPath)) { outputDirPath = OutputDirPath; } } if (string.IsNullOrWhiteSpace(sourceZipPath)) { if (!string.IsNullOrWhiteSpace(SourceZipPath)) { sourceZipPath = SourceZipPath; } } if (string.IsNullOrWhiteSpace(sourceZipPath)) { throw new MissingArgumentException(UnzipArchiveActionExecutionArgs.SourceZipPath); } if (string.IsNullOrWhiteSpace(outputDirPath)) { throw new MissingArgumentException(UnzipArchiveActionExecutionArgs.OutputDirPath); } var result = ZipUtilities.ExtractArchive(sourceZipPath, outputDirPath, OverrideFiles); return(result ? ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(UnzipArchiveActionResultsArgs.OutputDirPath, outputDirPath) .WithArgument(UnzipArchiveActionResultsArgs.SourceZipPath, sourceZipPath) ) : ActionResult.Failed().WithAdditionInformation(ArgumentCollection.New() .WithArgument(UnzipArchiveActionResultsArgs.OutputDirPath, outputDirPath) .WithArgument(UnzipArchiveActionResultsArgs.SourceZipPath, sourceZipPath))); } catch (Exception exception) { return(ActionResult.Failed().WithException(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(UnzipArchiveActionResultsArgs.OutputDirPath, outputDirPath) .WithArgument(UnzipArchiveActionResultsArgs.SourceZipPath, sourceZipPath))); } }
/// <summary> /// Executes the specified arguments. /// </summary> /// <param name="arguments">The arguments.</param> /// <returns></returns> /// <exception cref="Exception"> /// Missing mandatory execution argument: {GenerateQRCodeActionExecutionArgs.PlainText} /// or /// Mandatory instance argument is not set : {GenerateQRCodeActionInstanceArgs.ErrorCorrectionLevel} /// or /// Wrong value for argument: {GenerateQRCodeActionInstanceArgs.PixelPerModule} set to {PixelPerModule} /// or /// Mandatory instance argument is not set : {GenerateQRCodeActionInstanceArgs.ImageFormat} /// or /// Missing mandatory argument: {GenerateQRCodeActionExecutionArgs.OutputFilePath} /// or /// Another file with the same name exist: {outputFilePath} /// or /// Failed to get the QR Code image. /// </exception> public ActionResult Execute(ArgumentCollection arguments) { var plainText = string.Empty; var outputFilePath = OutputFilePath; try { if (arguments.HasArgument(GenerateQRCodeActionExecutionArgs.PlainText)) { plainText = arguments.GetValue <string>(GenerateQRCodeActionExecutionArgs.PlainText); } if (string.IsNullOrWhiteSpace(plainText)) { throw new Exception( $"Missing mandatory execution argument: {GenerateQRCodeActionExecutionArgs.PlainText}"); } QRCodeGenerator.ECCLevel?errorCorrectLevel = null; if (!string.IsNullOrWhiteSpace(ErrorCorrectLevel)) { if (Enum.TryParse <QRCodeGenerator.ECCLevel>(ErrorCorrectLevel, true, out var eccl)) { errorCorrectLevel = eccl; } } if (!errorCorrectLevel.HasValue) { throw new Exception( $"Mandatory instance argument is not set : {GenerateQRCodeActionInstanceArgs.ErrorCorrectionLevel}"); } var pixelPerModule = 0; if (PixelPerModule >= MinPixelPerModule && PixelPerModule <= MaxPixelPerModule) { pixelPerModule = PixelPerModule; } if (pixelPerModule == 0) { throw new Exception( $"Wrong value for argument: {GenerateQRCodeActionInstanceArgs.PixelPerModule} set to {PixelPerModule}"); } string imageFormat = null; if (!string.IsNullOrWhiteSpace(ImageFormat) && AllowedImageFormats() .Any(f => string.Equals(f, ImageFormat, StringComparison.CurrentCultureIgnoreCase))) { imageFormat = ImageFormat; } if (imageFormat == null) { throw new Exception( $"Mandatory instance argument is not set : {GenerateQRCodeActionInstanceArgs.ImageFormat}"); } if (string.IsNullOrWhiteSpace(outputFilePath)) { if (arguments.HasArgument(GenerateQRCodeActionExecutionArgs.OutputFilePath)) { outputFilePath = arguments.GetValue <string>(GenerateQRCodeActionExecutionArgs.OutputFilePath); } } if (string.IsNullOrWhiteSpace(outputFilePath)) { throw new Exception( $"Missing mandatory argument: {GenerateQRCodeActionExecutionArgs.OutputFilePath}"); } if (EraseExistingFile) { if (File.Exists(outputFilePath)) { File.Delete(outputFilePath); } } if (File.Exists(outputFilePath)) { throw new Exception($"Another file with the same name exist: {outputFilePath}"); } byte[] qrCodeBytes = null; using (var qrCodeGenerator = new QRCodeGenerator()) { var qrCodeData = qrCodeGenerator.CreateQrCode(plainText, errorCorrectLevel.Value, ForceUtf8); if (qrCodeData != null) { qrCodeBytes = GetByteQrCode(imageFormat, pixelPerModule, qrCodeData); } } if (qrCodeBytes == null) { throw new Exception("Failed to get the QR Code image."); } File.WriteAllBytes(outputFilePath, qrCodeBytes); // qrCodeImage.Save(outputFilePath, imageFormat); return(ActionResult.Succeeded().WithAdditionInformation(ArgumentCollection.New() .WithArgument(GenerateQRCodeActionResultsArgs.OutputFilePath, outputFilePath) .WithArgument(GenerateQRCodeActionResultsArgs.QRCodeData, plainText) )); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed(exception).WithAdditionInformation(ArgumentCollection.New() .WithArgument(GenerateQRCodeActionResultsArgs.OutputFilePath, outputFilePath) .WithArgument(GenerateQRCodeActionResultsArgs.QRCodeData, plainText) )); } }
public ActionResult Execute(ArgumentCollection arguments) { try { if (!IsValid()) { return(new ActionResult(false, new ArgumentCollection( ("ERROR", "MANDATORY_PROPERTY_MISSING") ))); } if (arguments.HasArgument(EmailSenderExecutionArgs.Subject)) { this.Subject = arguments[EmailSenderExecutionArgs.Subject].ToString(); } if (arguments.HasArgument(EmailSenderExecutionArgs.Body)) { this.Body = arguments[EmailSenderExecutionArgs.Body].ToString(); } List <string> attachments = new List <string>(); if (arguments.HasArgument(EmailSenderExecutionArgs.AttachedFile)) { LoggingService.Debug($"Arguments contains argument ({nameof(EmailSenderExecutionArgs.AttachedFile)})"); var attachmentsArgValue = arguments[EmailSenderExecutionArgs.AttachedFile]; if (attachmentsArgValue is string) { LoggingService.Debug($"Argument ({nameof(EmailSenderExecutionArgs.AttachedFile)}) is a string"); this.AttachedFile = attachmentsArgValue.ToString(); } else if (attachmentsArgValue is IEnumerable <string> value) { LoggingService.Debug($"Argument ({nameof(EmailSenderExecutionArgs.AttachedFile)}) is a IEnumerable<string>"); attachments.AddRange(value); } else { LoggingService.Error($"({nameof(EmailSenderExecutionArgs.AttachedFile)}) is in type ({attachmentsArgValue.GetType()})"); } // this.AttachedFile = arguments[EmailSenderExecutionArgs.AttachedFile].ToString(); } using (SmtpClient smtpClient = new SmtpClient(this.SmtpHost)) { // Smtp smtpClient.Port = Port; smtpClient.Credentials = new NetworkCredential(Username, Password); smtpClient.EnableSsl = EnableSsl; List <Stream> attachmentsStreams = new List <Stream>(); // Email Message using (var mail = new MailMessage() { From = new MailAddress(SenderEmail, SenderDisplayName), Subject = this.Subject, Body = this.Body }) { mail.To.Add(RecipientEmail); // Attachment if (!attachments.Any() && !string.IsNullOrWhiteSpace(AttachedFile)) { attachments.Add(AttachedFile); } if (attachments.Any()) { foreach (var attachment in attachments) { Stream attachmentStream = null; if (!string.IsNullOrWhiteSpace(attachment) && File.Exists(attachment)) { string fileName = Path.GetFileName(attachment); attachmentStream = File.Open(attachment, FileMode.Open, FileAccess.Read); mail.Attachments.Add(new Attachment(attachmentStream, fileName)); } if (attachmentStream != null) { attachmentsStreams.Add(attachmentStream); } } } // Send var sendingTask = smtpClient.SendMailAsync(mail); sendingTask.GetAwaiter().GetResult(); } if (attachmentsStreams.Any()) { attachmentsStreams.ForEach(a => a?.Close()); } } return(ActionResult.Succeeded()); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed()); } }