private static void PerformCommand() { if (CommandIsNotAllowed()) { return; } CommandExecutionResult result = null; try { result = CommandHandlerFactory .Create(_executionContext.Command.CommandType) .Execute(_executionContext.Command.Parameters, _executionContext.CurrentScreen.Model); } catch (Exception exception) { ExceptionScreen(exception); return; } _executionContext.CurrentScreen = result.NextScreenType.HasValue ? ScreenFactory.CreateScreen(_render, result.NextScreenType.Value, result.Model) : null; _executionContext.Command = null; _render.Clear(); }
public override CommandExecutionResult Execute() { try { using (var adminContext = new AdministrationDbContext()) { var system = adminContext.GetSystemInstance(); Log.Info(system.Description); var agencies = adminContext.GetSystemInstance() .Agencies .Select(a => new { a.Name, a.Jurisdiction.Ori }) .ToList(); foreach (var agency in agencies) { Log.Info("[{0}]\t{1}", agency.Ori, agency.Name); } } } catch (Exception ex) { return(CommandExecutionResult.Exception(ex)); } return(CommandExecutionResult.Ok()); }
//Gets the left over diskspace on the FROST device: public string[] getDeviceDiskUsage() { try { CommandExecutionResult strOut = s.ExecuteCommand("df -h | grep mmc"); Console.WriteLine(strOut.Output.ToString()); //Split the string on spaces. Warning space count can be random, so clean up the array by removing all empty or only space containing values. int I = 0; //I counter string[] strRetArr = new string[6]; // 6 long as the / is the last character to enter string[] strBufArr = strOut.Output.Split(' '); //split on space foreach (string str in strBufArr) //loop the splited string as an array { if (str != "" && str != " ") //skip empty or spaces; { strRetArr[I] = str; // add usefull data to return array; Console.WriteLine(strRetArr[I]); I++; } } return(strRetArr); } catch (Exception e) { string[] errorstring = new string[2]; errorstring[0] = "Exception happend loading diskusage!"; errorstring[1] = e.ToString(); return(errorstring); } }
public void HttpResponseDataInResult() { MockServiceTracer tracer = new MockServiceTracer(); System.Net.Http.HttpResponseMessage httpResponse = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Accepted); httpResponse.Headers.Add("x-ms-header", "value"); tracer.HttpResponses.Add(httpResponse); LiveTestRequest request = new LiveTestRequest(); request.Id = "12345"; request.JsonRpc = "2.0"; request.HttpResponse = true; CommandExecutionResult result = new CommandExecutionResult(null, null, false); LiveTestResponse response = request.MakeResponse(result, tracer, this.logger); Assert.NotNull(response.Result.Headers); Assert.True(response.Result.Headers is Dictionary <string, object>); Dictionary <string, object> headers = (Dictionary <string, object>)response.Result.Headers; Assert.Equal(1, headers.Count); Assert.True(headers.ContainsKey("x-ms-header")); Assert.Equal(new string[] { "value" }, headers["x-ms-header"]); Assert.Equal((long)System.Net.HttpStatusCode.Accepted, response.Result.StatusCode); }
static void Main(string[] args) { DMDVision.Commands.CommandContext context = new DMDVision.Commands.CommandContext(); List <ICommand> commands = new List <ICommand>(); commands.Add(new DMDVision.Commands.ClaimFundsCommand()); var originalForegroundColor = Console.ForegroundColor; foreach (ICommand command in commands) { bool success = false; string message = ""; try { message = command.Execute(context); success = true; } catch (Exception e) { success = false; message = e.Message; } CommandExecutionResult result = new CommandExecutionResult(success, message); Console.ForegroundColor = result.Success ? originalForegroundColor : ConsoleColor.Red; Console.WriteLine(result.Text); } }
public void MultipleResultResponse() { MockServiceTracer tracer = new MockServiceTracer(); object psResult1 = 5; object psResult2 = "test"; List <object> psResults = new List <object>(); psResults.Add(psResult1); psResults.Add(psResult2); CommandExecutionResult result = new CommandExecutionResult(psResults, null, false); LiveTestRequest request = new LiveTestRequest(); request.Id = "12345"; request.JsonRpc = "2.0"; LiveTestResponse response = request.MakeResponse(result, tracer, this.logger); Assert.Equal(request.Id, response.Id); Assert.Equal(request.JsonRpc, response.JsonRpc); Assert.NotNull(response.Result); Assert.Null(response.Result.Headers); Assert.Equal(default(long), response.Result.StatusCode); Assert.NotNull(response.Result.Response); Assert.Collection <object>((object[])response.Result.Response, new Action <object>[] { (obj) => { Assert.Equal(psResult1, obj); }, (obj) => { Assert.Equal(psResult2, obj); } }); }
//Save device temperature ranges: public bool setTemperatureRanges(string _tempRangeMin, string _tempRangeMax) { CommandExecutionResult strOut = s.ExecuteCommand("echo \"" + _tempRangeMin + ":" + _tempRangeMax + "\" > /home/FROST/FROST_TempRanges.conf"); Console.WriteLine(strOut.IsSuccess.ToString()); return(strOut.IsSuccess); }
public ICommandExecutionResult ExecuteCommand() { try { var sw1 = new Stopwatch(); using (var db = BotEngine.Storage.Clone()) { sw1.Start(); db.Store(BotEngine.SceneNodes); db.Commit(); } sw1.Stop(); var ret = new CommandExecutionResult { DisplayMessage = string.Format("World backup completed in {0} ms.", sw1.ElapsedMilliseconds) }; return(ret); } catch (Exception ex) { return(new CommandExecutionResult() { DisplayMessage = ex.Message }); } }
public override CommandExecutionResult Execute() { try { var result = new CommandExecutionResult(); _notifier.Notify(new CreateMovieCommand() { Title = Title, Budget = Budget, Salary = Salary, ImagePath = ImagePath, Description = Description, ReleaseDate = ReleaseDate, DirectorId = DirectorId, Genres = Genres, ActorIds = ActorIds }); return(Ok()); } catch (Exception exception) { return(Fail(exception)); } }
//Save device measurement interval: public bool setMeasureInterval(string _measureInterval) { CommandExecutionResult strOut = s.ExecuteCommand("echo \"" + _measureInterval + "\" > /home/FROST/FROST_MeasureInterval.conf"); Console.WriteLine(strOut.IsSuccess.ToString()); return(strOut.IsSuccess); }
//Save user new login password: public bool setCurrentUserNewPassword(string userName, string strOldPassword, string strNewPassword) { CommandExecutionResult strOut = s.ExecuteCommand("echo -e \"" + strOldPassword + "\n" + strNewPassword + "\n" + strNewPassword + "\" | passwd " + userName); Console.WriteLine(strOut.IsSuccess.ToString()); return(strOut.IsSuccess); }
//Save device name: public bool setDeviceName(string _deviceName) { CommandExecutionResult strOut = s.ExecuteCommand("echo \"" + _deviceName + "\" > /home/FROST/FROST_DeviceName.conf"); Console.WriteLine(strOut.IsSuccess.ToString()); return(strOut.IsSuccess); }
//Load device measure inteval: public string getMeasureInterval() { CommandExecutionResult strOut = s.ExecuteCommand("cat /home/FROST/FROST_MeasureInterval.conf"); Console.WriteLine(strOut.Output.ToString()); return(strOut.Output.ToString()); }
public void ProcessOperationFromJsonFull() { MockRunspaceManager runspace = new MockRunspaceManager(); GeneratedModule module = new GeneratedModule(runspace); module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing") { Parameters = new Dictionary <string, ParameterData>() { { "parameter", new ParameterData() { Name = "Parameter", Type = new RuntimeTypeData(typeof(GeneratedModuleTestsObject)) } } } }; string json = "{\"method\":\"Things.Thing_Get\",\"params\":{\"__reserved\":{\"credentials\":[{\"x-ps-credtype\":\"commandBased\",\"tenantId\":\"testTenantId\",\"clientId\":\"testClientId\",\"secret\":\"testSecret\"},{\"x-ps-credtype\":\"parameterBased\",\"tenantId\":\"testTenantId\",\"clientId\":\"testClientId\",\"secret\":\"testSecret\"}]},\"parameter\":{\"string\":\"testValue\",\"number\":500,\"object\":{\"decimal\":1.2,\"boolean\":true}}}}"; LiveTestRequestConverter converter = new LiveTestRequestConverter(module); Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); converter.RegisterSelf(settings); MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory(); credentialsFactory.RegisterProvider("commandbased", new CommandBasedCredentialProvider()); credentialsFactory.RegisterProvider("parameterbased", new ParameterBasedCredentialProvider()); LiveTestRequest request = Newtonsoft.Json.JsonConvert.DeserializeObject <LiveTestRequest>(json, settings); CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory); Assert.Equal("Login-Account [parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}]", (string)runspace.InvokeHistory[0]); Assert.Equal("Login-Account [parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}] [CredentialKey testCredentials]", (string)runspace.InvokeHistory[1]); }
//Load device name: public string getDeviceName() { CommandExecutionResult strOut = s.ExecuteCommand("cat /home/FROST/FROST_DeviceName.conf"); Console.WriteLine(strOut.Output.ToString()); return(strOut.Output.ToString()); }
/// <summary> /// Decrypt a Section in a Configuration File. /// </summary> /// <param name="pathToExe">The path to the exe that owns the configuration file</param> /// <param name="sectionName">The name of the section to decrypt.</param> /// <returns></returns> public CommandExecutionResult DecryptConfigurationSection(string pathToExe, string sectionName) { try { // Open the config and locate the section var config = OpenApplicationConfiguration(pathToExe); var section = GetConfigurationSection(config, sectionName); if (section == null) { return(new CommandExecutionResult(false, "The section '" + sectionName + "' was not found in the configuration.")); } // Already Decrypted if (!section.SectionInformation.IsProtected) { return(CommandExecutionResult.NoOp("Section is already Decrypted.")); } // Decrypt the Section _log.Debug("Decrypting Section"); section.SectionInformation.UnprotectSection(); // Save the Configuration Changes _log.Debug("Saving Configuration"); config.Save(); return(new CommandExecutionResult(true, "Section '" + sectionName + "' Decrypted.")); } catch (Exception ex) { _log.Error(ex); return(new CommandExecutionResult(false, ex.Message)); } }
public void SingleErrorResponse() { MockServiceTracer tracer = new MockServiceTracer(); object errorResult = 5; List <object> errors = new List <object>(); errors.Add(errorResult); CommandExecutionResult result = new CommandExecutionResult(null, errors, true); LiveTestRequest request = new LiveTestRequest(); request.Id = "12345"; request.JsonRpc = "2.0"; LiveTestResponse response = request.MakeResponse(result, tracer, this.logger); Assert.Equal(request.Id, response.Id); Assert.Equal(request.JsonRpc, response.JsonRpc); Assert.NotNull(response.Error); Assert.Equal(-32600, response.Error.Code); // Invalid Request error code defined by LSP Assert.NotNull(response.Error.Data); Assert.Null(response.Error.Data.Headers); Assert.Equal(default(long), response.Error.Data.StatusCode); Assert.NotNull(response.Error.Data.Response); Assert.Equal(errorResult, response.Error.Data.Response); }
private CommandExecutionResult Convert(DocumentView documentView) { var convertEnum = new Func <DocumentViewType, CommandExecutionResultType>(it => { switch (it) { case DocumentViewType.Ok: return(CommandExecutionResultType.Ok); case DocumentViewType.Warning: return(CommandExecutionResultType.Warning); case DocumentViewType.Error: return(CommandExecutionResultType.Error); } throw new ArgumentException($"Unknown DocumentViewType - {it}."); }); var result = new CommandExecutionResult { Content = documentView.Content, Type = convertEnum(documentView.Type) }; return(result); }
public override CommandExecutionResult Execute() { var ctx = new AdministrationDbContext(); var rmsSystem = ctx.GetSystemInstance(); var sysAdmin = rmsSystem.FindIdentity("sys_admin"); if (Password != null) { if (string.IsNullOrWhiteSpace(Password)) { return(CommandExecutionResult.Fail("Password cannot be blank")); } sysAdmin.SetPassword(Password); } if (Enable) { sysAdmin.MakeActive(); } if (Disable) { sysAdmin.MakeActive(false); } ctx.SaveChanges(); return(CommandExecutionResult.Ok()); }
//Load device temperature ranges: public string[] getTemperatureRanges() { CommandExecutionResult strOut = s.ExecuteCommand("cat /home/FROST/FROST_TempRanges.conf"); Console.WriteLine(strOut.Output.ToString()); string[] tempRangeArr = strOut.Output.ToString().Split(':'); return(tempRangeArr); }
public void SendCommandExecutionResult(CommandExecutionResult commandExecutionResult) { try { this.yandexDiskManager.UploadFileWithContent($"{commandExecutionResult.GivenCommandID}.{ConstantValues.FileExtensions.CommandExecutionResult}", commandExecutionResult.Output); } catch (FileAlreadyExistsException) { } }
//Load MySQL server settings: public string[] getMySqlSettings() { CommandExecutionResult strOut = s.ExecuteCommand("cat /home/FROST/FROST_MySQL.conf"); Console.WriteLine(strOut.Output.ToString()); string[] configData = strOut.Output.ToString().Split('\n'); return(configData); }
public LiveTestResponse MakeResponse(CommandExecutionResult commandResult, IServiceTracer tracer, IList<DynamicObjectTransform> transforms, Logger logger) { LiveTestResponse response = MakeBaseResponse(); if (commandResult.HadErrors) { if (logger != null) { logger.LogAsync("Command failed with errors."); commandResult.LogErrors(logger); } response.Error = new LiveTestError(); response.Error.Code = InvalidRequest; List<object> errors = new List<object>(); foreach (object originalError in commandResult.Errors) { errors.AddRange(TransformObject(originalError, transforms)); } response.Error.Data = errors.Count == 0 ? null : errors.Count == 1 ? errors[0] : errors; if (this.HttpResponse) { HttpResponseMessage responseMessage = tracer.HttpResponses.LastOrDefault(); if (responseMessage != null) { // Kill the Content property - doesn't work with Newtonsoft.Json serialization HttpResponseMessage clonedMessage = new HttpResponseMessage(responseMessage.StatusCode); foreach (var header in responseMessage.Headers) { clonedMessage.Headers.Add(header.Key, header.Value); } clonedMessage.ReasonPhrase = responseMessage.ReasonPhrase; clonedMessage.RequestMessage = responseMessage.RequestMessage; clonedMessage.Version = responseMessage.Version; response.Error.HttpResponse = clonedMessage; } } } else { if (logger != null) { logger.LogAsync("Command executed successfully."); } List<object> results = new List<object>(); foreach (object originalResult in commandResult.Results) { results.AddRange(TransformObject(originalResult, transforms)); } response.Result = GetLiveTestResult(results, tracer); } return response; }
//Load device mail list: public List <string> getMailList() { CommandExecutionResult strOut = s.ExecuteCommand("cat /home/FROST/FROST_mailList.conf"); Console.WriteLine(strOut.Output.ToString()); List <string> mailListArr = strOut.Output.ToString().Split(' ').ToList <string>(); return(mailListArr); }
public static void Main(string[] args) { // Process the incoming arguments var commandParser = new CommandArgumentsParserService(); Tuple <string, Dictionary <string, string> > commandArguments; try { commandArguments = commandParser.ParseCommandWithArguments(args); } catch (FormatException ex) { Log.Error(ex.Message); Environment.ExitCode = ExitCodeInvalidCommandFormat; return; } if (commandArguments == null) { Log.Info(@"No command specified. " + Environment.NewLine); PrintAvailableCommands(); Environment.ExitCode = ExitCodeOk; return; } // Locate the specified Command var command = CommandInstanceFactory.CreateCommandInstance(commandArguments.Item1, commandArguments.Item2); if (command == null) { Log.Info(@"Command not found."); Environment.ExitCode = ExitCodeCommandNotFound; return; } // Execute the command only if it is ready if (command.Ready()) { CommandExecutionResult result; try { result = command.Execute(); } catch (Exception ex) { result = CommandExecutionResult.Exception(ex); } Log.Info(result.Message); Environment.ExitCode = result.Success ? ExitCodeOk : ExitCodeCommandExecutionFailed; return; } Log.Info(@"Command was not ready to execute. Check your parameters and try again."); Log.Info(command.GetType().GetCustomAttribute <CommandAttribute>().GetCommandInfo()); Environment.ExitCode = ExitCodeCommandNotReady; }
public void ProcessOperationWithCredentials() { MockRunspaceManager runspace = new MockRunspaceManager(); GeneratedModule module = new GeneratedModule(runspace); module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing"); MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory(); credentialsFactory.RegisterProvider("commandbased", new CommandBasedCredentialProvider()); credentialsFactory.RegisterProvider("parameterbased", new ParameterBasedCredentialProvider()); LiveTestRequest request = new LiveTestRequest(); request.Method = "Things.Thing_Get"; request.OperationId = "Thing_Get"; request.Params = new Dictionary <string, object>() { { "__reserved", new Dictionary <string, object>() { { "credentials", new LiveTestCredentials[] { new LiveTestCredentials() { Type = "commandBased", Properties = new Dictionary <string, object>() { { "tenantId", "testTenantId" }, { "clientId", "testClientId" }, { "secret", "testSecret" } } }, new LiveTestCredentials() { Type = "parameterBased", Properties = new Dictionary <string, object>() { { "tenantId", "testTenantId" }, { "clientId", "testClientId" }, { "secret", "testSecret" } } } } } } } }; request.Params["parameter"] = new GeneratedModuleTestsObject() { String = "testValue", Number = 500, Object = new GeneratedModuleTestsSubObject() { Decimal = 1.2, Boolean = true } }; CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory); Assert.Equal(2, runspace.InvokeHistory.Count); Assert.Equal("Login-Account", (string)runspace.InvokeHistory[0]); Assert.Equal("Login-Account [CredentialKey testCredentials]", (string)runspace.InvokeHistory[1]); }
/// <summary> /// Initializes a new instance of the <see cref="CommandActionExecutionResult" /> class. /// </summary> /// <param name="result">result (required).</param> /// <param name="deviceId">Device ID for device actions (required).</param> public CommandActionExecutionResult(CommandExecutionResult result = default(CommandExecutionResult), string deviceId = default(string)) { this.Result = result; // to ensure "deviceId" is required (not null) if (deviceId == null) { throw new ArgumentNullException("deviceId is a required property for CommandActionExecutionResult and cannot be null"); } this.DeviceId = deviceId; }
protected CommandExecutionResult Ok(DomainOperationResult data) { var result = new CommandExecutionResult { Data = data, Success = true }; return(result); }
protected IActionResult CommandResultToHttpResponse(CommandExecutionResult result, EntityStatusCode entityStatusCode) { if (result.Success) { return(entityStatusCode switch { EntityStatusCode.Created => Created("", result.Data), EntityStatusCode.Updated => Ok(result.Data), EntityStatusCode.Deleted => NoContent(), _ => BadRequest(), });
public void RunCommandWithExpectedErrorAsErrorRecord() { PowerShellRunspace psRunspace = new PowerShellRunspace(this.logger); ICommandBuilder psCommand = psRunspace.CreateCommand(); psCommand.Command = "Get-Process"; psCommand.AddParameter("Name", "123456789"); CommandExecutionResult results = psCommand.Invoke(); Assert.True(results.HadErrors); Assert.Equal(1, results.Errors.Count()); }