/// <summary> /// Parses input parameters and finds the correct service and command handler for executing the command. /// </summary> /// <param name="input"> /// User input from command line arguments, split into list of parameters separated by space. /// Commands are structured as follows: [command] [subCommand] [options] /// </param> /// <returns>A commandHandler that can execute the command given by user input</returns> private ISubCommandHandler ProcessArgs(string[] input) { ISubCommandHandler subCommandHandler = ServiceProvider.GetServices <ISubCommandHandler>() .FirstOrDefault(s => string.Equals(s.Name, input[1], StringComparison.OrdinalIgnoreCase) && string.Equals(s.CommandProvider, input[0], StringComparison.OrdinalIgnoreCase)); if (subCommandHandler != null) { subCommandHandler.BuildSelectableCommands(); subCommandHandler.DictOptions = ParseArguments(input); OptionBuilder.Instance(_logger).AssignValueToCliOptions(subCommandHandler); return(subCommandHandler); } // No command found, find help command to display help. IHelp helpService = ServiceProvider.GetServices <IHelp>().FirstOrDefault(); if (helpService != null) { helpService.GetHelp(); } else { _logger.LogError("Help is not found"); } return(null); }
private void RunCommandWithParameters(string[] input, ICommand command) { ISubCommandHandler subCommandHandler = ProcessArgs(input); if (subCommandHandler != null) { if (subCommandHandler.IsValid) { if (subCommandHandler.IsValid) { command.Run(subCommandHandler); } else if (subCommandHandler.IsValid) { command.Run(ParseArguments(input)); } } else { _logger.LogError($"Command error: {subCommandHandler.ErrorMessage}"); } } else { command.Run(); } }
public virtual void Run(ISubCommandHandler subCommandHandler) { if (subCommandHandler != null) { subCommandHandler.Run(); } }
/// <summary> /// /// </summary> /// <param name="subCommandHandler"></param> public virtual void Run(ISubCommandHandler subCommandHandler) { if (subCommandHandler != null) { subCommandHandler.Run(); } else { _logger.LogError($"Missing sub command, use help to find avilable sub commands."); } }
public void Run(ISubCommandHandler commandHandler = null) { if (commandHandler == null) { Console.WriteLine(); Console.WriteLine(Usage); Console.WriteLine(); } else { commandHandler.Run(); } }
/// <summary> /// Builds the parameters that can be used by a sub command. /// </summary> /// <param name="commandHandler">The SubCommand for which the parameters are build</param> /// <returns>List of sub command parameters</returns> public List <IOption> BuildAvailableOptions(ISubCommandHandler commandHandler) { List <IOption> subCommandOptions = new List <IOption>(); // the defintion file shall be only be read at startup if (_instance.CfgCommands == null) { _instance.LoadCommandFile(); } if (CfgCommands.Commands == null || CfgCommands.Commands.Count == 0) { _logger.LogError("There is not define any cli commands, check command definition file"); } else { // find defined sub command with options and build an option list CfgSubCommand cfgCubCommand = CfgCommands.Commands.FirstOrDefault(x => x.Name == commandHandler.CommandProvider)? .SubCommands.FirstOrDefault(y => y.Name == commandHandler.Name); if (cfgCubCommand != null && cfgCubCommand.Options != null) { List <CfgOption> cfgOptions = cfgCubCommand.Options; foreach (CfgOption cfgOption in cfgOptions) { IOption option = CreateOption(cfgOption); if (option != null) { subCommandOptions.Add(CreateOption(cfgOption)); } } } } return(subCommandOptions); }
/// <summary> /// Assigns value for the options defined as input parameters to selectable parameters. /// </summary> /// <param name="commandHandler"></param> /// <returns>Status of assignments which includes validation of parameters</returns> public bool AssignValueToCliOptions(ISubCommandHandler commandHandler) { bool isValid = true; foreach (IOption option in commandHandler.SelectableCliOptions) { KeyValuePair <string, string> valuePair = commandHandler.DictOptions.FirstOrDefault(x => string.Equals(x.Key, option.Name, StringComparison.OrdinalIgnoreCase)); if (valuePair.Value != null) { // validate according to option type option.Value = valuePair.Value; option.IsValid = option.Validate(); option.IsAssigned = true; if (option.IsValid == false) { isValid = false; } } } return(isValid); }
public void Run(ISubCommandHandler commandHandler = null) { AllCommandsHelp(); }
public void Storage_UploadData__File_Exits_File_Uploaded() { string expectedOwnerId = "ownerId"; string expectedOwnerIdValue = "50013748"; string expectedInstanceId = "instanceId"; string expectedInstanceIdValue = "bd5d5066-5ae4-42eb-8d5d-076a600acdd5"; string expectedElementType = "elementType"; string expectedElementTypeValue = "kvittering"; string expectedFile = "file"; string expectedFileValue = @"c:\Temp\test.xml"; int expectedLogEntries = 1; string expectedFileUploadedMessage = "was successfully uploaded"; string environmentSetting = "{\"UseLiveClient\": \"false\"}"; NullLogger <OptionBuilder> logger = new NullLogger <OptionBuilder>(); TextWriter textWriter = new StringWriter(); ConfigureLogging(textWriter); BuildEnvironment(environmentSetting); Dictionary <string, string> cliOptions = new Dictionary <string, string>(); cliOptions.Add(expectedOwnerId, expectedOwnerIdValue); cliOptions.Add(expectedInstanceId, expectedInstanceIdValue); cliOptions.Add(expectedElementType, expectedElementTypeValue); cliOptions.Add(expectedFile, expectedFileValue); // Define which command and sub command that shall be registered in service provider List <Type> availableCommandTypes = new List <Type>(); availableCommandTypes.Add(typeof(StorageCommand)); List <Type> availableSubCommands = new List <Type>(); availableSubCommands.Add(typeof(UploadData)); // Register commands and sub commands ServiceProvider serviceProvider = TestDataBuilder.BuildServiceProvider(availableCommandTypes, availableSubCommands, Log.Logger); // Fetch UploadData subCommand and assign available options by use og OptionBuilder. Options for the command is fetched from // the Command resource file defined in the Cli project var sssList = serviceProvider.GetServices <ISubCommandHandler>().ToList(); ISubCommandHandler subCommandHandler = sssList.First(x => x.Name == "UploadData"); OptionBuilder builder = OptionBuilder.Instance(logger); subCommandHandler.SelectableCliOptions = builder.BuildAvailableOptions(subCommandHandler); subCommandHandler.DictOptions = cliOptions; // Need to mock the FileOption to avoid dependency to disk, so replace the registered option with a mock option FileOption <FileStream> mockFileOption = Mock.Of <FileOption <FileStream> >(x => x.Validate()); ReplaceSelectableOption("file", mockFileOption, subCommandHandler.SelectableCliOptions); // Mock the file wrapper Mock <IFileWrapper> mockedWrapper = new Mock <IFileWrapper>(); mockedWrapper.Setup(x => x.GetFile(It.IsAny <string>())).Returns(new MemoryStream()); subCommandHandler.CliFileWrapper = mockedWrapper.Object; // Set response from ClientWrapper StorageClientFileWrapper.IsSuccessStatusCode = true; // Assign the input options to the subCommand subCommandHandler.DictOptions = cliOptions; // Assign and validate the input options to the selectable options builder.AssignValueToCliOptions(subCommandHandler); // Run the command subCommandHandler.Run(); // Verify that the log contain expected result List <string> logEntries = GetLogEntries(textWriter); Assert.AreEqual(expectedLogEntries, logEntries.Count); string logMessage = logEntries.FirstOrDefault(x => x.Contains(expectedFileUploadedMessage)); Assert.IsFalse(string.IsNullOrEmpty(logMessage)); Assert.IsTrue(logMessage.Contains(expectedFileValue)); textWriter.Dispose(); builder.CfgCommands = null; }
public void Storage_UploadData_No_File() { string expectedOwnerId = "ownerId"; string expectedOwnerIdValue = "50013748"; string expectedInstanceId = "instanceId"; string expectedInstanceIdValue = "bd5d5066-5ae4-42eb-8d5d-076a600acdd5"; string expectedElementType = "elementType"; string expectedElementTypeValue = "kvittering"; string expectedFile = "file"; string expectedFileValue = @"c:\Temp\test.xml"; string expectedLogMessage = "No valid combination"; int expectedLogEntries = 2; string expectedFileNotFoundErrorMessage = "Invalid value for parameter"; string environmentSetting = "{\"UseLiveClient\": \"false\"}"; NullLogger <OptionBuilder> logger = new NullLogger <OptionBuilder>(); // Configure logger which is set on registered classes/objects TextWriter textWriter = new StringWriter(); ConfigureLogging(textWriter); BuildEnvironment(environmentSetting); // Build command options Dictionary <string, string> cliOptions = new Dictionary <string, string>(); cliOptions.Add(expectedOwnerId, expectedOwnerIdValue); cliOptions.Add(expectedInstanceId, expectedInstanceIdValue); cliOptions.Add(expectedElementType, expectedElementTypeValue); cliOptions.Add(expectedFile, expectedFileValue); // Define which command and sub command that shall be registered in service provider List <Type> availableCommandTypes = new List <Type>(); availableCommandTypes.Add(typeof(StorageCommand)); List <Type> availableSubCommands = new List <Type>(); availableSubCommands.Add(typeof(UploadData)); // Register commands and sub commands ServiceProvider serviceProvider = TestDataBuilder.BuildServiceProvider(availableCommandTypes, availableSubCommands, Log.Logger); // Fetch UploadData subCommand and assign available options by use og OptionBuilder. Options for the command is fetched from // the Command resource file defined in the Cli project var sssList = serviceProvider.GetServices <ISubCommandHandler>().ToList(); ISubCommandHandler subCommandHandler = sssList.First(x => x.Name == "UploadData"); OptionBuilder builder = OptionBuilder.Instance(logger); subCommandHandler.SelectableCliOptions = builder.BuildAvailableOptions(subCommandHandler); subCommandHandler.DictOptions = cliOptions; // Need to mock the FileOption to avoid dependency to disk, so replace the registered option with a mock option FileOption <FileStream> mockFileOption = Mock.Of <FileOption <FileStream> >(x => x.Validate() == false && x.ErrorMessage == expectedFileNotFoundErrorMessage); ReplaceSelectableOption("file", mockFileOption, subCommandHandler.SelectableCliOptions); // Assign the input options to the subCommand subCommandHandler.DictOptions = cliOptions; // Assign and validate the input options to the selectable options builder.AssignValueToCliOptions(subCommandHandler); // Run the command subCommandHandler.Run(); // Verify that the log contain expected result List <string> logEntries = GetLogEntries(textWriter); Assert.AreEqual(expectedLogEntries, logEntries.Count); string logMessage = logEntries.FirstOrDefault(x => x.Contains(expectedLogMessage)); Assert.IsFalse(string.IsNullOrEmpty(logMessage)); string fileNotFoundMessage = logEntries.FirstOrDefault(x => x.Contains(expectedFileNotFoundErrorMessage)); Assert.IsFalse(string.IsNullOrEmpty(fileNotFoundMessage)); textWriter.Dispose(); builder.CfgCommands = null; }
public void Storage_GetData_Wrong_Option_Combination() { string expectedOption = "TestOption"; string expectedDataType = "string"; string expectedDescription = "Option test description"; string expectedApiName = "TestApiName"; string expectedValue = "TestValue"; string expectedLogMessage = "No valid combination"; int expectedLogEntries = 1; string environmentSetting = "{\"UseLiveClient\": \"false\"}"; NullLogger <OptionBuilder> logger = new NullLogger <OptionBuilder>(); // Configure logger which is set on registered classes/objects TextWriter textWriter = new StringWriter(); ConfigureLogging(textWriter); BuildEnvironment(environmentSetting); // Build command options OptionBuilder builder = OptionBuilder.Instance(logger); List <IOption> selectableOptions = new List <IOption>(); selectableOptions.Add(TestDataBuilder.CreateOption(expectedOption, expectedDataType, expectedDescription, expectedApiName)); Dictionary <string, string> cliOptions = new Dictionary <string, string>(); cliOptions.Add(expectedOption, expectedValue); // Define which command and sub command that shall be registered in service provider List <Type> availableCommandTypes = new List <Type>(); availableCommandTypes.Add(typeof(StorageCommand)); List <Type> availableSubCommands = new List <Type>(); availableSubCommands.Add(typeof(GetDataHandler)); // Register commands and sub commands ServiceProvider serviceProvider = TestDataBuilder.BuildServiceProvider(availableCommandTypes, availableSubCommands, Log.Logger); // Fetch GetDataHandler subCommand var sssList = serviceProvider.GetServices <ISubCommandHandler>().ToList(); ISubCommandHandler subCommandHandler = sssList.First(x => x.Name == "GetData"); subCommandHandler.SelectableCliOptions = selectableOptions; subCommandHandler.DictOptions = cliOptions; // Assign option values to the sub command builder.AssignValueToCliOptions(subCommandHandler); // Run the command subCommandHandler.Run(); // Verify that the log contain expected result List <string> logEntries = GetLogEntries(textWriter); Assert.AreEqual(expectedLogEntries, logEntries.Count); string logMessage = logEntries.FirstOrDefault(x => x.Contains(expectedLogMessage)); Assert.IsFalse(string.IsNullOrEmpty(logMessage)); textWriter.Dispose(); builder.CfgCommands = null; }
public void Storage_GetData_Data_For_Instance() { string expectedOrgOption = "org"; string expectedOrgDataType = "string"; string expectedOrgDescription = "org"; string expectedOrgApiName = "org"; string expectedOrgValue = "5533"; string expectedFetchMessage = "Fetched 1 instances."; string expectedSaveMessage = "File:Kvittering"; int expectedLogEntries = 2; string environmentSetting = "{\"UseLiveClient\": \"false\"}"; NullLogger <OptionBuilder> logger = new NullLogger <OptionBuilder>(); // Configure logger which is set on registered classes/objects TextWriter textWriter = new StringWriter(); ConfigureLogging(textWriter); BuildEnvironment(environmentSetting); // Build command options OptionBuilder builder = OptionBuilder.Instance(logger); List <IOption> selectableOptions = new List <IOption>(); selectableOptions.Add(TestDataBuilder.CreateOption(expectedOrgOption, expectedOrgDataType, expectedOrgDescription, expectedOrgApiName)); Dictionary <string, string> cliOptions = new Dictionary <string, string>(); cliOptions.Add(expectedOrgOption, expectedOrgValue); // Define which command and sub command that shall be registered in service provider List <Type> availableCommandTypes = new List <Type>(); availableCommandTypes.Add(typeof(StorageCommand)); List <Type> availableSubCommands = new List <Type>(); availableSubCommands.Add(typeof(GetDataHandler)); // Register commands and sub commands ServiceProvider serviceProvider = TestDataBuilder.BuildServiceProvider(availableCommandTypes, availableSubCommands, Log.Logger); // Set response from ClientWrapper InstanceResponseMessage response = TestDataBuilder.CreateInstanceResponse(1); StorageClientFileWrapper.InstanceResponse = response; StorageClientFileWrapper.DataContent = new MemoryStream(); // Fetch GetDataHandler subCommand var sssList = serviceProvider.GetServices <ISubCommandHandler>().ToList(); ISubCommandHandler subCommandHandler = sssList.First(x => x.Name == "GetData"); subCommandHandler.SelectableCliOptions = selectableOptions; subCommandHandler.DictOptions = cliOptions; // Mock the file wrapper Mock <IFileWrapper> mockedWrapper = new Mock <IFileWrapper>(); mockedWrapper.Setup(x => x.SaveToFile(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Stream>())).Returns(true); subCommandHandler.CliFileWrapper = mockedWrapper.Object; // Assign option values to the sub command builder.AssignValueToCliOptions(subCommandHandler); // Run the command subCommandHandler.Run(); // Verify that the log contain expected result List <string> logEntries = GetLogEntries(textWriter); Assert.AreEqual(expectedLogEntries, logEntries.Count); string fetchMessage = logEntries.FirstOrDefault(x => x.Contains(expectedFetchMessage)); Assert.IsFalse(string.IsNullOrEmpty(fetchMessage)); string saveMessage = logEntries.FirstOrDefault(x => x.Contains(expectedSaveMessage)); Assert.IsFalse(string.IsNullOrEmpty(saveMessage)); textWriter.Dispose(); builder.CfgCommands = null; }
public void Run(ISubCommandHandler commandHandler = null) { Environment.Exit(0); }