/// <summary> /// Turn off the wireless LAN /// </summary> /// <param name="callback">Action<Error></param> public void FinishWlan(Action<Error> callback) { CommandRequest request = new CommandRequest("camera._finishWlan"); request.AddParameter("sessionId", currentSessionId); CommandExecute(request, (response) => { callback(response.error); }); }
/// <summary> /// Returns a full-size or scaled image given its URI. Input parameters include resolution. This is the only command that should return /// </summary> /// <param name="fileUri">URI of the target file. Manufacturers decide whether to use absolute or relative URIs. Clients may treat this as an opaque identifier.</param> /// <param name="type">enum DataType { full, thumb }</param> /// <param name="callback">Action<byte[], Error></param> public void GetImage(string fileUri, DataType type, Action<byte[], Error> callback) { CommandRequest request = new CommandRequest("camera.getImage"); request.AddParameter("fileUri", fileUri); request.AddParameter("_type", type.ToString()); CommandExecute(request, (response) => { callback(response.bytes, response.error); }); }
public ICommandResponse SetupGitRepos (InitialGitStatus status) { var argument = string.Empty; switch (status) { case InitialGitStatus.BareAheadOfHome: argument = " bare"; break; case InitialGitStatus.HomeAheadOfBare: argument = " home"; break; default: break; } var script = TestConstants.ScriptDirName + TestConstants.CreateRepoScript + argument; ICommandRequest request = new CommandRequest (); request.WorkingDirectory = TestConstants.ScriptDirPath; request.Name = "bash"; request.Arguments = script; var service = new CommandService (new BashGitCommandOutputStrategy ()); var result = service.Execute (request); return result; }
public override async Task <Reply> Execute(Request request, ServerCallContext callContext) { // TODO: read-only stream wrap over a span // TODO: unsafe byte string // TODO: error handling? // TODO: operation context via HTTP headers // TODO: resource handling here. Guid operationId = _context.TracingContext.Id; foreach (var header in callContext.RequestHeaders) { if (header.Key.Equals("X-Cache-Operation-Id", StringComparison.OrdinalIgnoreCase)) { Guid.TryParse(header.Value, out operationId); break; } } var tracingContext = new Context(operationId, _context.TracingContext.Logger); var operationContext = new OperationContext(tracingContext, token: callContext.CancellationToken); return(await operationContext.PerformNonResultOperationAsync(Tracer, async() => { var commandRequest = _serializationPool.Deserialize(request.Request_.ToByteArray(), reader => CommandRequest.Deserialize(reader)); try { var commandResponse = await _service.HandleAsync(commandRequest); var serialized = _serializationPool.Serialize(commandResponse, (value, writer) => value.Serialize(writer)); return new Reply() { Reply_ = Google.Protobuf.ByteString.CopyFrom(serialized), }; } catch (Exception e) { // TODO: do this properly. throw new RpcException(new Status(StatusCode.Internal, detail: e.ToString()), message: "Internal server error"); } }, traceErrorsOnly : true)); }
/// <summary> /// Start the interval still image capturing or video recording. /// Capture mode is selected by captureMode of Option. /// </summary> /// <param name="callback">Action<Error></param> public void StartCapture(Action<Error> callback) { CommandRequest request = new CommandRequest("camera._startCapture"); request.AddParameter("sessionId", currentSessionId); CommandExecute(request, (response) => { callback(response.error); }); }
protected override bool _Execute(CommandRequest e) { string[] args = e.ArgumentList; ServerResponse response = ResponseHandler.NewOutputResponse; try { // 0 if (args.Length <= 0) { List<Issue> l = GetIssueList(); foreach (Issue o in l) { if (o.State == Issue.IssueState.NEW || o.State == Issue.IssueState.WORK) response.AddData(CreateHtmlEntry(o)); } } // 3 //PRIORITY else if (check(args, 3, "prio", "priority", "-p")) { Issue o = GetObject(Int32.Parse(args[1])); if (o != null) { o.Priority = Issue.GetPriority(args[2].ToLower().Trim()); response.AddData(HTML.CreateCssClassOutputLine("blue-light", "Changed: ")); response.AddData(CreateHtmlEntry(UpdateObject(o))); } else response.AddData(CmdMessage.Get(CmdMessage.Type.Error, HTML.Encode("Error: ID Not found!"))); } // 2 //ADD else if (check(args, 2, "add", "report")) { List<Issue> l = GetIssueList(); string desc = Regex.Replace(e.ArgumentString.Substring(args[0].Length), "\\s+", " ").Trim(); string highlight = ""; Issue.IssueType type = Issue.IssueType.TODO; //prio Issue.IssuePriority prio = Issue.GetPriority(desc.ToLower().Trim().Substring(0, 1)); if (prio != Issue.IssuePriority.NORMAL) desc = desc.Trim().Substring(1).Trim(); //heightlight (e.g. "[JS] ...") if (desc.ToLower().StartsWith("[") && desc.ToLower().Contains("]")) { highlight = desc.Substring(0, desc.IndexOf("]") + 1).Trim(); desc = desc.Substring(highlight.Length).Trim(); } //bug string b = e.Command.ToLower(); if (b.Contains("bug")) type = Issue.IssueType.BUG; if (desc.ToLower().StartsWith("bug:")) { type = Issue.IssueType.BUG; desc = desc.Substring(4).Trim(); } //add if (desc.ToLower().StartsWith("add:")) { type = Issue.IssueType.ADD; desc = desc.Substring(4).Trim(); } Issue o = new Issue(type, String.Concat(highlight, " ", desc)); o.ID = l[l.Count - 1].ID + 1; o.State = Issue.IssueState.NEW; o.Priority = prio; l.Add(o); SaveIssueList(l); response.AddData(HTML.CreateCssClassOutputLine("green", "Added: ")); response.AddData(CreateHtmlEntry(o)); } //REMOVE else if (check(args, 2, "remove", "-rm")) { List<Issue> l = GetIssueList(); int n = Int32.Parse(args[1]); bool match = false; foreach (Issue o in l) { if (o.ID == n) { match = true; l.Remove(o); response.AddData(HTML.CreateCssClassOutputLine("red", "Removed: ")); response.AddData(CreateHtmlEntry(o)); break; } } if (match) SaveIssueList(l); else response.AddData(CmdMessage.Get(CmdMessage.Type.Error, HTML.Encode("Error: ID Not found!"))); } //FIXED else if (check(args, 2, "fixed", "-f", "done")) { Issue o = GetObject(Int32.Parse(args[1])); if (o != null) { o.State = Issue.IssueState.DONE; if (o.Type == Issue.IssueType.BUG) o.State = Issue.IssueState.FIXED; response.AddData(HTML.CreateCssClassOutputLine("blue-light", "Changed: ")); response.AddData(CreateHtmlEntry(UpdateObject(o))); } else response.AddData(CmdMessage.Get(CmdMessage.Type.Error, HTML.Encode("Error: ID Not found!"))); } //INVALID else if (check(args, 2, "invalid", "-i")) { Issue o = GetObject(Int32.Parse(args[1])); if (o != null) { o.State = Issue.IssueState.INVALID; response.AddData(HTML.CreateCssClassOutputLine("blue-light", "Changed: ")); response.AddData(CreateHtmlEntry(UpdateObject(o))); } else response.AddData(CmdMessage.Get(CmdMessage.Type.Error, HTML.Encode("Error: ID Not found!"))); } //NEW else if (check(args, 2, "new", "-n")) { Issue o = GetObject(Int32.Parse(args[1])); if (o != null) { o.State = Issue.IssueState.NEW; response.AddData(HTML.CreateCssClassOutputLine("blue-light", "Changed: ")); response.AddData(CreateHtmlEntry(UpdateObject(o))); } else response.AddData(CmdMessage.Get(CmdMessage.Type.Error, HTML.Encode("Error: ID Not found!"))); } //IN PROGRESS else if (check(args, 2, "work", "assign", "-w", "-as")) { Issue o = GetObject(Int32.Parse(args[1])); if (o != null) { o.State = Issue.IssueState.WORK; response.AddData(HTML.CreateCssClassOutputLine("blue-light", "Changed: ")); response.AddData(CreateHtmlEntry(UpdateObject(o))); } else response.AddData(CmdMessage.Get(CmdMessage.Type.Error, HTML.Encode("Error: ID Not found!"))); } // 1 //LIST else if (check(args, 1, "list")) { List<Issue> l = GetIssueList(); List<Issue.IssueState> filters = new List<Issue.IssueState>(); if (args.Length >= 2) { for (int i = 1; i < args.Length; i++) { try { filters.Add((Issue.IssueState)Enum.Parse(typeof(Issue.IssueState), args[i], true)); } catch { filters.Clear(); } } } foreach (Issue o in l) { if (filters.Count <= 0) response.AddData(CreateHtmlEntry(o)); foreach (Issue.IssueState filter in filters) { if (o.State == filter) response.AddData(CreateHtmlEntry(o)); } } } else { PrintUsage(response); } } catch(Exception ex2) { PrintUsage(response); response.AddData("ERROR: ", ex2.ToString()); } e.Source.Response.Send(response); return true; }
public static async Task OnCreateLeagueCommandHandlerOrchestrator ([OrchestrationTrigger] DurableOrchestrationContext context, Microsoft.Extensions.Logging.ILogger log) { CommandRequest <Create_New_League_Definition> cmdRequest = context.GetInput <CommandRequest <Create_New_League_Definition> >(); if (null != cmdRequest) { ActivityResponse resp = await context.CallActivityAsync <ActivityResponse>("CreateLeagueCommandLogParametersActivity", cmdRequest); #region Logging if (null != log) { if (null != resp) { log.LogInformation($"{resp.FunctionName} complete: {resp.Message } "); } } #endregion if (null != resp) { context.SetCustomStatus(resp); } if (!resp.FatalError) { // validate the command bool valid = await context.CallActivityAsync <bool>("CreateLeagueCommandValidationAction", cmdRequest); if (!valid) { resp.Message = $"Validation failed for command {cmdRequest.CommandName} id: {cmdRequest.CommandUniqueIdentifier }"; resp.FatalError = true; } } if (!resp.FatalError) { // execute the command resp = await context.CallActivityAsync <ActivityResponse>("CreateLeagueCommandHandlerAction", cmdRequest); #region Logging if (null != log) { if (null != resp) { log.LogInformation($"{resp.FunctionName} complete: {resp.Message } "); } } #endregion if (null != resp) { context.SetCustomStatus(resp); } } } else { #region Logging if (null != log) { // Unable to get the request details from the orchestration log.LogError("OnCreateLeagueCommandHandlerOrchestrator : Unable to get the command request from the context"); string contextAsString = context.GetInput <string>(); if (!string.IsNullOrWhiteSpace(contextAsString)) { log.LogError($"Context was {contextAsString} "); } else { log.LogError($"Context was blank "); } } #endregion return; } }
private void Mngr_RecievedCommand(ClientManager client, CommandRequest request) { request.Client = client.Client_ID; client.SendMessage(CommandGenerator(request)); }
/// <inheritdoc/> public CommandResult Handle(CommandRequest command) { return(Handle(_commandContextManager.EstablishForCommand(command), command)); }
public async Task List(CommandRequest request) { OutputMode outputMode = CommandParser.ParseOutputMode(request.GetArg(2, "text")); await request.Write(generatePlaneList(server.PlaneManager.Planes, outputMode)); }
//In Datagrid tabs the tab title looks like this : Cars.sav(DatasetN), where N is any integer. //So here DatasetN is the object in memory that is dataframe( or similar). //Cars.sav is just extra info about the Dataset you tried to open. This extra info could be a disk filename // or it could also be just a memory object name if memory object name is different from 'DatasetN' style of naming // eg.. mydf(mydf) , Dataset1(Dataset1), Cars.sav(Dataset2), mydata.rdata(Dataset3) // in above example mydf, Dataset1 Dataset2, Dataset3 , all R objects exists in R memory. //Wrong way of naming would look something like this : mydf(Dataset1) // mydf is not a disk file, so lets assume it may be R dataframe obj in memory, but then we always put memory object // name within round brackets, so, if (Dataset1) is a memory object, the extra info 'mydf' does not make sense. //So 'mydf' should be named as 'Dataset1' instead. //Right thing would be either one of two mydf(mydf) or Dataset1(Dataset1) for non-disk datasets public DataSource OpenDataframe(string dframename, string sheetname, string fname = "") //13Feb2014 { UAReturn datasrc = null; DataSource ds = null; if (!isDatasetNew(dframename /*+ sheetname*/)) // if data.frame with same name already loaded in C1DataGrid { string filename = _datasourcenames[dframename /*+ sheetname*/]; ////////// datasrc = new UAReturn(); ////////// datasrc = _analyticService.DataFrameLoad(filename, dframename, sheetname); ////////// ////////////// ////////// if (datasrc == null) ////////// { ////////// logService.WriteToLogLevel("Could not open: " + filename, LogLevelEnum.Error); ////////// return null; ////////// } ////////// else if (datasrc != null && datasrc.Datasource == null) ////////// { ////////// if (datasrc.Error != null && datasrc.Error.Length > 0) ////////// { ////////// logService.WriteToLogLevel("Could not refresh/open: " + filename + ".\n" + datasrc.Error, LogLevelEnum.Error); ////////// } ////////// else ////////// logService.WriteToLogLevel("Could not refresh/open: " + dframename + ".\nInvalid format OR issue related to R.Net server.", LogLevelEnum.Error); ////////// DataSource dsnull = new DataSource() { Message = datasrc.Error }; ////////// return dsnull; ////////// } ////////// datasrc.CommandString = "Refresh Dataframe"; try { if (_datasources.Keys.Contains(filename + sheetname)) { ds = _datasources[filename + sheetname]; } else //no need to check if it exists as we alreay checked if its new dataset or not in code above { ds = _datasources[_datasourcenames[dframename /*+ sheetname*/].Trim() + sheetname]; } //So by now we know we know that Dataset name is same. //And new one already overwrote old data.frame in memory. //Now we need to figure out if the disk filename is same or not //if same no issue. If different then we need to replace old with new filename #region Overwrite with new filename if Filename is different from old one //if ( !filename.ToLower().Equals(fname)) //fname.Length > 0 && filename.Length > 0 && //{ // //remove old keys in _datasources _datasourcenames // if (_datasources.Keys.Contains(filename + sheetname)) //Check if dataset is already loaded in the grid // { // _datasources.Remove(filename + sheetname);//Remove old // //_datasources.Add(dsourceName.FileName + sheetname, dsourceName);///Replace ds with new one // //5Mar2014 No need to do following but we can still do it // _datasourcenames.Remove(dframename /*+ sheetname*/); // //_datasourcenames.Add(dsourceName.Name + sheetname, dsourceName.FileName); // } //} //update ds. if new filename then overwrite old. if blank then use DatasetNN for filename if (fname.Trim().Length > 0) { ds.FileName = fname; } else { // ds.FileName = dframename; ds.SheetName = ""; } #endregion } catch (Exception ex) { logService.WriteToLogLevel("Error getting existing DataSource handle", LogLevelEnum.Fatal); } string existingDatasetname = ds.Name; //20Oct2016 save a copy for using in 'if' below DataSource ds_for_cleanup = ds; ds = Refresh(ds); //THIS COULD BE THE LINE THATs CAUSING REFRESHDATASET PERFORMANCE ISSUE if (ds == null) //20Oct2016 Making UI grid NULL { ds = new DataSource(); ds.Variables = new List <DataSourceVariable>();//making it blank ds.FileName = ds_for_cleanup.FileName; ds.Name = ds_for_cleanup.Name; ds.SheetName = ""; ds.DecimalCharacter = ds_for_cleanup.DecimalCharacter; ds.FieldSeparator = ds_for_cleanup.FieldSeparator; ds.HasHeader = ds_for_cleanup.HasHeader; ds.IsBasketData = ds_for_cleanup.IsBasketData; UIController = LifetimeService.Instance.Container.Resolve <IUIController>(); UIController.RefreshBothGrids(ds); //here I can also close before or after above line(whereever works) //Close(ds_for_cleanup); //Generating the message for null dataset CommandRequest msg = new CommandRequest(); msg.CommandSyntax = ds_for_cleanup.Name + " been set to NULL. The reason may be, running some analysis or command on the dataset."; //string title = "NULL Dataset."; //if (msg != null && title != null)//16May2013 // SendToOutputWindow(title, msg.CommandSyntax); logService.WriteToLogLevel(msg.CommandSyntax, LogLevelEnum.Error); } } else // Its New Data.Frame . { string datasetname = "Dataset" + SessionDatasetCounter;//dframename;// //(_datasources.Keys.Count + 1);//can also be filename without path and extention //15Jun2015 dframename exists in memory so use that name for datagrid tab name enclosed in round brackets (Dataset1) or (df1) if (!dframename.Equals(datasetname)) //df2 and Dataset2 { datasetname = dframename; //use df2 for both because df2 exists in R memory //no need to increament the SessionDatasetCounter as when you try to open a disk file it will have (Dataset2) // as name and it will not clash with the (df2) name. //incrementing may not harm but there is no need to increment. //ELSE dframename.Equals(datasetname) like both are say "Dataset2" // use (Dataset2) for both because Dataset2 exists in memory //Also increament the SessionDatasetCounter in this case because now later //when you open Dataset from disk is should have name Dataset3 and not Dataset2 } if (fname.ToLower().EndsWith(".rdata")) { dframename = fname; //pass RData filename } datasrc = _analyticService.DataFrameLoad(dframename, datasetname, ""); if (datasrc == null) { logService.WriteToLogLevel("Could not open: " + dframename, LogLevelEnum.Error); return(null); } else if (datasrc != null && datasrc.Datasource == null) { if (datasrc.Error != null && datasrc.Error.Length > 0) { logService.WriteToLogLevel("Could not open: " + dframename + ".\n" + datasrc.Error, LogLevelEnum.Error); } else { logService.WriteToLogLevel("Could not open: " + dframename + ".\nInvalid format OR issue related to R.Net server.", LogLevelEnum.Error); } DataSource dsnull = new DataSource() { Message = datasrc.Error }; return(dsnull); } datasrc.CommandString = "Open Dataset";//21Oct2013 ds = datasrc.Datasource.ToClientDataSource(); if (ds != null)//03Dec2012 { //_datasources.Add(ds.FileName, ds);///key filename _datasources.Add(ds.FileName + ds.SheetName, ds); ///key filename _datasourcenames.Add(datasetname /*+ ds.SheetName*/, ds.FileName); //5Mar2014 } ///incrementing dataset counter //// 15Jun2015 /// if the name of the Dataset created in syntax matches to the Dataset name generated for UI grid. if (dframename.Equals(datasetname)) { SessionDatasetCounter++; } } if (fname.Length == 0) { ds.Extension = ""; ds.FileName = ""; } //04Nov2014. Dont show "Open Dataset" before subset command title. SendToOutput(datasrc); return(ds); }
public bool HandleLocal(CommandRequest request) { // Return true here. MasterService will send the receipt message return(true); }
public async Task Grant(CommandRequest request) { if (request.Arguments.Length < 5) { await request.WriteLine("Error: No username specified!"); return; } if (request.Arguments.Length < 4) { await request.WriteLine("Error: No plane name specified!"); return; } if (request.Arguments.Length < 3) { await request.WriteLine("Error: No role specified!"); return; } string grantRoleName = request.Arguments[2]; string grantPlaneName = request.Arguments[3]; string grantUsername = request.Arguments[4]; if (grantRoleName.ToLower() != "creator" && grantRoleName.ToLower() != "member") { await request.WriteLine($"Error: Invalid role {grantRoleName}. Valid values: Creator, Member. Is not case-sensitive."); return; } Plane grantPlane = server.PlaneManager.GetByName(grantPlaneName); if (grantPlane == null) { await request.WriteLine($"Error: The plane with the name {grantPlaneName} could not be found."); return; } if (server.AccountManager.GetByName(grantUsername) == null) { await request.WriteLine($"Error: No user could be found with the name {grantUsername}."); return; } switch (grantRoleName.ToLower()) { case "creator": if (grantPlane.Creators.Contains(grantUsername)) { await request.WriteLine($"Error: {grantUsername} is already a creator on {grantPlaneName}."); return; } grantPlane.Creators.Add(grantUsername); break; case "member": if (grantPlane.Members.Contains(grantUsername)) { await request.WriteLine($"Error: {grantUsername} is already a member on {grantPlaneName}."); return; } grantPlane.Members.Add(grantUsername); break; } await request.WriteLine($"Ok: {grantUsername} has been granted {grantRoleName} on {grantPlaneName} successfully."); await request.Write("Saving - "); DateTime grantTimeStart = DateTime.Now; await grantPlane.Save(PlaneSavingMode.MetadataOnly); await request.WriteLine($"done in {(DateTime.Now - grantTimeStart).Milliseconds}ms."); }
public async Task Revoke(CommandRequest request) { if (request.Arguments.Length < 5) { await request.WriteLine("Error: No username specified!"); return; } if (request.Arguments.Length < 4) { await request.WriteLine("Error: No plane name specified!"); return; } if (request.Arguments.Length < 3) { await request.WriteLine("Error: No role specified!"); return; } string roleName = request.Arguments[2]; string planeName = request.Arguments[3]; string username = request.Arguments[4]; if (roleName.ToLower() != "creator" && roleName.ToLower() != "member") { await request.WriteLine($"Error: Invalid role {roleName}. Valid values: Creator, Member. Is not case-sensitive."); return; } Plane targetPlane = server.PlaneManager.GetByName(planeName); if (targetPlane == null) { await request.WriteLine($"Error: The plane with the name {planeName} could not be found."); return; } if (server.AccountManager.GetByName(username) == null) { await request.WriteLine($"Error: No user could be found with the name {username}."); return; } switch (roleName.ToLower()) { case "creator": targetPlane.Creators.Remove(username); break; case "member": targetPlane.Members.Remove(username); break; } await request.WriteLine($"Ok: {username} has been revoked {roleName} on {planeName} successfully."); await request.Write("Saving - "); DateTime timeStart = DateTime.Now; await targetPlane.Save(PlaneSavingMode.MetadataOnly); await request.WriteLine($"done in {(DateTime.Now - timeStart).Milliseconds}ms."); }
public async Task <CommandResponse> ForwardRequest(CommandRequest request) { //var internalTraceId = Guid.NewGuid(); var handler = _httpRequestHelper.GetClientHandler(request); var response = new CommandResponse(); using (var client = new HttpClient(handler)) { var httpRequest = _httpRequestHelper.GetRequestMessage(request); //string responseMessage = null; //LogRequest(httpRequest, request.Resource, internalTraceId); using (HttpResponseMessage res = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead)) using (HttpContent content = res.Content) { try { //TODO: upgrade to core 2.2 and use IHttpClientFactory for delegate handling var data = content.ReadAsByteArrayAsync().Result; //responseMessage = Encoding.UTF8.GetString(data, 0, data.Length); if (res.Headers.TransferEncodingChunked == true && res.Headers.TransferEncoding.Count == 1) { res.Headers.TransferEncoding.Clear(); } foreach (var resHeader in res.Headers) { response.Headers.Add(resHeader.Key, resHeader.Value); } var contentLength = content.Headers.ContentLength; foreach (var resHeader in content.Headers) { response.Headers.Add(resHeader.Key, resHeader.Value); } response.Content = data; response.StatusCode = (int)res.StatusCode; } catch (Exception e) { throw new HttpRequestException($"Parsing response from {request.ForwardUrl} failed."); } finally { //LogResponse(res.Headers, (int)res.StatusCode, responseMessage, internalTraceId); } } } return(await Task.Run(() => response)); }
static bool IsInContext(CommandRequest command) => _currentContext.Value?.Command.Equals(command) == true;
CommandResult Handle(ITransaction transaction, CommandRequest command) { var commandResult = new CommandResult(); try { using (_localizer.BeginScope()) { _logger.Information($"Handle command of type {command.Type}"); commandResult = CommandResult.ForCommand(command); _logger.Trace("Authorize"); var authorizationResult = _commandSecurityManager.Authorize(command); if (!authorizationResult.IsAuthorized) { _logger.Trace("Command not authorized"); commandResult.SecurityMessages = authorizationResult.BuildFailedAuthorizationMessages(); transaction.Rollback(); return(commandResult); } _logger.Trace("Validate"); var validationResult = _commandValidationService.Validate(command); commandResult.ValidationResults = validationResult.ValidationResults; commandResult.CommandValidationMessages = validationResult.CommandErrorMessages; if (commandResult.Success) { _logger.Trace("Command is considered valid"); try { _logger.Trace("Handle the command"); _commandHandlerManager.Handle(command); _logger.Trace("Commit transaction"); transaction.Commit(); } catch (TargetInvocationException ex) { _logger.Error(ex, "Error handling command"); commandResult.Exception = ex.InnerException; transaction.Rollback(); } catch (Exception ex) { _logger.Error(ex, "Error handling command"); commandResult.Exception = ex; transaction.Rollback(); } } else { _logger.Information("Command was not successful, rolling back"); transaction.Rollback(); } } } catch (TargetInvocationException ex) { _logger.Error(ex, "Error handling command"); commandResult.Exception = ex.InnerException; } catch (Exception ex) { _logger.Error(ex, "Error handling command"); commandResult.Exception = ex; } return(commandResult); }
private CommandResult CommandGenerator(CommandRequest request) { //Builds the command result Object CommandResult ret = new CommandResult { User = request.Client }; //Logs the user and the command lstCommands.Items.Add($"{request.Client}::{request.Message}"); //Cleans the command from the message string command = request.Message.Split(' ')[0]; command = command.Trim('!'); //All commands exist within this switch (Scary i know) switch (command.ToLower()) { //Needs to be manually updated case "help": string[] commands = new string[] { "Help; displays this", "list; returns a list of files on the server", "clear; Clears the chat boxes", "get <FileName>; pulls a specific file", "download <FileName>; Downloads a file from a get", "ping; pings the server", "users; gets a list of active users" }; ret.Contents = commands; break; case "list": List <string> files = new List <string>(); foreach (FileStandard a in lstFiles.Items) { files.Add(a.Name); } ret.Contents = files.ToArray(); break; case "get": //This solves a bug when it comes to files with a space in the name string File_Name = null; for (int i = 1; i < request.Message.Split(' ').Length; i++) { File_Name += request.Message.Split(' ')[i] + " "; } File_Name = File_Name.TrimEnd(); for (int i = 0; i < lstFiles.Items.Count; i++) { if (((FileStandard)lstFiles.Items[i]).Name == File_Name) { ret.Contents = lstFiles.Items[i]; break; } } break; //Returns a list of the current users case "users": List <string> Usernames = new List <string>(); //Loops through all users and adds them to the Usernames for (int i = 0; i < Client_List.Count; i++) { // if (Client_List[i].Client_ID != (int)request.Client) { if (Client_List[i].Client_Name == null || string.IsNullOrWhiteSpace(Client_List[i].Client_Name)) { Usernames.Add($"User ID: {Client_List[i].Client_ID}"); } else { Usernames.Add(Client_List[i].Client_Name); } } } ret.Contents = Usernames.ToArray(); break; case "ping": TimeSpan Pong = DateTime.Now - request.RequestTime; ret.Contents = Pong; break; //Runs if no command was found default: ret.Contents = "Command Does not exist!"; break; } //if nothing is found within the command this will be added if (ret.Contents == null) { ret.Contents = "Nothing was found!"; } return(ret); }
public CommandValidationResult Validate(CommandRequest command) { validate_called = true; command_passed_to_validate = command; return(result_to_return); }
public void Handle(CommandRequest request) { Logger.LogInfo("Handled CommandRequest"); }
protected override bool _Execute(CommandRequest e) { Client c = e.Source; c.Response.Send("MEOW ;3"); return true; }
/// <summary> /// Executes a command against the database using the provided information /// </summary> public static CommandResponse RunCommand(MongoDatabase database, BsonObject parameters, bool expectResponse) { //create the command to use CommandRequest request = new CommandRequest(database); request.Arguments.Merge(parameters); //send the command and check for the result CommandResponse response = database.SendRequest(request) as CommandResponse; if (response == null && expectResponse) { throw new MongoServerException( string.Format( "The request to {0} expected a response but nothing was returned!", database.Connection.Host )); } //return any documents that were found return response; }
public async SystemTasks.Task <FhirResponse> RequestOne(CommandRequest request) { var fhirResponse = await Request(request); return(fhirResponse); }
/// <summary> /// List all images /// </summary> /// <param name="entryCount">The list of entrys that vender specific of theta.</param> /// <param name="continuationToken"> (Optional) An opaque continuation token of type string, returned by previous listImages call, used to retrieve next images. </param> /// <param name="detail"></param> /// <param name="sort">sort string should be "newest" or "oldest"</param> /// <param name="callback">delegate void OnCompleteListAll(List<ThetaEntry> entries, int totalEntries, string continuationToken, Error error)</param> public void ListAll(int entryCount, string continuationToken, bool detail, string sort, OnCompleteListAll callback) { CommandRequest request = new CommandRequest("camera._listAll"); request.AddParameter("entryCount", entryCount); if(!string.IsNullOrEmpty(continuationToken)) request.AddParameter("continuationToken", continuationToken); if(!detail) request.AddParameter("detail", detail); if (sort == "oldest") request.AddParameter("sort", sort); CommandExecute(request, (response) => { if (response.error != null) { callback(new List<ThetaEntry>(), 0, "", response.error); } else { try { var entries = new List<ThetaEntry>(); if (response.results.Contains("entries")) { var list = (IList)response.results["entries"]; foreach (IDictionary dict in list) { var entry = new ThetaEntry(); JSONUtil.DictionaryToObjectFiled(dict, entry); entries.Add(entry); } } int _totalEntries = (response.results.Contains("totalEntries")) ? (int)((long)response.results["totalEntries"]) : 0; string _continuationToken = (response.results.Contains("continuationToken")) ? (string)response.results["continuationToken"] : null; callback(entries, _totalEntries, _continuationToken, null); } catch (System.Exception ex) { Error error = new Error(); error.message = ex.Message; callback(new List<ThetaEntry>(), 0, null, response.error); } } }); }
public async SystemTasks.Task <List <T> > RequestMany <T>(CommandRequest request) where T : Resource { var fhirResponse = await Request(request); return(fhirResponse.GetResources <T>()); }
public static async Task SetLeagueEmailAddressCommandHandlerOrchestrator( [OrchestrationTrigger] DurableOrchestrationContext context, ILogger log) { CommandRequest <Set_Email_Address_Definition> cmdRequest = context.GetInput <CommandRequest <Set_Email_Address_Definition> >(); if (null != cmdRequest) { ActivityResponse resp = await context.CallActivityWithRetryAsync <ActivityResponse>("SetLeagueEmailAddressCommandLogParametersActivity", DomainSettings.CommandRetryOptions(), cmdRequest); #region Logging if (null != log) { if (null != resp) { log.LogInformation($"{resp.FunctionName} complete: {resp.Message } "); } } #endregion if (null != resp) { context.SetCustomStatus(resp); } // Get the impacted entities from the command request - in this command they are passed as parameters IEnumerable <CommandNotificationImpactedEntity> impactedEntities = null; Set_Email_Address_Definition parameters = cmdRequest.GetParameters(); if (null != parameters) { Tuple <string, string>[] entitiesImpacted = new Tuple <string, string>[] { new Tuple <string, string>(@"League", parameters.LeagueName) }; impactedEntities = CommandNotificationImpactedEntity.CreateImpactedEntityList(entitiesImpacted); } if (!resp.FatalError) { // 1) Validate the command bool valid = await context.CallActivityWithRetryAsync <bool>("SetLeagueEmailAddressCommandValidationActivity", DomainSettings.CommandRetryOptions(), cmdRequest); CommandStepResponse stepValidateResponse = new CommandStepResponse() { CommandName = cmdRequest.CommandName, CommandUniqueIdentifier = cmdRequest.CommandUniqueIdentifier, StepName = "Set League Email Address Command Validation", Message = resp.Message, ImpactedEntities = impactedEntities }; resp = await context.CallActivityAsync <ActivityResponse>("CommandStepCompleteActivity", stepValidateResponse); if (valid) { // 2) Perform the operation of the command resp = await context.CallActivityWithRetryAsync <ActivityResponse>("SetLeagueEmailAddressCommandHandlerActivity", DomainSettings.CommandRetryOptions(), cmdRequest); #region Logging if (null != log) { if (null != resp) { log.LogInformation($"{resp.FunctionName} complete: {resp.Message } "); } } #endregion if (null != resp) { context.SetCustomStatus(resp); } // Mark the step as complete if (!resp.FatalError) { CommandStepResponse stepCommandResponse = new CommandStepResponse() { CommandName = cmdRequest.CommandName, CommandUniqueIdentifier = cmdRequest.CommandUniqueIdentifier, StepName = resp.FunctionName, Message = resp.Message, ImpactedEntities = impactedEntities }; resp = await context.CallActivityAsync <ActivityResponse>("CommandStepCompleteActivity", stepCommandResponse); } // Mark the command as complete if (!resp.FatalError) { resp = await context.CallActivityAsync <ActivityResponse>("CommandCompleteActivity", cmdRequest); } #region Logging if (null != log) { if (null != resp) { log.LogInformation($"{resp.FunctionName} complete: {resp.Message } "); } } #endregion if (null != resp) { context.SetCustomStatus(resp); } // Fire the orchestration to do the actual work of sending notifications Command_Get_Notifications_Request payload = new Command_Get_Notifications_Request() { CommandName = cmdRequest.CommandName, CommandUniqueIdentifier = cmdRequest.CommandUniqueIdentifier.ToString() }; // call the orchestrator... resp = await context.CallSubOrchestratorAsync <ActivityResponse>("CommandNotificationOrchestrator", payload); #region Logging if (null != log) { if (null != resp) { log.LogInformation($"{resp.FunctionName} complete: {resp.Message } "); } } #endregion if (null != resp) { context.SetCustomStatus(resp); } } else { #region Logging if (null != log) { log.LogWarning($"Command parameters not valid {cmdRequest.CommandName} : {cmdRequest.CommandUniqueIdentifier } "); } #endregion if (null != resp) { resp.Message = $"Command parameters not valid {cmdRequest.CommandName} : {cmdRequest.CommandUniqueIdentifier } "; context.SetCustomStatus(resp); } } } } }
public static async Task OnSetLeagueEmailAddressCommandHandler( [EventGridTrigger] EventGridEvent eventGridEvent, [OrchestrationClient] DurableOrchestrationClient SetLeagueEmailAddressOrchestrationClient, ILogger log ) { #region Logging if (null != log) { log.LogDebug("Function triggered in OnSetLeagueEmailAddressCommand"); } if (null == eventGridEvent) { // This function should not proceed if there is no event data if (null != log) { log.LogError("Missing event grid trigger data in OnSetLeagueEmailAddressCommand"); } return; } #endregion try { // Get the command request details out of the event grid data request var jsondata = JsonConvert.SerializeObject(eventGridEvent.Data); CommandRequest <Set_Email_Address_Definition> cmdRequest = null; if (!string.IsNullOrWhiteSpace(jsondata)) { cmdRequest = JsonConvert.DeserializeObject <CommandRequest <Set_Email_Address_Definition> >(jsondata); } // Log the parameters #region Logging if (null != log) { if (null == cmdRequest) { log.LogDebug($"Unable to read parameters from {eventGridEvent.Data} in OnSetLeagueEmailAddressCommand"); } } #endregion if (null != cmdRequest) { // Create a new command // Make sure the command has a new identifier if (cmdRequest.CommandUniqueIdentifier == Guid.Empty) { cmdRequest.CommandUniqueIdentifier = Guid.NewGuid(); } if (string.IsNullOrWhiteSpace(cmdRequest.CommandName)) { cmdRequest.CommandName = "Set League Email Address"; } // Using Azure Durable functions to do the command chaining string instanceId = await SetLeagueEmailAddressOrchestrationClient.StartNewAsync("SetLeagueEmailAddressCommandHandlerOrchestrator", cmdRequest); log.LogInformation($"Run SetLeagueEmailAddressCommandHandlerOrchestrator orchestration with ID = '{instanceId}'."); } } catch (Exception ex) { log.LogError(ex.ToString()); } }
/// <summary> /// Retrieve live preview bynary data. The data format is "Equirectangular" and "MotionJPEG". /// </summary> public void GetLivePreview(Action<byte[], Error> callback) { CommandRequest request = new CommandRequest("camera._getLivePreview"); request.AddParameter("sessionId", currentSessionId); CommandExecute(request, (response) => { callback(response.bytes, response.error); }); }
public Task <Result <CommandResponse> > ExecuteAsync(OperationContext context, CommandRequest request) { return(context.PerformOperationAsync(Tracer, async() => { var requestAsBytes = _serializationPool.Serialize(request, (value, writer) => value.Serialize(writer)); var requestAsProto = new Grpc.Request() { Request_ = Google.Protobuf.ByteString.CopyFrom((byte[])requestAsBytes), }; var callOptions = new CallOptions() .WithCancellationToken(context.Token) .WithHeaders(new Metadata() { { "X-Cache-Client-Version", "0.0" }, { "X-Cache-Operation-Id", context.TracingContext.Id.ToString() }, }); Contract.AssertNotNull(_client); var asyncUnaryCall = _client.ExecuteAsync(requestAsProto, callOptions); Grpc.Reply responseAsProto = await asyncUnaryCall; var responseAsBytes = responseAsProto.Reply_.ToByteArray(); var response = _serializationPool.Deserialize(responseAsBytes, reader => CommandResponse.Deserialize(reader)); Contract.AssertNotNull(response); return new Result <CommandResponse>(response); }, traceErrorsOnly: true)); }