private void DisplayResult(ExecuteResponse result) { if (result == null) { MessageBox.Show("Result is null.", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (result.ExceptionMessage != null) { MessageBox.Show(result.ExceptionMessage, "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { GridResult.DataSource = result.DataTable; } }
public async Task Should_Use_The_ProcessResponseProcessor(bool throwOnError, bool processResponseProcessorResult) { mockCoverageProject.Setup(cp => cp.ProjectName).Returns("TestProject"); var mockProcesUtil = mocker.GetMock <IProcessUtil>(); var executeResponse = new ExecuteResponse(); mockProcesUtil.Setup(p => p.ExecuteAsync(It.IsAny <ExecuteRequest>()).Result).Returns(executeResponse); var mockProcessResponseProcessor = mocker.GetMock <IProcessResponseProcessor>(); var logTitle = "Coverlet Collector Run (TestProject)"; mockProcessResponseProcessor.Setup(rp => rp.Process(executeResponse, It.IsAny <Func <int, bool> >(), throwOnError, logTitle, It.IsAny <Action>())).Returns(processResponseProcessorResult); Assert.AreEqual(processResponseProcessorResult, await coverletDataCollectorUtil.RunAsync(throwOnError)); }
public void Should_Log_Response_Output_With_Error_Title_If_Non_Success_ExitCode_And_Throw_Error_False() { var executeResponse = new ExecuteResponse { ExitCode = 999, Output = "This will be logged" }; Assert.False(processor.Process(executeResponse, exitCode => { return(false); }, false, "title", successCallback)); Assert.IsFalse(successCallbackCalled); mocker.Verify <ILogger>(l => l.Log("title Error", "This will be logged")); }
public void Should_Log_Response_Output_With_Title_If_Success_ExitCode_And_Call_Callback() { var executeResponse = new ExecuteResponse { ExitCode = 0, Output = "This will be logged" }; Assert.True(processor.Process(executeResponse, exitCode => { return(true); }, true, "title", successCallback)); Assert.IsTrue(successCallbackCalled); mocker.Verify <ILogger>(l => l.Log("title", "This will be logged")); }
private ExecuteResponse Execute(int languageId, string source) { try { Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sender.Connect(IPAddress.Parse("163.118.202.146"), 5557); sender.SendTimeout = sender.ReceiveTimeout = TimeLimit + 12000; ExecuteResponse response = ExecuteModule.SendRequest(new ExecuteRequest(languageId, source, TimeLimit, MemoryLimit, _inputs), sender); sender.Close(); return(response); } catch (Exception) { return(null); } }
private static ExecuteResponse.Builder GetHeroDigest(ExecuteRequest request) { var results = new List <OperationResult>(); foreach (Operation operation in request.OperationsList) { //var toonDigest = ToonHandle.ParseFrom(operation.RowId.Hash.ToByteArray().Skip(2).ToArray()); OperationResult.Builder operationResult = OperationResult.CreateBuilder().SetTableId(operation.TableId); var value = new EntityId.Builder { IdHigh = 0x300016200004433, IdLow = 2 }; operationResult.AddData( Cell.CreateBuilder() .SetColumnId(operation.ColumnId) .SetRowId(operation.RowId) .SetVersion(1) .SetData(D3.Hero.Digest.CreateBuilder().SetVersion(891) .SetHeroId(value) .SetHeroName("hazzik") .SetGbidClass(0) .SetPlayerFlags(0) .SetLevel(1) .SetVisualEquipment(new VisualEquipment.Builder().Build()) .SetLastPlayedAct(0) .SetHighestUnlockedAct(0) .SetLastPlayedDifficulty(0) .SetHighestUnlockedDifficulty(0) .SetLastPlayedQuest(-1) .SetLastPlayedQuestStep(-1) .SetTimePlayed(0) .Build() .ToByteString()) .Build() ); results.Add(operationResult.Build()); } ExecuteResponse.Builder builder = ExecuteResponse.CreateBuilder(); foreach (OperationResult result in results) { builder.AddResults(result); } return(builder); }
private static object UnhandledPageLoadResponse( PrefetchResponse prefetchResponse, ExecuteResponse executeResponse, TraceHandler traceHandler) { var response = new PageLoadResponse { Trace = traceHandler?.CurrentTrace }; if (prefetchResponse != null) { prefetchResponse.PageLoad = response; return(null); } executeResponse.PageLoad = response; return(null); }
public void Should_Throw_Exception_If_Non_Success_ExitCode_And_Throw_Error_True() { var executeResponse = new ExecuteResponse(); executeResponse.ExitCode = 999; executeResponse.Output = "This will be exception message"; var callbackExitCode = 0; Assert.Throws <Exception>(() => { processor.Process(executeResponse, exitCode => { callbackExitCode = exitCode; return(false); }, true, null, null); }, executeResponse.Output); Assert.AreEqual(executeResponse.ExitCode, callbackExitCode); }
public override Task <ExecuteResponse> Execute(ExecuteRequest request, ServerCallContext context) { Console.WriteLine("Execute called."); Int64 batchSequenceNumber; ExecuteResponse executeResponse = new ExecuteResponse(); mutex.WaitOne(); batchSequenceNumber = sequenceNumber; executeResponse.Latencies.Add(latencies); latencies.Clear(); sequenceNumber += 1; mutex.ReleaseMutex(); long currentTimeMillis = CurrentTimeMillis(); for (int i = 0; i < batchSize; ++i) { Google.Cloud.PubSub.V1.PubsubMessage message = new Google.Cloud.PubSub.V1.PubsubMessage { Data = messageData, Attributes = { { "sendTime", currentTimeMillis.ToString() }, { "clientId", clientId }, { "sequenceNumber", (batchSequenceNumber * batchSize + i).ToString() } } }; client.PublishAsync(message).ContinueWith( task => { Console.WriteLine("Publish handler invoked."); if (!task.IsFaulted) { long duration = CurrentTimeMillis() - currentTimeMillis; mutex.WaitOne(); latencies.Add(duration); mutex.ReleaseMutex(); } Console.WriteLine("Publish handler done."); } ); } Console.WriteLine("Execute returned."); return(Task.FromResult(executeResponse)); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <returns></returns> public ExecuteResponse ParseInput(ExecuteRequest request) { ExecuteResponse resp = new ExecuteResponse(); if (!string.IsNullOrEmpty(request.Input)) { List <string> lines = request.Input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList(); //assumption: 5 lines of input //1st line is upper bound of landing area // 2nd = deployment position of rover 1 // 3rd = instructions of rover 1 // 4th line = deployment position of rover 2 // 5th line = instructions of rover 2 if (lines.Any()) { try { Plateau p = GetPlateau(lines.First()); var splitRoversList = lines.SplitList(2, 1).ToList(); for (int i = 0; i < splitRoversList.Count; i++) { var deployment = splitRoversList[i][0]; var rover = _roverFactory.GetRover(splitRoversList[i][0]).SetName($"Rover{i}"); rover.Execute(p, _parser.Parse(splitRoversList[i][1])); resp.Output += $"{rover.Position.XCoordinate} {rover.Position.YCoordinate} {rover.Orientation}{Environment.NewLine}"; } } catch (ParserException) { throw; } catch (Exception ex) { throw new ApplicationException($"Unhandled exception encountered with message {ex.Message}", ex); } } } return(resp); }
private static ExecuteResponse ExecuteLoadedAssemblyString(byte[] loadedAssemblyBytes, Activity activity) { MethodInfo printMethod; object loadedInstance; try { // TODO: create new AppDomain for each loaded assembly, to prevent memory leakage var loadedAssembly = AppDomain.CurrentDomain.Load(loadedAssemblyBytes); var loadedType = loadedAssembly.GetType("__MTDynamicCode"); if (loadedType == null) { return(null); } loadedInstance = Activator.CreateInstance(loadedType); printMethod = loadedInstance.GetType().GetMethod("Main"); } catch (Exception e) { return(new ExecuteResponse { ErrorMessage = e.Message }); } var response = new ExecuteResponse(); try { printMethod.Invoke(loadedInstance, new object[] { activity, activity.Window }); var dumpsRaw = loadedInstance.GetType().GetField("___dumps").GetValue(loadedInstance) as IEnumerable; response.SetDumpValues(dumpsRaw.Cast <object>().Select(GetDumpObjectFromObject).ToList()); response.SetMaxEnumerableItemCount(Convert.ToInt32(loadedInstance.GetType().GetField("___maxEnumerableItemCount").GetValue(loadedInstance))); } catch (Exception e) { var lineNumber = loadedInstance.GetType().GetField("___lastExecutedStatementOffset").GetValue(loadedInstance); response.ErrorMessage = String.Format("___EXCEPTION_____At offset: {0}__{1}", lineNumber, e.InnerException.Message); } return(response); }
public async Task Should_Use_The_ProcessResponseProcessor() { mockCoverageProject.Setup(cp => cp.ProjectName).Returns("TestProject"); mockCoverageProject.Setup(cp => cp.CoverageOutputFolder).Returns(""); var mockProcesUtil = mocker.GetMock <IProcessUtil>(); var executeResponse = new ExecuteResponse(); var ct = CancellationToken.None; mockProcesUtil.Setup(p => p.ExecuteAsync(It.IsAny <ExecuteRequest>(), ct).Result).Returns(executeResponse); var mockProcessResponseProcessor = mocker.GetMock <IProcessResponseProcessor>(); var logTitle = "Coverlet Collector Run (TestProject)"; mockProcessResponseProcessor.Setup(rp => rp.Process(executeResponse, It.IsAny <Func <int, bool> >(), true, logTitle, It.IsAny <Action>())); await coverletDataCollectorUtil.RunAsync(ct); mockProcessResponseProcessor.VerifyAll(); }
private static bool HandleMboxRequest( PrefetchResponse prefetchResponse, ExecuteResponse executeResponse, MboxRequest mboxRequest, List <Option> consequenceOptions, List <Metric> consequenceMetrics, TraceHandler traceHandler) { if (prefetchResponse != null) { var prefetchMboxResponse = new PrefetchMboxResponse(mboxRequest.Index, mboxRequest.Name, consequenceOptions, consequenceMetrics); prefetchResponse.Mboxes ??= new List <PrefetchMboxResponse>(); prefetchResponse.Mboxes.Add(prefetchMboxResponse); return(true); } if (executeResponse == null) { return(false); } var mboxResponse = new MboxResponse(mboxRequest.Index, mboxRequest.Name, metrics: consequenceMetrics) { Options = consequenceOptions?.Select( option => { option.EventToken = null; return(option); }) .Where(option => option.Type != null || option.Content != null || option.ResponseTokens != null) .ToList(), Trace = traceHandler?.CurrentTrace, }; executeResponse.Mboxes ??= new List <MboxResponse>(); executeResponse.Mboxes.Add(mboxResponse); return(true); }
/// <summary> /// This request is used as a short-hand for create a Statement and fetching the first batch /// of results in a single call without any parameter substitution. /// </summary> public async Task <ExecuteResponse> PrepareAndExecuteRequestAsync(string connectionId, string sql, uint statementId, long maxRowsTotal, int firstFrameMaxSize, RequestOptions options) { PrepareAndExecuteRequest req = new PrepareAndExecuteRequest { Sql = sql, ConnectionId = connectionId, StatementId = statementId, MaxRowsTotal = maxRowsTotal, FirstFrameMaxSize = firstFrameMaxSize }; WireMessage msg = new WireMessage { Name = Constants.WireMessagePrefix + "PrepareAndExecuteRequest", WrappedMessage = req.ToByteString() }; using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options)) { if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK) { WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream()); ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage); throw new WebException( string.Format( "PrepareAndExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}", connectionId, webResponse.WebResponse.StatusCode, res.ToString())); } else { WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream()); ExecuteResponse res = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage); return(res); } } }
public void refreshChanges() { new Thread(() => { ExecuteResponse gitAdd = executeWithCode("git", "add -A"); if (gitAdd.exitCode != 0) { dialogue("git add -A returned exit code " + gitAdd.exitCode, gitAdd.message); return; } int changeLengthBefore = changes.Length; string status = execute("git", "-c color.status=false status -s"); status = status.Trim(); changes = status.Split('\n'); if (changes.Length == 1 && changes[0] == "") changes = new string[] { }; if (changeLengthBefore == 0 && changes.Length != 0) { changesFoldedOut = true; } }).Start(); /* ' ' = unmodified M = modified A = added D = deleted R = renamed C = copied U = updated but unmerged*/ }
/// <summary> /// This request is used to execute a PreparedStatement, optionally with values to bind to the parameters in the Statement. /// </summary> public async Task <ExecuteResponse> ExecuteRequestAsync(StatementHandle statementHandle, pbc::RepeatedField <TypedValue> parameterValues, ulong firstFrameMaxSize, bool hasParameterValues, RequestOptions options) { ExecuteRequest req = new ExecuteRequest { StatementHandle = statementHandle, ParameterValues = parameterValues, FirstFrameMaxSize = firstFrameMaxSize, HasParameterValues = hasParameterValues }; WireMessage msg = new WireMessage { Name = Constants.WireMessagePrefix + "ExecuteRequest", WrappedMessage = req.ToByteString() }; using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options)) { if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK) { WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream()); ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage); throw new WebException( string.Format( "ExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}", statementHandle.ConnectionId, webResponse.WebResponse.StatusCode, res.ToString())); } else { WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream()); ExecuteResponse res = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage); return(res); } } }
public async Task <IActionResult> ObtenerCotizacionesBCUAsync([Bind("IDMoneda,Fecha,Cotizacion")] Cotizaciones cotizaciones) { wsbcucotizacionesin DatosIn = new wsbcucotizacionesin(); DatosIn.FechaDesde = cotizaciones.Fecha; // new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); //ViewData["Fecha"]; DatosIn.FechaHasta = cotizaciones.Fecha; short[] misMonedas = new short[1]; //traigo las monedas, para obtener el código de BCU var monedas = await _context.Monedas .SingleOrDefaultAsync(m => m.IDMoneda == cotizaciones.IDMoneda); misMonedas[0] = (short)monedas.CodBCU; DatosIn.Moneda = misMonedas; wsbcucotizacionesout DatosOut = new wsbcucotizacionesout(); var miRequest = new ExecuteRequest(DatosIn); var miResponse = new ExecuteResponse(); wsbcucotizacionesSoapPortClient SoapClient = new wsbcucotizacionesSoapPortClient(); ExecuteResponse x = await SoapClient.ExecuteAsync(DatosIn); var miRespuestaStatusMensaje = x.Salida.respuestastatus.mensaje; var miRespuestaStatusCodigo = x.Salida.respuestastatus.codigoerror; var miRespuestaStatus = x.Salida.respuestastatus.status; //Console.WriteLine(x.Salida.datoscotizaciones[0].TCC); //ViewData["Cotizacion"] = x.Salida.datoscotizaciones[0].TCC; var miAnswer = JsonConvert.SerializeObject(new { tc = x.Salida.datoscotizaciones[0].TCC, status = miRespuestaStatus, error = miRespuestaStatusCodigo, mensaje = miRespuestaStatusMensaje }); return(Json(miAnswer)); }
private void checkout(string branch) { dialogue(branch); new Thread(() => { StringPointer busyLock = new StringPointer("checkout"); business.Add(busyLock); ExecuteResponse checkoutResponse = executeWithCode("git", "checkout " + branch); if (checkoutResponse.exitCode == 0) { refreshInformation(); } else { dialogue("Could not checkout", checkoutResponse.message); } mainThreadInvokeQueue += new Invoke(() => { business.Remove(busyLock); Repaint(); }); }).Start(); }
private ExecuteResponse executeWithCode(string command, string args) { Process p = new Process(); p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = command; p.StartInfo.Arguments = args; p.Start(); // To avoid deadlocks, always read the output stream first and then wait. string output = ""; p.WaitForExit(); ExecuteResponse executeResponse = new ExecuteResponse(); output = p.StandardOutput.ReadToEnd(); output += p.StandardError.ReadToEnd(); executeResponse.exitCode = p.ExitCode; executeResponse.message = output; return executeResponse; }
private static bool HandleResult( IDictionary <string, object> consequence, OnDeviceDecisioningRule rule, RequestDetailsUnion details, PrefetchResponse prefetchResponse, ExecuteResponse executeResponse, IList <Notification> notifications, TraceHandler traceHandler, string globalMbox = "target-global-mbox") { if (consequence == null || consequence.Count == 0) { return(false); } consequence.TryGetValue(Name, out var nameObject); var consequenceName = (string)nameObject; consequence.TryGetValue(Options, out var optionsObject); var consequenceOptions = (List <Option>)optionsObject; consequence.TryGetValue(Metrics, out var metricsObject); var consequenceMetrics = GetMetrics(metricsObject); if (executeResponse != null) { var notification = CreateNotification(details, consequenceOptions, globalMbox); traceHandler?.AddNotification(rule, notification); notifications.Add(notification); } return(details.Match( _ => HandlePageLoad(prefetchResponse, executeResponse, consequenceOptions, consequenceMetrics, traceHandler), mboxRequest => HandleMboxRequest(prefetchResponse, executeResponse, mboxRequest, consequenceOptions, consequenceMetrics, traceHandler), _ => HandleViewRequest(prefetchResponse, consequenceName, consequenceOptions, consequenceMetrics, traceHandler))); }
/// <summary> /// Gets the wpsjob recast response. /// </summary> /// <returns>The wpsjob recast response.</returns> /// <param name="wpsjob">Wpsjob.</param> /// <param name="execResponse">Exec response.</param> public static ExecuteResponse GetWpsjobRecastResponse(IfyContext context, WpsJob wpsjob, ExecuteResponse execResponse = null) { log.DebugFormat("GetWpsjobRecastResponse"); if (wpsjob.Status == WpsJobStatus.COORDINATOR) { log.DebugFormat("GetWpsjobRecastResponse -- Status is Coordinator"); var resultUrl = WpsJob.GetResultUrl(execResponse); if (resultUrl == null) { return(UpdateProcessOutputs(context, execResponse, wpsjob)); } wpsjob.StatusLocation = resultUrl; wpsjob.Store(); return(CreateExecuteResponseForStagedWpsjob(context, wpsjob, execResponse)); } if (wpsjob.Status != WpsJobStatus.SUCCEEDED) { log.DebugFormat("GetWpsjobRecastResponse -- Status is not Succeeded"); return(UpdateProcessOutputs(context, execResponse, wpsjob)); } if (execResponse == null) { var jobresponse = wpsjob.GetStatusLocationContent(); if (jobresponse is ExecuteResponse) { execResponse = jobresponse as ExecuteResponse; } else { throw new Exception("Error while creating Execute Response of job " + wpsjob.Identifier); } } if (wpsjob.Provider != null && !wpsjob.Provider.StageResults) { log.DebugFormat("GetWpsjobRecastResponse -- Provider does not allow staging"); return(UpdateProcessOutputs(context, execResponse, wpsjob)); } if (execResponse.Status.Item is ProcessSucceededType) { var resultUrl = WpsJob.GetResultUrl(execResponse); if (resultUrl == null) { return(UpdateProcessOutputs(context, execResponse, wpsjob)); } var url = new Uri(resultUrl); System.Text.RegularExpressions.Regex r; System.Text.RegularExpressions.Match m; string hostname = url.Host; string workflow = "", runId = ""; string recaststatusurl = "", newStatusLocation = ""; //case url is recast describe url if (resultUrl.StartsWith(string.Format("{0}/t2api/describe", recastBaseUrl))) { wpsjob.StatusLocation = resultUrl; wpsjob.Status = WpsJobStatus.STAGED; wpsjob.Store(); return(CreateExecuteResponseForStagedWpsjob(context, wpsjob, execResponse)); } else { //case old sandboxes r = new System.Text.RegularExpressions.Regex(@"^\/sbws\/wps\/(?<workflow>[a-zA-Z0-9_\-]+)\/(?<runid>[a-zA-Z0-9_\-]+)\/results"); m = r.Match(url.AbsolutePath); if (m.Success) { workflow = m.Result("${workflow}"); runId = m.Result("${runid}"); if (wpsjob.Provider != null && wpsjob.Provider.BaseUrl != null) { r = new System.Text.RegularExpressions.Regex(@"https?:\/\/ogc-eo-apps-0?[0-9@].terradue.com"); m = r.Match(wpsjob.Provider.BaseUrl); if (m.Success) { if (wpsjob.Owner != null) { var username = wpsjob.Owner.TerradueCloudUsername; var recastdescribeurl = string.Format("{0}/t2api/describe/{1}/_results/workflows/{2}/run/{3}", recastBaseUrl, username, workflow, runId); wpsjob.StatusLocation = recastdescribeurl; wpsjob.Status = WpsJobStatus.STAGED; wpsjob.Store(); return(CreateExecuteResponseForStagedWpsjob(context, wpsjob, execResponse)); } } } recaststatusurl = GetWpsJobRecastStatusUrl(hostname, workflow, runId); newStatusLocation = GetWpsJobRecastDescribeUrl(hostname, workflow, runId); } else { //case new sandboxes r = new System.Text.RegularExpressions.Regex(@"^\/sbws\/production\/run\/(?<workflow>[a-zA-Z0-9_\-]+)\/(?<runid>[a-zA-Z0-9_\-]+)\/products"); m = r.Match(url.AbsolutePath); if (m.Success) { workflow = m.Result("${workflow}"); runId = m.Result("${runid}"); recaststatusurl = GetWpsJobRecastStatusUrl(hostname, workflow, runId); newStatusLocation = GetWpsJobRecastDescribeUrl(hostname, workflow, runId); } else { //case production clusters r = new System.Text.RegularExpressions.Regex(@"^\/production\/(?<community>[a-zA-Z0-9_\-]+)\/results\/workflows\/(?<workflow>[a-zA-Z0-9_\-]+)\/runs\/(?<runid>[a-zA-Z0-9_\-]+)"); m = r.Match(url.AbsolutePath); if (m.Success) { workflow = m.Result("${workflow}"); runId = m.Result("${runid}"); var community = m.Result("${community}"); recaststatusurl = GetWpsJobRecastStatusUrl(hostname, workflow, runId); newStatusLocation = GetWpsJobRecastDescribeUrl(hostname, workflow, runId); } else { //case direct recast or catalog response if (url.Host == new Uri(recastBaseUrl).Host || CatalogueFactory.IsCatalogUrl(url)) { log.DebugFormat("Recasting (DIRECT) job {0} - url = {1}", wpsjob.Identifier, resultUrl); wpsjob.StatusLocation = resultUrl; wpsjob.Status = WpsJobStatus.STAGED; wpsjob.Store(); return(CreateExecuteResponseForStagedWpsjob(context, wpsjob, execResponse)); } else { //cases external providers var dataGatewaySubstitutions = JsonSerializer.DeserializeFromString <List <DataGatewaySubstitution> >(AppSettings["DataGatewaySubstitutions"]); if (dataGatewaySubstitutions != null) { foreach (var sub in dataGatewaySubstitutions) { if (url.Host.Equals(sub.host) && url.AbsolutePath.Contains(sub.oldvalue)) { var path = url.AbsolutePath; path = path.Replace(sub.oldvalue, sub.substitute); //we assume that result url is pointing to a metadata file path = path.Substring(0, path.LastIndexOf("/")); recaststatusurl = GetWpsJobRecastStatusUrl(path); newStatusLocation = GetWpsJobRecastDescribeUrl(path); continue; } } } //none of the above cases if (string.IsNullOrEmpty(recaststatusurl)) { log.DebugFormat("Recasting job {0} - url = {1} ; the url did not match any case", wpsjob.Identifier, url.AbsolutePath); return(UpdateProcessOutputs(context, execResponse, wpsjob)); } } } } } } try { var recaststatus = GetWpsjobRecastStatus(recaststatusurl); //error during recast if (recaststatus.status == statusError) { log.ErrorFormat("Recasting job {0} - url = {1} - message = {2}", wpsjob.Identifier, recaststatusurl, recaststatus.message); var exceptionReport = new ExceptionReport { Exception = new List <ExceptionType> { new ExceptionType { ExceptionText = new List <string> { "Error while staging data to store --- " + recaststatus.message } } } }; execResponse.Status = new StatusType { Item = new ProcessFailedType { ExceptionReport = exceptionReport }, ItemElementName = ItemChoiceType.ProcessFailed, creationTime = wpsjob.CreatedTime }; } //recast is still in progress else if (recaststatus.status == statusInProgress) { log.DebugFormat("Recasting STILL IN PROGRESS job {0} - url = {1} - message = {2}", wpsjob.Identifier, recaststatusurl, recaststatus.message); execResponse.Status = new StatusType { Item = new ProcessStartedType { Value = "Process in progress", percentCompleted = "99" }, ItemElementName = ItemChoiceType.ProcessStarted, creationTime = wpsjob.CreatedTime }; } //recast is completed else if (recaststatus.status == statusCompleted) { log.DebugFormat("Recasting job {0} - url = {1} - message = {2}", wpsjob.Identifier, recaststatusurl, recaststatus.message); wpsjob.StatusLocation = newStatusLocation; wpsjob.Status = WpsJobStatus.STAGED; wpsjob.Store(); return(CreateExecuteResponseForStagedWpsjob(context, wpsjob, execResponse)); } }catch (Exception) { } } return(UpdateProcessOutputs(context, execResponse, wpsjob)); }
/// <summary> /// Constructs an instance from the execution results of an /// <see cref="AnsiblePlayer"/> play operation. /// </summary> /// <param name="rawResults">The execution results.</param> internal AnsiblePlayResults(ExecuteResponse rawResults) { Covenant.Requires <ArgumentNullException>(rawResults != null, nameof(rawResults)); RawResults = rawResults; if (rawResults.ExitCode != 0 && rawResults.ExitCode != 2) { // Must be a command line argument or playbook syntax error // as opposed to a valid playbook that had one or more failed // tasks. throw new Exception(rawResults.ErrorText); } using (var reader = new StringReader(rawResults.OutputText)) { string line; // Skip over all lines until we see the first task line. for (line = reader.ReadLine(); line != null; line = reader.ReadLine()) { if (line.StartsWith("TASK [") && line.EndsWith("**********")) { break; } } var sbTask = new StringBuilder(); var lastTask = false; while (!lastTask) { // Capture the current line and any subsequent lines up to but not // including the next task marker or the PLAY RECAP line and then // use this to create the next task result. sbTask.AppendLine(line); for (line = reader.ReadLine(); line != null; line = reader.ReadLine()) { if (line.StartsWith("TASK [") && line.EndsWith("**********")) { break; } else if (line.StartsWith("PLAY RECAP **********") && line.EndsWith("**********")) { lastTask = true; break; } sbTask.AppendLine(line); } var taskResult = new AnsibleTaskResult(sbTask.ToString()); if (taskResult.HasStatus) { TaskResults.Add(taskResult); } if (!lastTask) { sbTask.Clear(); sbTask.AppendLine(line); // This is the first line of the next task } } } }
public void SimpleTest() { var client = new PhoenixClient(_credentials); string connId = GenerateRandomConnId(); RequestOptions options = RequestOptions.GetGatewayDefaultOptions(); // In gateway mode, url format will be https://<cluster dns name>.azurehdinsight.net/hbasephoenix<N>/ // Requests sent to hbasephoenix0/ will be forwarded to PQS on workernode0 options.AlternativeEndpoint = "hbasephoenix0/"; string tableName = "Persons" + connId; OpenConnectionResponse openConnResponse = null; CreateStatementResponse createStatementResponse = null; try { // Opening connection pbc::MapField <string, string> info = new pbc::MapField <string, string>(); openConnResponse = client.OpenConnectionRequestAsync(connId, info, options).Result; // Syncing connection ConnectionProperties connProperties = new ConnectionProperties { HasAutoCommit = true, AutoCommit = true, HasReadOnly = true, ReadOnly = false, TransactionIsolation = 0, Catalog = "", Schema = "", IsDirty = true }; client.ConnectionSyncRequestAsync(connId, connProperties, options).Wait(); createStatementResponse = client.CreateStatementRequestAsync(connId, options).Result; // Running query 1 string sql1 = "CREATE TABLE " + tableName + " (LastName varchar(255) PRIMARY KEY,FirstName varchar(255))"; client.PrepareAndExecuteRequestAsync(connId, sql1, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); // Running query 2 string sql2 = "UPSERT INTO " + tableName + " VALUES ('d1','x1')"; client.PrepareAndExecuteRequestAsync(connId, sql2, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); // Running query 3 string sql3 = "select count(*) from " + tableName; ExecuteResponse execResponse3 = client.PrepareAndExecuteRequestAsync(connId, sql3, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Result; long count = execResponse3.Results[0].FirstFrame.Rows[0].Value[0].ScalarValue.NumberValue; Assert.AreEqual(1, count); // Running query 4 string sql4 = "DROP TABLE " + tableName; client.PrepareAndExecuteRequestAsync(connId, sql4, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (createStatementResponse != null) { client.CloseStatementRequestAsync(connId, createStatementResponse.StatementId, options).Wait(); createStatementResponse = null; } if (openConnResponse != null) { client.CloseConnectionRequestAsync(connId, options).Wait(); openConnResponse = null; } } }
public void RowInsertWithArbitraryTimestamp() { // https://phoenix.apache.org/faq.html#Can_phoenix_work_on_tables_with_arbitrary_timestamp_as_flexible_as_HBase_API // The table creation time must not be later than the row insert timestamp // Otherwise will get table NOT FOUND exception // Row insert time must not be later than row query time // Otherwise the row will not appear in the resultset var client = new PhoenixClient(_credentials); string connId = GenerateRandomConnId(); RequestOptions options = RequestOptions.GetGatewayDefaultOptions(); // In gateway mode, url format will be https://<cluster dns name>.azurehdinsight.net/hbasephoenix<N>/ // Requests sent to hbasephoenix0/ will be forwarded to PQS on workernode0 options.AlternativeEndpoint = "hbasephoenix0/"; string tableName = "Persons" + connId; OpenConnectionResponse openConnResponse = null; CreateStatementResponse createStatementResponse = null; try { // Opening connection // Set table creation time to 0 long ts = 0; pbc::MapField <string, string> info = new pbc::MapField <string, string>(); info.Add("CurrentSCN", ts.ToString()); openConnResponse = client.OpenConnectionRequestAsync(connId, info, options).Result; // Syncing connection ConnectionProperties connProperties = new ConnectionProperties { HasAutoCommit = true, AutoCommit = true, HasReadOnly = true, ReadOnly = false, TransactionIsolation = 0, Catalog = "", Schema = "", IsDirty = true }; client.ConnectionSyncRequestAsync(connId, connProperties, options).Wait(); createStatementResponse = client.CreateStatementRequestAsync(connId, options).Result; // Running query 1 string sql1 = "CREATE TABLE " + tableName + " (LastName varchar(255) PRIMARY KEY,FirstName varchar(255))"; client.PrepareAndExecuteRequestAsync(connId, sql1, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (createStatementResponse != null) { client.CloseStatementRequestAsync(connId, createStatementResponse.StatementId, options).Wait(); createStatementResponse = null; } if (openConnResponse != null) { client.CloseConnectionRequestAsync(connId, options).Wait(); openConnResponse = null; } } // insert row with specified timestamp try { // Opening connection long ts = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds; pbc::MapField <string, string> info = new pbc::MapField <string, string>(); info.Add("CurrentSCN", ts.ToString()); openConnResponse = client.OpenConnectionRequestAsync(connId, info, options).Result; // Syncing connection ConnectionProperties connProperties = new ConnectionProperties { HasAutoCommit = true, AutoCommit = true, HasReadOnly = true, ReadOnly = false, TransactionIsolation = 0, Catalog = "", Schema = "", IsDirty = true }; client.ConnectionSyncRequestAsync(connId, connProperties, options).Wait(); createStatementResponse = client.CreateStatementRequestAsync(connId, options).Result; // Running query 2 string sql2 = "UPSERT INTO " + tableName + " VALUES ('d1','x1')"; client.PrepareAndExecuteRequestAsync(connId, sql2, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (createStatementResponse != null) { client.CloseStatementRequestAsync(connId, createStatementResponse.StatementId, options).Wait(); createStatementResponse = null; } if (openConnResponse != null) { client.CloseConnectionRequestAsync(connId, options).Wait(); openConnResponse = null; } } // query row with specified timestamp try { // Opening connection long ts = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds; pbc::MapField <string, string> info = new pbc::MapField <string, string>(); info.Add("CurrentSCN", ts.ToString()); openConnResponse = client.OpenConnectionRequestAsync(connId, info, options).Result; // Syncing connection ConnectionProperties connProperties = new ConnectionProperties { HasAutoCommit = true, AutoCommit = true, HasReadOnly = true, ReadOnly = false, TransactionIsolation = 0, Catalog = "", Schema = "", IsDirty = true }; client.ConnectionSyncRequestAsync(connId, connProperties, options).Wait(); createStatementResponse = client.CreateStatementRequestAsync(connId, options).Result; // Running query 3 string sql3 = "select count(*) from " + tableName; ExecuteResponse execResponse3 = client.PrepareAndExecuteRequestAsync(connId, sql3, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Result; long count = execResponse3.Results[0].FirstFrame.Rows[0].Value[0].ScalarValue.NumberValue; Assert.AreEqual(1, count); // Running query 4 string sql4 = "DROP TABLE " + tableName; client.PrepareAndExecuteRequestAsync(connId, sql4, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (createStatementResponse != null) { client.CloseStatementRequestAsync(connId, createStatementResponse.StatementId, options).Wait(); createStatementResponse = null; } if (openConnResponse != null) { client.CloseConnectionRequestAsync(connId, options).Wait(); openConnResponse = null; } } }
public void ManyRowBatchInsertTest() { var client = new PhoenixClient(_credentials); string connId = GenerateRandomConnId(); RequestOptions options = RequestOptions.GetGatewayDefaultOptions(); // In gateway mode, url format will be https://<cluster dns name>.azurehdinsight.net/hbasephoenix<N>/ // Requests sent to hbasephoenix0/ will be forwarded to PQS on workernode0 options.AlternativeEndpoint = "hbasephoenix0/"; string tableName = "Persons" + connId; OpenConnectionResponse openConnResponse = null; CreateStatementResponse createStatementResponse = null; try { // Opening connection pbc::MapField <string, string> info = new pbc::MapField <string, string>(); openConnResponse = client.OpenConnectionRequestAsync(connId, info, options).Result; // Syncing connection ConnectionProperties connProperties = new ConnectionProperties { HasAutoCommit = true, AutoCommit = true, HasReadOnly = true, ReadOnly = false, TransactionIsolation = 0, Catalog = "", Schema = "", IsDirty = true }; client.ConnectionSyncRequestAsync(connId, connProperties, options).Wait(); // Creating statement createStatementResponse = client.CreateStatementRequestAsync(connId, options).Result; // Running query 1 string sql1 = "CREATE TABLE " + tableName + " (LastName varchar(255) PRIMARY KEY,FirstName varchar(255))"; ExecuteResponse execResponse1 = client.PrepareAndExecuteRequestAsync(connId, sql1, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Result; // Running query 2 // Batching two sqls in a single HTTP request pbc::RepeatedField <string> list = new pbc.RepeatedField <string>(); list.Add("UPSERT INTO " + tableName + " VALUES('d1','x1')"); list.Add("UPSERT INTO " + tableName + " VALUES('d2','x2')"); ExecuteBatchResponse execResponse2 = client.PrepareAndExecuteBatchRequestAsync(connId, createStatementResponse.StatementId, list, options).Result; // Running query 3 string sql3 = "select count(*) from " + tableName; ExecuteResponse execResponse3 = client.PrepareAndExecuteRequestAsync(connId, sql3, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Result; long count3 = execResponse3.Results[0].FirstFrame.Rows[0].Value[0].ScalarValue.NumberValue; Assert.AreEqual(2, count3); // Running query 4 // Batching two sqls in a single HTTP request // Creating statement 2 string sql4 = "UPSERT INTO " + tableName + " VALUES (?,?)"; PrepareResponse prepareResponse = client.PrepareRequestAsync(connId, sql4, int.MaxValue, options).Result; StatementHandle statementHandle = prepareResponse.Statement; pbc::RepeatedField <UpdateBatch> updates = new pbc.RepeatedField <UpdateBatch>(); for (int i = 3; i < 10; i++) { pbc::RepeatedField <TypedValue> parameterValues = new pbc.RepeatedField <TypedValue>(); TypedValue v1 = new TypedValue { StringValue = "d" + i, Type = Rep.String }; TypedValue v2 = new TypedValue { StringValue = "x" + i, Type = Rep.String }; parameterValues.Add(v1); parameterValues.Add(v2); UpdateBatch batch = new UpdateBatch { ParameterValues = parameterValues }; updates.Add(batch); } ExecuteBatchResponse execResponse4 = client.ExecuteBatchRequestAsync(connId, statementHandle.Id, updates, options).Result; // Running query 5 string sql5 = "select count(*) from " + tableName; ExecuteResponse execResponse5 = client.PrepareAndExecuteRequestAsync(connId, sql5, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Result; long count5 = execResponse5.Results[0].FirstFrame.Rows[0].Value[0].ScalarValue.NumberValue; Assert.AreEqual(9, count5); // Running query 5 string sql6 = "DROP TABLE " + tableName; client.PrepareAndExecuteRequestAsync(connId, sql6, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (createStatementResponse != null) { client.CloseStatementRequestAsync(connId, createStatementResponse.StatementId, options).Wait(); createStatementResponse = null; } if (openConnResponse != null) { client.CloseConnectionRequestAsync(connId, options).Wait(); openConnResponse = null; } } }
public void QueryManyRowTest() { var client = new PhoenixClient(_credentials); string connId = GenerateRandomConnId(); RequestOptions options = RequestOptions.GetGatewayDefaultOptions(); // In gateway mode, url format will be https://<cluster dns name>.azurehdinsight.net/hbasephoenix<N>/ // Requests sent to hbasephoenix0/ will be forwarded to PQS on workernode0 options.AlternativeEndpoint = "hbasephoenix0/"; string tableName = "Persons" + connId; OpenConnectionResponse openConnResponse = null; CreateStatementResponse createStatementResponse = null; try { // Opening connection pbc::MapField <string, string> info = new pbc::MapField <string, string>(); openConnResponse = client.OpenConnectionRequestAsync(connId, info, options).Result; // Syncing connection ConnectionProperties connProperties = new ConnectionProperties { HasAutoCommit = true, AutoCommit = false, HasReadOnly = true, ReadOnly = false, TransactionIsolation = 0, Catalog = "", Schema = "", IsDirty = true }; client.ConnectionSyncRequestAsync(connId, connProperties, options).Wait(); createStatementResponse = client.CreateStatementRequestAsync(connId, options).Result; // Running query 1 string sql1 = "CREATE TABLE " + tableName + " (LastName varchar(255) PRIMARY KEY,FirstName varchar(255))"; client.PrepareAndExecuteRequestAsync(connId, sql1, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); // Commit statement 1 client.CommitRequestAsync(connId, options).Wait(); // Creating statement 2 string sql2 = "UPSERT INTO " + tableName + " VALUES (?,?)"; PrepareResponse prepareResponse = client.PrepareRequestAsync(connId, sql2, long.MaxValue, options).Result; StatementHandle statementHandle = prepareResponse.Statement; // Insert 300 rows for (int i = 0; i < 300; i++) { pbc::RepeatedField <TypedValue> list = new pbc.RepeatedField <TypedValue>(); TypedValue v1 = new TypedValue { StringValue = "d" + i, Type = Rep.String }; TypedValue v2 = new TypedValue { StringValue = "x" + i, Type = Rep.String }; list.Add(v1); list.Add(v2); ExecuteResponse executeResponse = client.ExecuteRequestAsync(statementHandle, list, long.MaxValue, true, options).Result; } // Commit statement 2 client.CommitRequestAsync(connId, options).Wait(); // Running query 3 string sql3 = "select * from " + tableName; ExecuteResponse execResponse3 = client.PrepareAndExecuteRequestAsync(connId, sql3, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Result; pbc::RepeatedField <Row> rows = execResponse3.Results[0].FirstFrame.Rows; for (int i = 0; i < rows.Count; i++) { Row row = rows[i]; Debug.WriteLine(row.Value[0].ScalarValue.StringValue + " " + row.Value[1].ScalarValue.StringValue); } // 100 is hard coded in server side as default firstframe size // In order to get remaining rows, FetchRequestAsync is used Assert.AreEqual(100, rows.Count); // Fetch remaining rows, offset is not used, simply set to 0 // if FetchResponse.Frame.Done = true, that means all the rows fetched FetchResponse fetchResponse = client.FetchRequestAsync(connId, createStatementResponse.StatementId, 0, int.MaxValue, options).Result; Assert.AreEqual(200, fetchResponse.Frame.Rows.Count); Assert.AreEqual(true, fetchResponse.Frame.Done); // Running query 4 string sql4 = "DROP TABLE " + tableName; client.PrepareAndExecuteRequestAsync(connId, sql4, createStatementResponse.StatementId, long.MaxValue, int.MaxValue, options).Wait(); // Commit statement 4 client.CommitRequestAsync(connId, options).Wait(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (createStatementResponse != null) { client.CloseStatementRequestAsync(connId, createStatementResponse.StatementId, options).Wait(); createStatementResponse = null; } if (openConnResponse != null) { client.CloseConnectionRequestAsync(connId, options).Wait(); openConnResponse = null; } } }
static void Main(string[] args) { Log = new EventLog { Source = "PowerQueryNet" }; if (args == null || args.Length == 0) { ServiceBase.Run(new WindowsService()); } else if (args.FirstOrDefault(x => x == "-ipc") != null) { try { PowerQueryService.Start(); var taskHandle = new ManualResetEvent(false); taskHandle.WaitOne(); } catch (Exception ex) { Log.WriteEntry(ex.ToString(), EventLogEntryType.Error); } } else if (args.Length == 1) { string filePath = args[0]; string fileExtension = Path.GetExtension(filePath); ExecuteResponse executeResponse = null; AllocConsole(); try { var powerQueryService = new PowerQueryService(); if (fileExtension == ".pq") { string powerQueryFolder = Path.GetDirectoryName(filePath); string powerQueryFile = Path.GetFileNameWithoutExtension(filePath); var queries = Queries.LoadFromFolder(powerQueryFolder); var credentials = Credentials.LoadFromFile(Path.Combine(powerQueryFolder, "#credentials.xml")); var executeRequest = new ExecuteRequest { QueryName = powerQueryFile, Queries = queries, Credentials = credentials, }; executeResponse = powerQueryService.Execute(executeRequest); OutputResponse(executeResponse); //string connectionString = @"Data Source=P16019\SQL2016; Integrated Security=true; Initial Catalog=TEST"; //string response = powerQueryService.ExecuteToSQL(connectionString, powerQueryFile, queries, credentials); } if (fileExtension == ".xlsx" || fileExtension == ".xlsm" || fileExtension == ".pbix" || fileExtension == ".pbit" ) { string mashup = powerQueryService.MashupFromFile(filePath); Console.WriteLine(mashup); //Queries queries = powerQueryService.MashupToQueries(filePath); } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("ex = {0}", ex.ToString()); } } else { AllocConsole(); Console.WriteLine(" Usage: -ipc"); Console.WriteLine(" Usage: [Power Query File Path]"); Console.WriteLine(" Usage: [Excel or Power BI File Path]"); Console.WriteLine(""); Console.WriteLine(" -ipc\t\t\t\tOpen named pipes service for interprocess communication"); Console.WriteLine(" [Power Query File Path]\tRun Power Query formula (*.pq)"); Console.WriteLine(" [Excel or Power BI File Path]\tGet Mashup from Excel or Power BI (*.xlsx;*.xlsm;*.pbix;*.pbit)"); Console.ReadLine(); } }
/// <summary> /// 异常接收事件。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void sms_Port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { ExecuteResponse?.Invoke(Enum.GetName(typeof(SerialError), e.EventType)); }
/// <summary> /// Constructor. /// </summary> /// <param name="response">The low-level SSH command response.</param> internal XenResponse(ExecuteResponse response) { this.Response = response; this.Items = new List <Dictionary <string, string> >(); // We need to parse the [xe] results from the standard output. This will // look something like: //uuid ( RO) : c73af9a3-8f67-0c52-6c8e-fe3208aae490 // name-label ( RW): Removable storage // name-description ( RW): // host ( RO): xentest // type ( RO): udev // content-type ( RO): disk // // //uuid ( RO) : 7a490025-7911-95f8-6058-2d4647d5f855 // name-label ( RW): DVD drives // name-description ( RW): Physical DVD drives // host ( RO): xentest // type ( RO): udev // content-type ( RO): iso // // //uuid ( RO) : 1aedccc5-8b18-4fc8-b498-e776a5ae2702 // name-label ( RW): Local storage // name-description ( RW): // host ( RO): xentest // type ( RO): lvm // content-type ( RO): user // // //uuid ( RO) : e24cd80a-f54a-4c5b-18e8-245c37b5b7e6 // name-label ( RW): XenServer Tools // name-description ( RW): XenServer Tools ISOs // host ( RO): xentest // type ( RO): iso // content-type ( RO): iso // When running XE commands directly on the XenServer host, this appears to // be a list of records with each record being terminated by two blank lines. // When executing the commands remotely via the Windows [xe.exe] CLI, the // blank lines are omitted and it appears that the "uuid " or sometimes other // property names like "Disk 0 VDI:" at the beginning of the line indicates // a new record. // // PARSING PROBLEM: // ---------------- // The problem is that we may see more than one properties starting at the // beginning of a line for an individual record. I'm going to assume that every // record will include at least one [indented] property and also that all // properties that with no leading whitespace appear at the beginning of the // record. // // Each line includes a read/write or read-only indicator (which we'll strip out) // followed by a colon and the property value. I'm not entirely sure if this // fully describes the format so I'm going to be a bit defensive below. using (var reader = new StringReader(response.OutputText)) { var isEOF = false; while (!isEOF) { // Read the next record. var rawRecord = new Dictionary <string, string>(); var parsedIndented = false; while (true) { var line = reader.ReadLine(); if (line == null) { if (rawRecord.Count > 0) { Items.Add(rawRecord); rawRecord = new Dictionary <string, string>(); } isEOF = true; break; } if (string.IsNullOrEmpty(line)) { // Ignore blank lines. continue; } var isIndented = char.IsWhiteSpace(line.First()); if (!isIndented && parsedIndented) { // Looks like the start of a new record, so add the previous record // (if not empty) before beginning to parse the new record. if (rawRecord.Count > 0) { Items.Add(rawRecord); rawRecord = new Dictionary <string, string>(); } parsedIndented = false; } else if (isIndented) { parsedIndented = true; } line = line.Trim(); // Parse the property name and value. var colonPos = line.IndexOf(':'); if (colonPos == -1) { continue; // We shouldn't ever see this so ignore it. } var namePart = line.Substring(0, colonPos).Trim(); var valuePart = line.Substring(colonPos + 1).Trim(); var parenPos = namePart.IndexOf('('); if (parenPos != -1) { namePart = namePart.Substring(0, parenPos).Trim(); } rawRecord.Add(namePart, valuePart); } // Add the record to the results if it's not empty. if (rawRecord.Count > 0) { Items.Add(rawRecord); } } } }
/// <summary> /// Creates the execute response for staged wpsjob. /// </summary> /// <returns>The execute response for staged wpsjob.</returns> /// <param name="context">Context.</param> /// <param name="wpsjob">Wpsjob.</param> public static ExecuteResponse CreateExecuteResponseForStagedWpsjob(IfyContext context, WpsJob wpsjob, ExecuteResponse response) { if (response == null) { response = new ExecuteResponse(); response.Status = new StatusType { Item = new ProcessSucceededType { Value = "Process successful" }, ItemElementName = ItemChoiceType.ProcessSucceeded, creationTime = wpsjob.EndTime != DateTime.MinValue ? wpsjob.EndTime : wpsjob.CreatedTime }; } var statusurl = wpsjob.StatusLocation; var url = new Uri(statusurl); var searchableUrls = JsonSerializer.DeserializeFromString <List <string> >(AppSettings["OpenSearchableUrls"]); if (searchableUrls == null || searchableUrls.Count == 0) { searchableUrls = new List <string>(); searchableUrls.Add(recastBaseUrl);//in case appsettings not set } var recognizedHost = false; foreach (var u in searchableUrls) { if (new Uri(u).Host == url.Host) { recognizedHost = true; } } bool statusNotOpensearchable = !recognizedHost && !statusurl.Contains("/search") && !statusurl.Contains("/description"); context.LogDebug(wpsjob, string.Format("Status url {0} is opensearchable : {1}", statusurl, statusNotOpensearchable ? "false" : "true")); if (statusNotOpensearchable) { statusurl = context.BaseUrl + "/job/wps/" + wpsjob.Identifier + "/products/description"; } response.statusLocation = context.BaseUrl + "/wps/RetrieveResultServlet?id=" + wpsjob.Identifier; response.serviceInstance = context.BaseUrl + "/wps/WebProcessingService?REQUEST=GetCapabilities&SERVICE=WPS"; response.ProcessOutputs = new List <OutputDataType> { }; response.ProcessOutputs.Add(new OutputDataType { Identifier = new CodeType { Value = "result_osd" }, Item = new DataType { Item = new ComplexDataType { mimeType = "application/xml", Reference = new OutputReferenceType { href = statusurl, mimeType = "application/opensearchdescription+xml" } } } }); if (!string.IsNullOrEmpty(wpsjob.OwsUrl)) { response.ProcessOutputs.Add(new OutputDataType { Identifier = new CodeType { Value = "job_ows" }, Item = new DataType { Item = new ComplexDataType { mimeType = "application/xml", Reference = new OutputReferenceType { href = wpsjob.OwsUrl, mimeType = "application/xml" } } } }); } return(response); }