public AsyncCommandResult(string command, Dictionary<string, object> parameters, ExecutionOptions executionOptions, AsyncCallback callback, object state) { _command = command; _parameters = parameters; _executionOptions = executionOptions; _callback = callback; _state = state; }
public IAsyncResult BeginExecute(string command, Dictionary<string, object> parameters, ExecutionOptions options, AsyncCallback callback, object asyncState) { AsyncCommandResult asyncCommandResult = new AsyncCommandResult(command, parameters, options, callback, asyncState); Queue.Enqueue(asyncCommandResult); return asyncCommandResult; }
private static void ConfigureDocumentExecutionListeners(ExecutionOptions options, IEnumerable <IDocumentExecutionListener> listeners) { Debug.Assert(listeners != null, "listeners != null"); var listenerSet = new HashSet <IDocumentExecutionListener>(options.Listeners); listenerSet.UnionWith(listeners); options.Listeners.Clear(); foreach (var listener in listenerSet) { options.Listeners.Add(listener); } }
public async Task <ExecutionResult> Process(GraphqlQuery query, ClaimsPrincipal user, params UserAuthRole[] roles) { if (query == null) { throw new ArgumentNullException(nameof(query)); } var executionOptions = new ExecutionOptions { Query = query.Query, Inputs = query.Variables.ToInputs(), }; return(await SetParamsAndExecute(executionOptions, user, roles)); }
public void apply_to_not_called_without_execute() { var docExec = new DocumentExecuter(); var execOptions = new ExecutionOptions { Schema = new Schema() }; var mockMiddleware = new ApplyCounterMiddlewareBuilder(); execOptions.FieldMiddleware = mockMiddleware; // no execute in this test //docExec.ExecuteAsync(execOptions).Wait(); Assert.Equal(0, mockMiddleware.AppliedCount); }
private Task <ExecutionResult> ExcecuteAsync(ExecutionOptions options, Context context) { var sut = CreateSut(TestSchemas.Default, TestSchemas.Ref1, TestSchemas.Ref2); options.UserContext = ActivatorUtilities.CreateInstance <GraphQLExecutionContext>(sut.Services, context); var listener = sut.Services.GetService <DataLoaderDocumentListener>(); if (listener != null) { options.Listeners.Add(listener); } return(sut.ExecuteAsync(options)); }
/// <summary> /// Gives specific information on the current condition. /// </summary> /// <param name="attributes">A list with the attributes related to the condition.</param> /// <param name="executionOptions">Specifies the modality of execution for getting the condition's state.</param> /// <returns>The result of acknowledging the condition.</returns> /// <returns>The result of getting the conditon's state.</returns> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AeCondition"]/method[@name="UpdateConditionState"]/doc/*' /// /> public virtual int UpdateConditionState(AeAttribute[] attributes, ExecutionOptions executionOptions) { int res = (int) EnumResultCode.E_FAIL; AeConditionState conditionState; if (this.AeSession == null) { Application.Instance.Trace( EnumTraceLevel.ERR, EnumTraceGroup.CLIENT, "AE.Condition.UpdateConditionState", "The Session property of the Condition cannot be null! Set the property to a value before calling UpdateConditionState!"); return res; } try { res = this.AeSession.GetAeConditionState( this.SourcePath, this.ConditionName, attributes, out conditionState, executionOptions); if (ResultCode.SUCCEEDED(res)) { this.ActiveTime = conditionState.ConditionActiveTime; this.ActorId = conditionState.AcknowledgerId; this.Attributes = conditionState.EventAttributes; } else { Application.Instance.Trace( EnumTraceLevel.ERR, EnumTraceGroup.CLIENT, "AeCondition.UpdateConditionState", "Updating condition state failed! Result: " + res); } } catch (Exception exc) { Application.Instance.Trace( EnumTraceLevel.ERR, EnumTraceGroup.CLIENT, "AeCondition.UpdateConditionState", exc.ToString()); } return res; }
/// <summary> /// Updates some object attributes to the server. /// </summary> /// <param name="whatAttributes">A list with all the object attributes to be updated to the server.</param> /// <param name="results">A list with the result of the update for each object attribute. </param> /// <param name="executionOptions">Specifies the modality of execution for updating attributes to a server.</param> /// <returns>The result of updating attributes to a server.</returns> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="ObjectSpaceElement"]/method[@name="SetAttributesToServer"]/doc/*' /// /> public virtual int SetAttributesToServer( EnumObjectAttribute[] whatAttributes, out int[] results, ExecutionOptions executionOptions) { int res = (int)EnumResultCode.E_FAIL; results = null; try { OTCExecutionOptions options = new OTCExecutionOptions(); if (executionOptions != null) { options.m_executionType = (byte)executionOptions.ExecutionType; options.m_executionContext = (uint)executionOptions.ExecutionContext; } else { options.m_executionType = (byte)EnumExecutionType.SYNCHRONOUS; options.m_executionContext = 0; } int count = whatAttributes.Length; uint[] whatAttributesToChange = new uint[count]; for (int i = 0; i < whatAttributes.Length; i++) { whatAttributesToChange[i] = (uint)whatAttributes[i]; } results = new int[count]; res = OTBFunctions.OTCUpdateAttributes( this.Handle, 0, (uint)count, whatAttributesToChange, results, ref options); } catch (Exception exc) { Application.Instance.Trace( EnumTraceLevel.ERR, EnumTraceGroup.CLIENT, "ObjectSpaceElement.SetAttributesToServer", exc.ToString()); } return(res); }
private static ExecutionResult Validate(ExecutionOptions executionOptions, params UserAuthRole[] roles) { try { executionOptions.ValidateRole(roles); // Auth. filter } catch (Exception e) { ExecutionResult er = new() { Errors = new() }; er.Errors.Add(new ExecutionError(e.Message, e)); return(er); } return(null); } }
public void apply_to_called_once_with_multiple_execute() { var docExec = new DocumentExecuter(); var execOptions = new ExecutionOptions(); execOptions.Schema = new Schema(); execOptions.Query = "{ abcd }"; var mockMiddleware = new ApplyCounterMiddlewareBuilder(); execOptions.FieldMiddleware = mockMiddleware; docExec.ExecuteAsync(execOptions).Wait(); docExec.ExecuteAsync(execOptions).Wait(); Assert.Equal(1, mockMiddleware.AppliedCount); }
async Task ExecuteQuery() { #region UseFluentValidation var options = new ExecutionOptions { Schema = schema, Query = queryString, Inputs = inputs } .UseFluentValidation(validatorTypeCache); var executionResult = await executer.ExecuteAsync(options); #endregion }
//[InlineData("Combined")] public void CanSpecifyLiveData(string dataSource) { using (var remoteViewClient = Context.ViewProcessor.CreateClient()) { var pSpec = new LiveMarketDataSpecification(dataSource); var spec = pSpec; var options = new ExecutionOptions(new InfiniteViewCycleExecutionSequence(), ViewExecutionFlags.TriggersEnabled, null, new ViewCycleExecutionOptions(default(DateTimeOffset), spec)); //const string viewDefinitionName = "Primitives Only (Combined) 04f3f46f-15d5-48d9-a17e-848505d4246b"; const string viewDefinitionName = "Equity Option Test View 1"; var resultsEnum = remoteViewClient.GetResults(viewDefinitionName, options); var results = resultsEnum.Take(1).ToList(); Assert.True(results.All(r => r != null)); Console.Out.WriteLine("{0}: {1}", dataSource, string.Join(",", results.SelectMany(r => r.AllLiveData.Select(d => d.Specification.TargetSpecification.Uid.ToString())).OrderBy(u => u))); } }
public void apply_to_not_called_without_execute() { var docExec = new DocumentExecuter(); var schema = new Schema(); var execOptions = new ExecutionOptions { Schema = schema }; var mockMiddleware = new ApplyCounterMiddlewareBuilder(); schema.FieldMiddleware = mockMiddleware; // no execute in this test //docExec.ExecuteAsync(execOptions).Wait(); mockMiddleware.AppliedCount.ShouldBe(0); }
public async Task <IActionResult> Post([FromBody] GraphQLQuery query) { var executionOptions = new ExecutionOptions { Schema = _schema, Query = query.Query, Inputs = query.Variables.ToInputs(), UserContext = null, EnableMetrics = true, ExposeExceptions = true, }; var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(true); return(Ok(result)); }
protected async Task <ExecutionResult> BuildSchemaAndExecuteQueryAsync(GraphQLQuery query) { var schema = _serviceProvider.GetService <ISchema>(); var documentExecuter = _serviceProvider.GetService <IDocumentExecuter>(); var executionOptions = new ExecutionOptions { Schema = schema, Query = query.Query, Inputs = query.Variables.ToInputs() }; var result = await documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false); return(result); }
public async Task <IActionResult> Post([FromBody] GraphQLQuery query) { ExecutionOptions executionOptions = new ExecutionOptions { Schema = _schema, Query = query.Query }; ExecutionResult result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false); if (result.Errors?.Count > 0) { _logger.LogError("GraphQL errors: {0}", result.Errors); return(BadRequest()); } _logger.LogDebug("GraphQL execution result: {result}", JsonConvert.SerializeObject(result.Data)); return(Ok(result)); }
public async Task <IActionResult> Post([FromBody] GraphQLQuery query) { if (query == null) { throw new ArgumentNullException(nameof(query)); } var inputs = query.Variables.ToInputs(); var executionOptions = new ExecutionOptions { Schema = _schema, Query = query.Query, Inputs = inputs }; return(BadRequest("Não implementado")); }
public async Task <IActionResult> Post([FromBody] GraphQLQuery query) { var executionOptions = new ExecutionOptions { Schema = this._schema, Query = query.Query, Inputs = query.Variables.ToInputs(), EnableMetrics = true, ExposeExceptions = true, }; var result = await this._documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(true); Console.WriteLine(result); return(base.Ok(result)); }
private ExecutionOptions ValidateGraphQuery(GraphQlQuery graphQlQuery) { if (graphQlQuery is null) { throw new ArgumentNullException($"{nameof(graphQlQuery)} was not informed."); } var executionOptions = new ExecutionOptions { Schema = _schema, Query = graphQlQuery.Query, Inputs = graphQlQuery.Variables?.ToInputs() }; return(executionOptions); }
public void apply_to_called_once() { var docExec = new DocumentExecuter(); var execOptions = new ExecutionOptions { Schema = new Schema(), Query = "{ abcd }" }; var mockMiddleware = new ApplyCounterMiddlewareBuilder(); execOptions.FieldMiddleware = mockMiddleware; docExec.ExecuteAsync(execOptions).Wait(); mockMiddleware.AppliedCount.ShouldBe(1); }
public override TestResult Execute() { if (string.IsNullOrEmpty(Url)) { return(TestResult.ParameterMissing("Url")); } try { ExecutionOptions executionOptions = new ExecutionOptions(EnumExecutionType.SYNCHRONOUS, 0); DaSession session = new DaSession(ExpandProperty(Url)); if (!session.Valid) { return(TestResult.Failed("DaSession not Valid")); } // set the global prioperty no matter what SetProperty(Property, session); if (ForcedOpcSpecification != EnumOPCSpecification.DEFAULT) { session.ForcedOpcSpecification = ForcedOpcSpecification; } if (Connect) { int result = session.Connect(Deep, Active, executionOptions); if (ResultCode.FAILED(result)) { EnumResultCode resCode = (EnumResultCode)Enum.Parse(typeof(EnumResultCode), result.ToString()); return(TestResult.Failed(string.Format("Call returned: {0} ({1})", resCode.ToString(), result))); } } } catch (Exception ex) { if (ExpectedSuccess) { return(new TestResult(ex)); } } return(TestResult.Success()); }
public T Execute <T>(string queryText, object inputData = null, bool throwOnError = true) { var inputs = Inputs.Empty; if (inputData != null) { var inputAsJson = JsonConvert.SerializeObject(inputData); inputs = GraphQL.SystemTextJson.StringExtensions.ToInputs(inputAsJson); } var executer = _provider.GetRequiredService <IDocumentExecuter>(); var opts = new ExecutionOptions { Query = queryText, Schema = _schema, Inputs = inputs }; opts.Listeners.Add(_provider.GetRequiredService <DataLoaderDocumentListener>()); var resultAsync = executer.ExecuteAsync(opts); var executionResult = resultAsync.Result; if (executionResult.Errors != null && executionResult.Errors.Count > 0 && throwOnError) { throw new InvalidOperationException("Errors found: " + JArray.FromObject(executionResult.Errors).ToString()); } var data = JObject.FromObject(executionResult.Data); if (!throwOnError) { data = new JObject( new JProperty("data", data), new JProperty("errors", JArray.FromObject(executionResult.Errors ?? new ExecutionErrors())) ); } if (typeof(T) == typeof(string)) { return((T)(object)(data.ToString())); } if (typeof(T) == typeof(JObject)) { return((T)(object)data); } return(data.ToObject <T>()); }
public async Task Mutate_add_human_leia() { /* Given */ var starwars = new Starwars(); var query = @" mutation { addHuman(human: {name:""Leia""}) { id name homePlanet friends { name } } } "; var executableSchema = await _fixture.CreateSchema(starwars); var options = new ExecutionOptions { Schema = executableSchema, Document = query, OperationName = null, InitialValue = null, VariableValues = null }; /* When */ var actual = await ExecuteAsync(options).ConfigureAwait(false); /* Then */ actual.ShouldMatchJson( @"{ ""data"": { ""addHuman"": { ""id"": ""humans/leia"", ""name"": ""Leia"", ""homePlanet"": null, ""friends"": [] } } }"); }
public async Task Query_typename_of_character_luke() { /* Given */ var starwars = new Starwars(); var id = "\"humans/luke\""; var query = $@"{{ character(id: {id}) {{ __typename id name appearsIn }} }}"; var executableSchema = await _fixture.CreateSchema(starwars); var options = new ExecutionOptions { Schema = executableSchema, Document = query, OperationName = null, InitialValue = null, VariableValues = null }; /* When */ var actual = await ExecuteAsync(options).ConfigureAwait(false); /* Then */ actual.ShouldMatchJson( @"{ ""data"": { ""character"": { ""__typename"":""Human"", ""id"": ""humans/luke"", ""name"": ""Luke"", ""appearsIn"": [ ""JEDI"", ""EMPIRE"", ""NEWHOPE"" ] } } }"); }
public async Task <IActionResult> Post([FromBody] GraphQlQuery query) { var executionOptions = new ExecutionOptions { Schema = _schema, Query = query.Query }; var result = await _documentExecuter.ExecuteAsync(executionOptions); if (result.Errors?.Count > 0) { return(BadRequest(result)); } return(Ok(result)); }
private async Task <IntrospectionQueryData> GetSchemaAsync(ISchema schema) { var options = new ExecutionOptions { Schema = schema, Query = IntrospectionQuery.GetQuery() }; var result = await _documentExecuter.ExecuteAsync(options); using var stream = new MemoryStream(); await _documentWriter.WriteAsync(stream, result); stream.Position = 0; var response = await IntrospectionQuery.DeserializeAsync(stream); return(response?.Data); }
/// <inheritdoc /> public override bool Equals(object obj) { ExecutionOptions executionOptions = obj as ExecutionOptions; if (object.ReferenceEquals((object)executionOptions, (object)null) || this.MergeOption != executionOptions.MergeOption) { return(false); } bool?specifiedStreaming1 = this.UserSpecifiedStreaming; bool?specifiedStreaming2 = executionOptions.UserSpecifiedStreaming; if (specifiedStreaming1.GetValueOrDefault() == specifiedStreaming2.GetValueOrDefault()) { return(specifiedStreaming1.HasValue == specifiedStreaming2.HasValue); } return(false); }
protected async Task <ExecutionResult> ExecuteSubscribeAsync(ExecutionOptions options) { var executer = new DocumentExecuter(); var services = new ServiceCollection(); services.AddSingleton <IChat>(Chat); var provider = services.BuildServiceProvider(); options.Schema = new SubscriptionSchemaWithAutoGraphType(); options.RequestServices = provider; var result = await executer.ExecuteAsync(options).ConfigureAwait(false); result.Data.ShouldBeNull(); return(result); }
BuildQueryContextAsync( ExecutionOptions options, ExtensionsRunner extensionsRunner, ILogger logger) { await extensionsRunner.BeginParseDocumentAsync(); var document = options.Document; await extensionsRunner.EndParseDocumentAsync(document); var operation = Operations.GetOperation(document, options.OperationName); logger.Operation(operation); var coercedVariableValues = Variables.CoerceVariableValues( options.Schema, operation, options.VariableValues); var queryContext = new QueryContext( options.FormatError, document, operation, options.Schema, coercedVariableValues, options.InitialValue, extensionsRunner); logger.Validate(options.Validate != null); var validationResult = ValidationResult.Success; if (options.Validate != null) { await extensionsRunner.BeginValidationAsync(); validationResult = await options.Validate( options.Schema, document, coercedVariableValues); logger.ValidationResult(validationResult); await extensionsRunner.EndValidationAsync(validationResult); } return(queryContext, validationResult); }
public int InitializeAeObjects(string url) { int connectResult = (int)EnumResultCode.E_FAIL; m_executionOptions = new ExecutionOptions(); m_executionOptions.ExecutionType = EnumExecutionType.ASYNCHRONOUS; m_executionOptions.ExecutionContext = 0; try { m_aeSession = new MyAeSession(url); m_aeSubscription = new MyAeSubscription(m_aeSession); connectResult = m_aeSession.Connect(true, false, new ExecutionOptions()); uint[] categoryIds = new uint[] { (uint)CategoriesAndAttribute.Categories.System_alarm, (uint)CategoriesAndAttribute.Categories.Process_alarm, (uint)CategoriesAndAttribute.Categories.Operation_record }; m_aeSubscription.FilterCategories = categoryIds; AeReturnedAttributes[] returnedAttributes = new AeReturnedAttributes[categoryIds.Length]; for (int i = 0; i < categoryIds.Length; i++) { List <uint> temp = CategoriesAndAttribute.getAttributeIDsFromCategoryID(categoryIds[i]); uint[] attributeIds = new uint[temp.Count]; attributeIds = temp.ToArray(); returnedAttributes[i] = new AeReturnedAttributes(); returnedAttributes[i].AttributeIds = attributeIds; returnedAttributes[i].CategoryId = categoryIds[i]; } m_aeSubscription.ReturnedAttributes = returnedAttributes; } catch (Exception exc) { GetApplication().Trace( EnumTraceLevel.ERR, EnumTraceGroup.USER, "OpcClient::InitializeAeObjects", exc.ToString()); } // end try...catch return(connectResult); } // end InitializeAeObjects
public async Task <SubscriptionExecutionResult> Subscribe(GraphQLDocument bdy, object context) { var executionOptions = new ExecutionOptions { Schema = _schema, Query = bdy.Query, OperationName = bdy.OperationName, Inputs = bdy.Variables.ToInputs(), ExposeExceptions = false, UserContext = context }; // call ChatSubscription's subscriber var result = await _subscriptionExecuter.SubscribeAsync(executionOptions); return(result); }
/// <summary> /// Load the query synchronously. <see cref="Cancellation"/> is used for cancellation /// token, <see cref="Progress"/> is used for reporting progress. /// </summary> /// <remarks> /// Found entities are added to a waiting queue. Use <see cref="Update"/> to get all /// entities loaded so far. /// </remarks> /// <seealso cref="RunAsync"/> public void Run() { var progress = AggregateProgress.Create( Progress, new FolderQueryProgress(_fileWatcher)); var options = new ExecutionOptions { CancellationToken = Cancellation.Token, Progress = progress }; foreach (var entity in Query.Execute(options)) { var thumbnail = _thumbnailFactory.Create(entity, Cancellation.Token); EnqueueRequest(new AddRequest(new EntityView(entity, thumbnail))); } }
// POST api/values public async Task<dynamic> Post([FromBody]Script script) { var scriptId = Guid.NewGuid(); using (var scope = new ManagerScope()) { dynamic host = new ExpandoObject(); //var host = new TestModel(); var option = new ExecutionOptions { HostObjects = new List<HostObject> {new HostObject {Name = "host", Target = host}} }; //var engine = new V8ScriptEngine(); //engine.AddHostObject("host", HostItemFlags.None, host); //engine.Execute(script.Text); await scope.RuntimeManager.ExecuteAsync(scriptId.ToString(), script.Text, option); return host; } }
public void ExecuteServiceByName(string correlationId, string repositoryName, string serviceName, ExecutionOptions options, System.IO.Stream inStream, System.IO.Stream outStream) { if (serviceName == "receive-pack") { var resultFilePath = resultFilePathBuilder.GetPathToResultFile(correlationId, repositoryName, serviceName); using (var resultFileStream = File.OpenWrite(resultFilePath)) { this.gitService.ExecuteServiceByName(correlationId, repositoryName, serviceName, options, inStream, new ReplicatingStream(outStream, resultFileStream)); } // only on successful execution remove the result file if (File.Exists(resultFilePath)) { File.Delete(resultFilePath); } } else { this.gitService.ExecuteServiceByName(correlationId, repositoryName, serviceName, options, inStream, outStream); } }
public static ScriptEngine ApplyOptions(this ScriptEngine engine, ExecutionOptions options) { if (options != null) { if (options.HostObjects != null) { foreach (HostObject hostObject in options.HostObjects) { engine.AddHostObject(hostObject); } } if (options.HostTypes != null) { foreach (HostType hostType in options.HostTypes) { engine.AddHostType(hostType); } } } return engine; }
public async void Basic_Http_Get_Headers_Are_Retrieved() { var subject = new TestObject(); var manager = new RuntimeManager(new ManualManagerSettings { ScriptTimeoutMilliSeconds = 0 }); PackageHelpers.RegisterRequestPackages(); manager.AddConsoleReference = true; var options = new ExecutionOptions(); options.HostObjects.Add(new HostObject { Name = "subject", Target = subject }); var scriptAwaiter = new ScriptAwaiter(); options.HostObjects.Add(new HostObject { Name = "scriptAwaiter", Target = scriptAwaiter }); var code = "var request = require('request');" + "request({url: 'http://api.icndb.com/jokes/random/1', json: true}," + " function (error, response, body) {subject.Response = response; subject.Headers = response.headers; scriptAwaiter.Callback();});"; await manager.ExecuteAsync("testScript", code, options); await scriptAwaiter.T; subject.Headers.Count().ShouldBeGreaterThan(0); }
private Collection<PSObject> ExecutePipeline(ExecutionOptions options, Pipeline tempPipeline, Collection<PSObject> collection, out Exception exceptionThrown) { exceptionThrown = null; try { bool acquired = Monitor.TryEnter(_runspace); if (! acquired) { return null; } try { WaitWhileRunspaceIsBusy(); _currentPipeline = tempPipeline; try { tempPipeline.InvokeAsync(); tempPipeline.Input.Close(); WaitWhilePipelineIsRunning(tempPipeline); } finally { _currentPipeline = null; } var exception = GetPipelineError(options, tempPipeline); collection = tempPipeline.Output.ReadToEnd(); if (null != exception) { RaisePipelineExceptionEvent(exception); } } finally { Monitor.Exit(_runspace); } } catch (Exception exception) { exceptionThrown = exception; } return collection; }
private Exception GetPipelineError(ExecutionOptions options, Pipeline tempPipeline) { Exception pipelineException = null; if (null != tempPipeline.PipelineStateInfo.Reason) { pipelineException = tempPipeline.PipelineStateInfo.Reason; } if (null == pipelineException && 0 < tempPipeline.Error.Count) { var error = tempPipeline.Error.Read(); pipelineException = error as Exception; if (null == pipelineException) { pipelineException = ((ErrorRecord) error).Exception; } } if (null != pipelineException && 0 == (options & ExecutionOptions.AddOutputter)) { throw pipelineException; } return pipelineException; }
private IEnumerable<ErrorRecord> GetPipelineErrors(ExecutionOptions options, Pipeline tempPipeline) { List<ErrorRecord> pipelineErrors = new List<ErrorRecord>(); if ( 0 < tempPipeline.Error.Count) { var error = tempPipeline.Error.Read(); var errorRecord = error.ToPSObject().BaseObject as ErrorRecord; if (null == errorRecord) { errorRecord = new ErrorRecord( error as Exception, "", ErrorCategory.CloseError, null); } if (null != errorRecord) { pipelineErrors.Add(errorRecord); } } return pipelineErrors; }
private static void ExecutePipeline(ExecutionOptions options, Pipeline tempPipeline) { //if (options.HasFlag(ExecutionOptions.Synchronous)) //{ // tempPipeline.Invoke(); //} //else { tempPipeline.InvokeAsync(); } }
private Collection<PSObject> ExecutePipeline(ExecutionOptions options, Pipeline tempPipeline, Collection<PSObject> collection, out IEnumerable<ErrorRecord> exceptionThrown) { exceptionThrown = null; try { bool acquired = Monitor.TryEnter(_runspace); if (! acquired) { return null; } try { _currentPipeline = tempPipeline; IEnumerable<ErrorRecord> exception = null; try { WaitWhileRunspaceIsBusy(); tempPipeline.StateChanged += OnPipelineStateChange; try { ExecutePipeline(options, tempPipeline); } catch (PSInvalidOperationException ioe) { /* * HACK: there seems to be some lag between the toggle of the runspace * availability state and the clearing of the runspace's current * pipeline state. it's possible for the runspace to report it's available * for use and then raise a PSInvalidOperationException indicating that another * pipeline is currently executing. * * This is a hacky way around the issue - wait 1/3 of a second for the * runspace state to clear and try again. * * I've also tried adding a WaitWhilePipelineIsRunning method that spins * on a DoWait while the pipeline is not in the completed or failed state; * however this seems to slow the execution down considerably. */ if (tempPipeline.PipelineStateInfo.State == PipelineState.NotStarted) { Thread.Sleep(333); ExecutePipeline(options, tempPipeline); } } tempPipeline.Input.Close(); // WaitWhilePipelineIsRunning(tempPipeline); collection = tempPipeline.Output.ReadToEnd(); if (null != tempPipeline.PipelineStateInfo.Reason) { throw tempPipeline.PipelineStateInfo.Reason; } exception = GetPipelineErrors(options, tempPipeline); } catch( RuntimeException re ) { exception = new ErrorRecord[]{re.ErrorRecord}; } catch( Exception e ) { exception = new ErrorRecord[] { new ErrorRecord( e, e.GetType().FullName, ErrorCategory.NotSpecified, null), }; } finally { _currentPipeline = null; } if (null != exception) { if (!options.HasFlag(ExecutionOptions.DoNotRaisePipelineException)) { exception.ToList().ForEach( RaisePipelineExceptionEvent ); } exceptionThrown = exception; } } finally { Monitor.Exit(_runspace); } } catch (Exception ex) { exceptionThrown = new ErrorRecord[] { new ErrorRecord( ex, ex.GetType().FullName, ErrorCategory.NotSpecified, null), }; } return collection; }
private static void ApplyExecutionOptionsToPipeline(ExecutionOptions options, Pipeline tempPipeline) { if ((options & ExecutionOptions.AddOutputter) != ExecutionOptions.None) { if (tempPipeline.Commands.Count == 1) { tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } var item = new Command("Out-Default", false, true); tempPipeline.Commands.Add(item); } }
internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(!useNestedPipelines, "can't async invoke a nested pipeline"); Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); bool addToHistory = (options & ExecutionOptions.AddToHistory) > 0; Pipeline tempPipeline = _parent.RunspaceRef.CreatePipeline(command, addToHistory, false); ExecuteCommandAsyncHelper(tempPipeline, out exceptionThrown, options); }
public Collection<PSObject> ExecuteCommand(string command, out IEnumerable<ErrorRecord> error, ExecutionOptions options) { var pipe = _runspace.CreatePipeline(command, ExecutionOptions.None != (ExecutionOptions.AddToHistory & options)); return ExecuteCommandHelper(pipe, out error, options); }
public Collection<PSObject> ExecuteCommand(string command, Dictionary<string, object> inputs, out IEnumerable<ErrorRecord> error, ExecutionOptions options) { var isscript = null == inputs || !inputs.Any(); var cmd = new Command(command, isscript, false); if (null != inputs && inputs.Any()) { inputs.ToList().ForEach(pair => cmd.Parameters.Add(pair.Key, pair.Value)); } var pipe = _runspace.CreatePipeline(); pipe.Commands.Add(cmd); return ExecuteCommandHelper(pipe, out error, options); }
private Collection<PSObject> ExecuteCommand(string command, Dictionary<string, object> parameters, ExecutionOptions executionOptions) { IEnumerable<ErrorRecord> e; var r = ExecuteCommand(command, parameters, executionOptions, out e); if( null != e ) { throw e.First().Exception; } return r; }
/// <summary> /// /// All calls to the Runspace to execute a command line must be done with this function, which properly synchronizes /// access to the running pipeline between the main thread and the break handler thread. This synchronization is /// necessary so that executions can be aborted with Ctrl-C (including evaluation of the prompt and collection of /// command-completion candidates. /// /// On any given Executor instance, ExecuteCommand should be called at most once at a time by any one thread. It is NOT /// reentrant. /// /// </summary> /// <param name="command"> /// /// The command line to be executed. Must be non-null. /// /// </param> /// <param name="exceptionThrown"> /// /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null. /// Can be tested to see if the execution was successful or not. /// /// </param> /// <param name="options"> /// /// options to govern the execution /// /// </param> /// <returns> /// /// the object stream resulting from the execution. May be null. /// /// </returns> internal Collection<PSObject> ExecuteCommand(string command, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0); return ExecuteCommandHelper(tempPipeline, out exceptionThrown, options); }
internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(!_isPromptFunctionExecutor, "should not async invoke the prompt"); exceptionThrown = null; Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; lock (_instanceStateLock) { Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } try { if ((options & ExecutionOptions.AddOutputter) > 0 && _parent.OutputFormat == Serialization.DataFormat.Text) { // Tell the script command to merge it's output and error streams if (tempPipeline.Commands.Count == 1) { tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } // then add out-default to the pipeline to render everything... Command outDefault = new Command("Out-Default", /* isScript */false, /* useLocalScope */ true); tempPipeline.Commands.Add(outDefault); } tempPipeline.Output.DataReady += new EventHandler(OutputObjectStreamHandler); tempPipeline.Error.DataReady += new EventHandler(ErrorObjectStreamHandler); PipelineFinishedWaitHandle waiterThereIsAFlyInMySoup = new PipelineFinishedWaitHandle(tempPipeline); tempPipeline.InvokeAsync(); if ((options & ExecutionOptions.ReadInputObjects) > 0 && Console.IsInputRedirected) { // read input objects from stdin WrappedDeserializer des = new WrappedDeserializer(_parent.InputFormat, "Input", Console.In); while (!des.AtEnd) { object o = des.Deserialize(); if (o == null) { break; } try { tempPipeline.Input.Write(o); } catch (PipelineClosedException) { //This exception can occurs when input is closed. This can happen //for various reasons. For ex:Command in the pipeline is invalid and //command discovery throws exception which closes the pipeline and //hence the Input pipe. break; } }; des.End(); } tempPipeline.Input.Close(); waiterThereIsAFlyInMySoup.Wait(); //report error if pipeline failed if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null) { if (_parent.OutputFormat == Serialization.DataFormat.Text) { //Report the exception using normal error reporting exceptionThrown = tempPipeline.PipelineStateInfo.Reason; } else { //serialize the error record AsyncPipelineFailureHandler(tempPipeline.PipelineStateInfo.Reason); } } } catch (Exception e) { ConsoleHost.CheckForSevereException(e); exceptionThrown = e; } finally { // Once we have the results, or an exception is thrown, we throw away the pipeline. _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } }
/// <summary> /// Called via a javascript to require and return the requested package. /// </summary> /// <param name="packageId">ID of the RequirePackage to require.</param> /// <param name="scriptUri">A script uri. This is only needed if the packageId doesn't meet the script convention name and the package is not a registered package.</param> /// <returns>The return object to use for the require. Either the export from the require script or the returned HostObject if not script is present.</returns> public object Require(string packageId, string scriptUri) { RequiredPackage package; bool hasUri = !String.IsNullOrEmpty(scriptUri); bool packageCreated = false; if (packageId.Contains("/") || packageId.Contains("\\")) { if (!hasUri) { scriptUri = packageId; hasUri = true; } packageId = DerivePackageIdFromUri(scriptUri); if (packageId.Length == 0) throw new ArgumentException( "The provided packageId is not a valid package name. The packageId must be a valid file path or uri if path characters are contained in the name."); } if (!RequireManager.TryGetPackage(packageId, out package)) { if (!hasUri) { throw new KeyNotFoundException(String.Format("The package with ID {0} was not found, did you register this package?", packageId)); } package = new RequiredPackage {PackageId = packageId, ScriptUri = scriptUri}; packageCreated = true; } var options = new ExecutionOptions { HostObjects = package.HostObjects, HostTypes = package.HostTypes }; Engine.ApplyOptions(options); if (!String.IsNullOrEmpty(package.ScriptUri)) { var compiledScript = Compiler.Compile(new IncludeScript {Uri = package.ScriptUri, PrependCode = "var " + packageId + " = {};"}); Engine.Execute(compiledScript); var outputObject = DynamicExtensions.GetProperty(Engine.Script, packageId); if (outputObject is Undefined) { //try to find pascal case if camel is not present. outputObject = DynamicExtensions.GetProperty(Engine.Script, packageId.ToPascalCase()); } if (packageCreated) { RequireManager.RegisterPackage(package); } return outputObject.exports; } if (options.HostObjects.SafeAny()) return options.HostObjects[0]; return null; }
private Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out IEnumerable<ErrorRecord> exceptionThrown, ExecutionOptions options) { exceptionThrown = null; Collection<PSObject> collection = null; ApplyExecutionOptionsToPipeline(options, tempPipeline); collection = ExecutePipeline(options, tempPipeline, collection, out exceptionThrown); return collection; }
private Collection<PSObject> ExecuteCommand(string input, ExecutionOptions executionOptions) { Exception error; var onx = CommandExecutionStateChange; if (null != onx) { onx(this, new EventArgs<bool>(true)); } var results = _commandExecutor.ExecuteCommand( input, out error, executionOptions ); if (null != onx) { onx(this, new EventArgs<bool>(false)); } return results; }
public static bool HasFlag(this ExecutionOptions options, ExecutionOptions flag) { return flag == (options & flag); }
public void ExecuteServiceByName(string correlationId, string repositoryName, string serviceName, ExecutionOptions options, System.IO.Stream inStream, System.IO.Stream outStream) { ParsedReceivePack receivedPack = null; if (serviceName == "receive-pack" && inStream.Length > 0) { // PARSING RECEIVE-PACK THAT IS OF THE FOLLOWING FORMAT: // (NEW LINES added for ease of reading) // (LLLL is length of the line (expressed in HEX) until next LLLL value) // // LLLL------ REF LINE -----------\0------- OHTER DATA ----------- // LLLL------ REF LINE ---------------- // ... // ... // 0000PACK------- REST OF PACKAGE -------- // var pktLines = new List<ReceivePackPktLine>(); var buff1 = new byte[1]; var buff4 = new byte[4]; var buff20 = new byte[20]; var buff16K = new byte[1024 * 16]; while (true) { ReadStream(inStream, buff4); var len = Convert.ToInt32(Encoding.UTF8.GetString(buff4), 16); if (len == 0) { break; } len = len - buff4.Length; var accum = new LinkedList<byte>(); while (len > 0) { len -= 1; ReadStream(inStream, buff1); if (buff1[0] == 0) { break; } accum.AddLast(buff1[0]); } if (len > 0) { inStream.Seek(len, SeekOrigin.Current); } var pktLine = Encoding.UTF8.GetString(accum.ToArray()); var pktLineItems = pktLine.Split(' '); var fromCommit = pktLineItems[0]; var toCommit = pktLineItems[1]; var refName = pktLineItems[2]; pktLines.Add(new ReceivePackPktLine(fromCommit, toCommit, refName)); } // parse PACK contents var packCommits = new List<ReceivePackCommit>(); // PACK format // https://www.kernel.org/pub/software/scm/git/docs/technical/pack-format.html // http://schacon.github.io/gitbook/7_the_packfile.html if (inStream.Position < inStream.Length) { ReadStream(inStream, buff4); if (Encoding.UTF8.GetString(buff4) != "PACK") { throw new Exception("Unexpected receive-pack 'PACK' content."); } ReadStream(inStream, buff4); Array.Reverse(buff4); var versionNum = BitConverter.ToInt32(buff4, 0); ReadStream(inStream, buff4); Array.Reverse(buff4); var numObjects = BitConverter.ToInt32(buff4, 0); while (numObjects > 0) { numObjects -= 1; ReadStream(inStream, buff1); var type = (GIT_OBJ_TYPE)((buff1[0] >> 4) & 7); long len = buff1[0] & 15; var shiftAmount = 4; while ((buff1[0] >> 7) == 1) { ReadStream(inStream, buff1); len = len | ((long)(buff1[0] & 127) << shiftAmount); shiftAmount += 7; } if (type == GIT_OBJ_TYPE.OBJ_REF_DELTA) { // read ref name ReadStream(inStream, buff20); } if (type == GIT_OBJ_TYPE.OBJ_OFS_DELTA) { // read negative offset ReadStream(inStream, buff1); while ((buff1[0] >> 7) == 1) { ReadStream(inStream, buff1); } } var origPosition = inStream.Position; long offsetVal = 0; using (var zlibStream = new ZlibStream(inStream, CompressionMode.Decompress, true)) { // read compressed data max 16KB at a time var readRemaining = len; do { var bytesUncompressed = zlibStream.Read(buff16K, 0, buff16K.Length); readRemaining -= bytesUncompressed; } while (readRemaining > 0); if (type == GIT_OBJ_TYPE.OBJ_COMMIT) { var parsedCommit = ParseCommitDetails(buff16K, len); packCommits.Add(parsedCommit); } offsetVal = zlibStream.TotalIn; } // move back position a bit because ZLibStream reads more than needed for inflating inStream.Seek(origPosition + offsetVal, SeekOrigin.Begin); } } // ------------------- var user = HttpContext.Current.User.Identity.Name; receivedPack = new ParsedReceivePack(correlationId, repositoryName, pktLines, user, DateTime.Now, packCommits); inStream.Seek(0, SeekOrigin.Begin); receivePackHandler.PrePackReceive(receivedPack); } GitExecutionResult execResult = null; using (var capturedOutputStream = new MemoryStream()) { gitService.ExecuteServiceByName(correlationId, repositoryName, serviceName, options, inStream, new ReplicatingStream(outStream, capturedOutputStream)); // parse captured output capturedOutputStream.Seek(0, SeekOrigin.Begin); execResult = resultParser.ParseResult(capturedOutputStream); } if(receivedPack != null) { receivePackHandler.PostPackReceive(receivedPack, execResult); } }
private Collection<PSObject> ExecuteCommand(string command, Dictionary<string, object> arguments, ExecutionOptions options) { Exception error; var onx = CommandExecutionStateChange; if (null != onx) { onx(this, new EventArgs<bool>(true)); } var results = _commandExecutor.ExecuteCommand( command, arguments, out error, options ); if (null != onx) { onx(this, new EventArgs<bool>(false)); } return results; }
public Collection<PSObject> OutputObjects(IEnumerable<object> inputs, out IEnumerable<ErrorRecord> error, ExecutionOptions options) { var pipe = _runspace.CreatePipeline(); if (null != inputs && inputs.Any()) { pipe.Input.Write(inputs, true); } return ExecuteCommandHelper(pipe, out error, options); }
internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(tempPipeline != null, "command should have a value"); exceptionThrown = null; Collection<PSObject> results = null; if ((options & ExecutionOptions.AddOutputter) > 0) { if (tempPipeline.Commands.Count < 2) { if (tempPipeline.Commands.Count == 1) { // Tell the script command to merge it's output and error streams. tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } // Add Out-Default to the pipeline to render. tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false)); } else { // For multiple commands/scripts we need to insert Out-Default at the end of each statement. CommandCollection executeCommands = new CommandCollection(); foreach (var cmd in tempPipeline.Commands) { executeCommands.Add(cmd); if (cmd.IsEndOfStatement) { // End of statement needs to pipe to Out-Default. cmd.IsEndOfStatement = false; executeCommands.Add(GetOutDefaultCommand(endOfStatement: true)); } } var lastCmd = executeCommands.Last(); if (!((lastCmd.CommandText != null) && (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase))) ) { // Ensure pipeline output goes to Out-Default. executeCommands.Add(GetOutDefaultCommand(endOfStatement: false)); } tempPipeline.Commands.Clear(); foreach (var cmd in executeCommands) { tempPipeline.Commands.Add(cmd); } } } Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; lock (_instanceStateLock) { Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } try { // blocks until all results are retrieved. results = tempPipeline.Invoke(); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); exceptionThrown = e; } finally { // Once we have the results, or an exception is thrown, we throw away the pipeline. _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } return results; }
private Collection<PSObject> ExecuteCommand(string script, ExecutionOptions executionOptions, out IEnumerable<ErrorRecord> error ) { error = null; Exception exception; if (_shellConfiguration.IsUnsupportedConsoleApplication( script, out exception )) { error = new ErrorRecord[] { new ErrorRecord( exception, "UnsupportedApplication", ErrorCategory.ResourceUnavailable, script) }; return null; } var onx = CommandExecutionStateChange; if (null != onx) { onx(this, new EventArgs<bool>(true)); } var results = _commandExecutor.ExecuteCommand( script, out error, executionOptions ); if (null != onx) { onx(this, new EventArgs<bool>(false)); } return results; }
public Collection<PSObject> ExecuteCommand(string command, Dictionary<string, object> inputs, out Exception error, ExecutionOptions options) { var cmd = new Command(command, true, false); if (null != inputs && inputs.Any()) { Debug.Fail("inputs are not supported - fix calling code"); //inputs.ToList().ForEach(pair => // cmd.Parameters.Add(pair.Key, pair.Value)); } var pipe = _runspace.CreatePipeline(); pipe.Commands.Add(cmd); return ExecuteCommandHelper(pipe, out error, options); }