private static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType) { SessionStateScope scope; SessionStateInternal engineSessionState = executionContext.EngineSessionState; CommandOrigin scopeOrigin = engineSessionState.CurrentScope.ScopeOrigin; PSVariable variable = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin); if (variable == null) { throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null, "NonExistingVariableReference", ParserStrings.NonExistingVariableReference, new object[0]); } object obj2 = variable.Value; if ((staticType == null) && (obj2 != null)) { obj2 = PSObject.Base(obj2); if (obj2 != null) { staticType = obj2.GetType(); } } if (staticType == null) { ArgumentTypeConverterAttribute attribute = variable.Attributes.OfType<ArgumentTypeConverterAttribute>().FirstOrDefault<ArgumentTypeConverterAttribute>(); staticType = (attribute != null) ? attribute.TargetType : typeof(LanguagePrimitives.Null); } return PSReference.CreateInstance(variable, staticType); }
protected override void ExecuteImpl(ExecutionContext context) { byte[] result; switch (OpCode) { case ScriptOpCode.OP_RIPEMD160: result = CryptoFunctionProviderFactory.Default.Ripemd160(context.ValueStack.Peek()).Bytes; break; case ScriptOpCode.OP_SHA1: result = CryptoFunctionProviderFactory.Default.Sha1(context.ValueStack.Peek()).Bytes; break; case ScriptOpCode.OP_SHA256: result = CryptoFunctionProviderFactory.Default.Sha256(context.ValueStack.Peek()).Bytes; break; case ScriptOpCode.OP_HASH160: result = CryptoFunctionProviderFactory.Default.Hash160(context.ValueStack.Peek()).Bytes; break; case ScriptOpCode.OP_HASH256: result = CryptoFunctionProviderFactory.Default.Hash256(context.ValueStack.Peek()).Bytes; break; default: context.HardFailure = true; return; } context.ValueStack.Pop(); context.ValueStack.Push(result); }
internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionContext, out object value) { bool flag; if (!((bool) ast.Accept(new SafeExprEvaluator()))) { value = null; return false; } PSLanguageMode? nullable = null; try { if (ExecutionContext.HasEverUsedConstrainedLanguage) { nullable = new PSLanguageMode?(executionContext.LanguageMode); executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } value = Compiler.GetExpressionValue(ast, executionContext, (IList)null); flag = true; } catch { value = null; flag = false; } finally { if (nullable.HasValue) { executionContext.LanguageMode = nullable.Value; } } return flag; }
private static object GetUsingValue(MutableTuple tuple, int index, ExecutionContext context) { UsingResult usingValueFromTuple = GetUsingValueFromTuple(tuple, index); if (usingValueFromTuple != null) { return usingValueFromTuple.Value; } for (SessionStateScope scope = context.EngineSessionState.CurrentScope; scope != null; scope = scope.Parent) { usingValueFromTuple = GetUsingValueFromTuple(scope.LocalsTuple, index); if (usingValueFromTuple != null) { return usingValueFromTuple.Value; } foreach (MutableTuple tuple2 in scope.DottedScopes) { usingValueFromTuple = GetUsingValueFromTuple(tuple2, index); if (usingValueFromTuple != null) { return usingValueFromTuple.Value; } } } throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand, new object[0]); }
private static void appendNativeArguments(ExecutionContext context, StringBuilder argumentBuilder, object arg) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arg); bool flag = false; if (enumerator == null) { appendOneNativeArgument(context, argumentBuilder, true, arg); } else { while (enumerator.MoveNext()) { object current = enumerator.Current; string name = string.Empty; if (current != null) { name = current.ToString(); } if (flag) { argumentBuilder.Append(" "); name = Environment.ExpandEnvironmentVariables(name); argumentBuilder.Append(name); } else if (string.Equals("--%", name, StringComparison.OrdinalIgnoreCase)) { flag = true; } else { appendOneNativeArgument(context, argumentBuilder, true, current); } } } }
public IObservable<Unit> ExecuteAsync(ExecutionContext context) { context.AssertNotNull(nameof(context)); var childExecutions = this .children .Select( child => Observable .Return(Unit.Default) .Select( _ => { context.CancellationToken.ThrowIfCancellationRequested(); var execute = true; if (context.SkipAhead > TimeSpan.Zero && context.SkipAhead >= child.Duration) { context.AddProgress(child.Duration); execute = false; } return new { Child = child, Execute = execute }; }) .Where(x => x.Execute) .SelectMany(x => x.Child.ExecuteAsync(context))) .DefaultIfEmpty(Observable.Return(Unit.Default)); return Observable .Concat(childExecutions) .RunAsync(context.CancellationToken); }
protected override void ExecuteStatement(ExecutionContext context) { if (!context.DirectAccess.TriggerExists(TriggerName)) throw new ObjectNotFoundException(TriggerName); //if (!context.User.CanAlter(DbObjectType.Trigger, TriggerName)) // throw new MissingPrivilegesException(context.User.Name, TriggerName, Privileges.Alter); var trigger = context.DirectAccess.GetObject(DbObjectType.Trigger, TriggerName) as Trigger; if (trigger == null) throw new ObjectNotFoundException(TriggerName); var triggerInfo = trigger.TriggerInfo; if (Action.ActionType == AlterTriggerActionType.Rename) { var action = (RenameTriggerAction) Action; triggerInfo = triggerInfo.Rename(action.Name); if (!context.DirectAccess.DropTrigger(TriggerName)) throw new InvalidOperationException(String.Format("Could not drop the trigger '{0}' to rename", TriggerName)); context.DirectAccess.CreateTrigger(triggerInfo); } else if (Action.ActionType == AlterTriggerActionType.ChangeStatus) { var action = (ChangeTriggerStatusAction) Action; triggerInfo.Status = action.Status; context.DirectAccess.AlterObject(triggerInfo); } }
public override object Execute(object[] args, ExecutionContext ctx) { ArgumentChecker checker = new ArgumentChecker(this.GetType().Name); checker.CheckForNumberOfArguments(ref args, 1, null); decimal d = Convert.ToDecimal(args[0]); return Math.Sign(d) * Math.Floor(Math.Abs(d)); }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { double lengthConversion = ActiveWindow.Units.Length.ConversionFactor; bool isImperial = Booleans[Resources.IsImperial].Value; bool isInternal = Booleans[Resources.ThreadIsInternal].Value; double pitch = isImperial ? (Const.inches / Values[Resources.ThreadPitch].Value) : (1E-3 * Values[Resources.ThreadPitch].Value); double angle = Values[Resources.ThreadAngle].Value * Math.PI / 180; Body[] bodies = SpaceClaimExtensions.GetAllSelectedIDesignFaces(Window.ActiveWindow) .Where(f => f.Shape.Geometry is Cylinder) .Select(f => f.Master.Parent.Shape.CopyFaces(new[] { f.Master.Shape })) .Select(b => b.Faces.First()) .Select(f => CreateThreads(f, pitch, angle, isInternal)) .ToArray(); Part part = Window.ActiveWindow.Scene as Part; foreach (Body body in bodies) DesignBody.Create(part, Resources.ThreadStructureText, body); Settings.Default.IsImperial = isImperial; Settings.Default.IsInternal = isInternal; Settings.Default.Pitch = isImperial ? 0.0254 / pitch : pitch / 1E3; Settings.Default.Angle = angle * 180 / Math.PI; Settings.Default.Save(); }
public override void Execute(ExecutionContext context) { if (context.CurrentBlockWeb != null && ownerBlockId == null) { throw new Exception("You cannot nest standalone blockWebs"); } IBlockWeb newWeb = null; IBlockWeb oldWeb = context.CurrentBlockWeb; if (ownerBlockId != null) { newWeb = (IBlockWeb)context.CurrentBlockWeb[ownerBlockId].ProcessRequest("ProcessMetaService", BlockMetaServiceType.GetInnerWeb, null, null); } else { newWeb = new BlockWeb(webId, context.Broker); } context.CurrentBlockWeb = newWeb; if (webId != null) { context.blockWebs[webId] = newWeb; } base.Execute(context); context.CurrentBlockWeb = oldWeb; }
internal ScriptBlockParameterBinder(ReadOnlyCollection<ParameterAst> scriptParameters, ExecutionContext context, ExecutionVisitor executionVisitor) { _scriptParameters = scriptParameters; _executionContext = context; _executionVisitor = executionVisitor; }
public void execute_executes_each_child_action() { var action1 = new ActionMock(MockBehavior.Loose); var action2 = new ActionMock(MockBehavior.Loose); var action3 = new ActionMock(MockBehavior.Loose); var sut = new SequenceActionBuilder() .WithChild(action1) .WithChild(action2) .WithChild(action3) .Build(); using (var context = new ExecutionContext()) { sut.Execute(context).Subscribe(); action1 .Verify(x => x.Execute(context)) .WasCalledExactlyOnce(); action2 .Verify(x => x.Execute(context)) .WasCalledExactlyOnce(); action3 .Verify(x => x.Execute(context)) .WasCalledExactlyOnce(); } }
public override object Execute(object[] args, ExecutionContext ctx) { ArgumentChecker checker = new ArgumentChecker(this.GetType().Name); if (!string.IsNullOrEmpty(Settings.Settings.Default.ActiveGeocacheCode)) { string codeToSearch = (args.Length == 0) ? Settings.Settings.Default.ActiveGeocacheCode : args[0].ToString(); if (codeToSearch.Length == 0) { codeToSearch = Settings.Settings.Default.ActiveGeocacheCode; } // Geocache Code if (codeToSearch == Settings.Settings.Default.ActiveGeocacheCode) { return GetGeocachePostion(Settings.Settings.Default.ActiveGeocacheCode); } // Waypoints return GetWaypointPostion(codeToSearch); } return ""; }
public override object Execute(object[] args, ExecutionContext ctx) { ArgumentChecker checker = new ArgumentChecker(this.GetType().Name); checker.CheckForNumberOfArguments(ref args, 1, null); CharMapAlphabet map = new CharMapAlphabet(); return map.GetCharacterCode(args[0].ToString()[0]); }
public void DashStringDoesNotSplitAtNonmatchingDashes() { // Given Engine engine = new Engine(); Metadata metadata = new Metadata(engine); Pipeline pipeline = new Pipeline("Pipeline", engine, null); IExecutionContext context = new ExecutionContext(engine, pipeline); IDocument[] inputs = { new Document(metadata).Clone(@"FM1 FM2 --- Content1 Content2") }; bool executed = false; FrontMatter frontMatter = new FrontMatter("-", new Execute(x => { executed = true; return new[] { x }; })); // When IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context); // Then Assert.AreEqual(1, documents.Count()); Assert.IsFalse(executed); Assert.AreEqual(@"FM1 FM2 --- Content1 Content2", documents.First().Content); }
public void DefaultCtorSplitsAtDashes() { // Given Engine engine = new Engine(); Metadata metadata = new Metadata(engine); Pipeline pipeline = new Pipeline("Pipeline", engine, null); IExecutionContext context = new ExecutionContext(engine, pipeline); IDocument[] inputs = { new Document(metadata).Clone(@"FM1 FM2 --- Content1 Content2") }; string frontMatterContent = null; FrontMatter frontMatter = new FrontMatter(new Execute(x => { frontMatterContent = x.Content; return new [] {x}; })); // When IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context); // Then Assert.AreEqual(1, documents.Count()); Assert.AreEqual(@"FM1 FM2 ", frontMatterContent); Assert.AreEqual(@"Content1 Content2", documents.First().Content); }
public override void Execute(ExecutionContext executionContext, IDictionary<string, object> tags) { DatabaseInventory inventory = executionContext.GetInventory(Source.Database, false) as DatabaseInventory; if (inventory == null) { throw new NotSupportedException("The database inventory could not be created"); } ExecuteInternal(executionContext, tags, inventory.GenerateUninstallSql()); }
internal override ElaValue Divide(ElaValue left, ElaValue right, ExecutionContext ctx) { if (right.TypeId != ElaMachine.REA) { if (right.TypeId == ElaMachine.DBL) return new ElaValue(left.DirectGetSingle() / right.Ref.AsDouble()); else if (right.TypeId == ElaMachine.INT) return new ElaValue(left.DirectGetSingle() / right.I4); else if (right.TypeId == ElaMachine.LNG) return new ElaValue(left.DirectGetSingle() / right.Ref.AsLong()); else { NoOverloadBinary(TCF.SINGLE, right, "divide", ctx); return Default(); } } if (right.DirectGetSingle() == 0) { ctx.DivideByZero(left); return Default(); } return new ElaValue(left.DirectGetSingle() / right.DirectGetSingle()); }
private static ExecutionContext CreateShadowExecutionContext(ExecutionContext context) { var shadowExecutionContext = new ExecutionContext(context.SkipAhead); shadowExecutionContext.SetCurrentExercise(context.CurrentExercise); shadowExecutionContext.SetCurrentSet(context.CurrentSet); shadowExecutionContext.SetCurrentRepetition(context.CurrentRepetition); // if either context is cancelled, cancel the other context .WhenAnyValue(x => x.IsCancelled) .Where(x => x) .Subscribe(_ => shadowExecutionContext.Cancel()); shadowExecutionContext .WhenAnyValue(x => x.IsCancelled) .Where(x => x) .Subscribe(_ => context.Cancel()); // if either context is paused, pause the other context .WhenAnyValue(x => x.IsPaused) .Subscribe(x => shadowExecutionContext.IsPaused = x); shadowExecutionContext .WhenAnyValue(x => x.IsPaused) .Subscribe(x => context.IsPaused = x); return shadowExecutionContext; }
/// <summary> /// Constructor for InvocationInfo object /// </summary> /// /// <param name="commandInfo"> /// The command information the invocation info represents. /// </param> /// /// <param name="scriptPosition"> /// The position representing the invocation, or the position representing the error. /// </param> /// /// <param name="context"> /// The context in which the InvocationInfo is being created. /// </param> /// internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context) { MyCommand = commandInfo; CommandOrigin = CommandOrigin.Internal; _scriptPosition = scriptPosition; ExecutionContext contextToUse = null; if ((commandInfo != null) && (commandInfo.Context != null)) { contextToUse = commandInfo.Context; } else if (context != null) { contextToUse = context; } // Populate the history ID of this command if (contextToUse != null) { Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace; if (localRunspace != null && localRunspace.History != null) { HistoryId = localRunspace.History.GetNextHistoryId(); } } }
internal void InternalDispose(bool isDisposing) { this.myInvocation = null; this.state = null; this.commandInfo = null; this.context = null; }
public IObservable<Unit> Execute(ExecutionContext context) { Ensure.ArgumentNotNull(context, nameof(context)); var childrenToExecute = this .children .Where(x => context.SkipAhead == TimeSpan.Zero || context.SkipAhead < x.Duration) .OrderByDescending(x => x.Duration) .ToList(); if (childrenToExecute.Count == 0) { // although this shouldn't really happen, we've been asked to execute even though the skip ahead exceeds even our longest-running child context.AddProgress(this.Duration); return Observable.Return(Unit.Default); } var shadowedContext = CreateShadowExecutionContext(context); // only the longest-running child gets the real execution context. The other actions get a shadowed context so that progress does not compound incorrectly var childExecutions = childrenToExecute .Select((action, index) => action.Execute(index == 0 ? context : shadowedContext)) .ToList(); return Observable .CombineLatest(childExecutions) .Select(_ => Unit.Default); }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { sweepAngle = Values[Resources.LenticularSweepAngle].Value * Math.PI / 180; interlaceCount = (int) Values[Resources.LenticularInterlaceCount].Value; interlaceWidth = (int) Values[Resources.LenticularInterlaceWidth].Value; SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "PNG Files (*.png)|*.png"; DialogResult result = dialog.ShowDialog(); if (result != DialogResult.OK) return; fileName = dialog.FileName; activeWindow = Window.ActiveWindow; originalWindowTrans = activeWindow.Projection; screenY = Line.Create(Point.Origin, originalWindowTrans.Inverse * Direction.DirY); string file = GetEnumeratedFileName(0); activeWindow.Export(WindowExportFormat.Png, file); Bitmap bitmap = (Bitmap) Bitmap.FromFile(file); width = bitmap.Width; height = bitmap.Height; }
protected override void ConfigureSecurity(ExecutionContext context) { context.Assertions.Add(c => { if (!c.User.CanManageUsers()) throw new SecurityException(String.Format("User '{0}' cannot create users.", c.User.Name)); }); }
protected override void ExecuteStatement(ExecutionContext context) { var evaluated = Password.EvaluateToConstant(context.Request, null); var passwordText = evaluated.AsVarChar().Value.ToString(); context.Request.Query.CreateUser(UserName, passwordText); }
public void DefaultCtorIgnoresDelimiterOnFirstLine() { // Given Engine engine = new Engine(); Pipeline pipeline = new Pipeline("Pipeline", null); IExecutionContext context = new ExecutionContext(engine, pipeline); IDocument[] inputs = { context.GetDocument(@"--- FM1 FM2 --- Content1 Content2") }; string frontMatterContent = null; FrontMatter frontMatter = new FrontMatter(new Execute((x, ctx) => { frontMatterContent = x.Content; return new[] {x}; })); // When IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context); // Then Assert.AreEqual(1, documents.Count()); Assert.AreEqual(@"FM1 FM2 ", frontMatterContent); Assert.AreEqual(@"Content1 Content2", documents.First().Content); }
public virtual IEnumerable<ILogicRuleObject> GetValidRules(View view, ExecutionContext executionContext) { if (view!=null) { var tuple = new Tuple<ITypeInfo, ExecutionContext>(view.ObjectTypeInfo, executionContext); return LogicRuleManager.Instance[tuple].Where(rule => IsValidRule(rule, view)).OrderBy(rule => rule.Index); } return Enumerable.Empty<ILogicRuleObject>(); }
public IObservable<Unit> Execute(ExecutionContext context) { Ensure.ArgumentNotNull(context, nameof(context)); var childExecutions = this .children .Select( child => Observable .Return(Unit.Default) .Select( _ => { var execute = true; if (context.SkipAhead > TimeSpan.Zero && context.SkipAhead >= child.Duration) { context.AddProgress(child.Duration); execute = false; } return new { Child = child, Execute = execute }; }) .Where(x => x.Execute) .SelectMany(x => x.Child.Execute(context))); return Observable .Concat(childExecutions) .DefaultIfEmpty(); }
public static void TestConstruction() { AssertEquals(new Literal(false).AsValue(), false); AssertEquals(new Literal(true).AsValue(), true); AssertEquals(new Literal(0).AsValue(), 0); AssertEquals(new Literal(1).AsValue(), 1); AssertEquals(new Literal(5).AsValue(), 5); AssertEquals(new Literal(0.1f).AsValue(), 0.1f); AssertEquals(new Literal(2.4f).AsValue(), 2.4f); AssertEquals(new Literal(5.0f).AsValue(), 5.0f); AssertEquals(new Literal("Hello ").AsValue(), "Hello "); AssertEquals(new Literal("World!").AsValue(), "World!"); AssertEquals(new Literal(new Literal(true)).AsValue(), true); AssertEquals(new Literal(new Literal(1)).AsValue(), 1); AssertEquals(new Literal(new Literal(2.4f)).AsValue(), 2.4f); AssertEquals(new Literal(new Literal("Hello ")).AsValue(), "Hello "); var context = new ExecutionContext(new Python3Calculator()); AssertEquals(new Variable("foo", context).Type, ValueType.ANY); AssertEquals(new Variable(ValueType.BOOL, "bar", context).Type, ValueType.BOOL); AssertException<InvalidOperationException>(() => new Variable("foo", context)); }
private void RegisterCommandDefault(ExecutionContext context, string commandName, Type commandType) { CommandEntry entry = new CommandEntry(); entry.command.Initialize(context, commandName, commandType); entry.command.AddNamedParameter("LineOutput", this.lo); this.defaultCommandEntry = entry; }
public async Task Invoke(object[] parameters) { // We require the ExecutionContext, so this will throw if one is not found. ExecutionContext functionExecutionContext = parameters.OfType <ExecutionContext>().First(); // These may not be present, so null is okay. TraceWriter functionTraceWriter = parameters.OfType <TraceWriter>().FirstOrDefault(); Binder binder = parameters.OfType <Binder>().FirstOrDefault(); ILogger logger = parameters.OfType <ILogger>().FirstOrDefault(); string invocationId = functionExecutionContext.InvocationId.ToString(); var startedEvent = new FunctionStartedEvent(functionExecutionContext.InvocationId, Metadata); _metrics.BeginEvent(startedEvent); var invokeLatencyEvent = LogInvocationMetrics(_metrics, Metadata); _stopwatch.Restart(); try { string startMessage = $"Function started (Id={invocationId})"; TraceWriter.Info(startMessage); Logger?.LogInformation(startMessage); FunctionInvocationContext context = new FunctionInvocationContext { ExecutionContext = functionExecutionContext, Binder = binder, TraceWriter = functionTraceWriter, Logger = logger }; await InvokeCore(parameters, context); _stopwatch.Stop(); string completeMessage = $"Function completed (Success, Id={invocationId}, Duration={_stopwatch.ElapsedMilliseconds}ms)"; TraceWriter.Info(completeMessage); Logger?.LogInformation(completeMessage); } catch (AggregateException ex) { ExceptionDispatchInfo exInfo = null; // If there's only a single exception, rethrow it by itself Exception singleEx = ex.Flatten().InnerExceptions.SingleOrDefault(); if (singleEx != null) { exInfo = ExceptionDispatchInfo.Capture(singleEx); } else { exInfo = ExceptionDispatchInfo.Capture(ex); } _stopwatch.Stop(); LogFunctionFailed(startedEvent, "Failure", invocationId, _stopwatch.ElapsedMilliseconds); exInfo.Throw(); } catch { _stopwatch.Stop(); LogFunctionFailed(startedEvent, "Failure", invocationId, _stopwatch.ElapsedMilliseconds); throw; } finally { if (startedEvent != null) { _metrics.EndEvent(startedEvent); } if (invokeLatencyEvent != null) { _metrics.EndEvent(invokeLatencyEvent); } } }
/// <summary> /// Creates a new instance of <see cref="AltCmdSession"/> /// </summary> /// <param name="ec">The execution context (defining the command store involved)</param> public AltCmdSession(ExecutionContext ec) { Context = ec ?? throw new ArgumentNullException(nameof(Context)); }
/// <summary>Schedules the continuation action for this operation.</summary> /// <param name="continuation">The continuation to invoke when the operation has completed.</param> /// <param name="state">The state object to pass to <paramref name="continuation"/> when it's invoked.</param> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> /// <param name="flags">The flags describing the behavior of the continuation.</param> public void OnCompleted(Action <object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { if (continuation == null) { throw new ArgumentNullException(nameof(continuation)); } ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext sc = SynchronizationContext.Current; if (sc != null && sc.GetType() != typeof(SynchronizationContext)) { _capturedContext = sc; } else { TaskScheduler ts = TaskScheduler.Current; if (ts != TaskScheduler.Default) { _capturedContext = ts; } } } // We need to set the continuation state before we swap in the delegate, so that // if there's a race between this and SetResult/Exception and SetResult/Exception // sees the _continuation as non-null, it'll be able to invoke it with the state // stored here. However, this also means that if this is used incorrectly (e.g. // awaited twice concurrently), _continuationState might get erroneously overwritten. // To minimize the chances of that, we check preemptively whether _continuation // is already set to something other than the completion sentinel. object oldContinuation = _continuation; if (oldContinuation == null) { _continuationState = state; oldContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null); } if (oldContinuation != null) { // Operation already completed, so we need to queue the supplied callback. if (!ReferenceEquals(oldContinuation, ManualResetValueTaskSourceCoreShared.s_sentinel)) { ManualResetValueTaskSourceCoreShared.ThrowInvalidOperationException(); } switch (_capturedContext) { case null: if (_executionContext != null) { ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true); } else { ThreadPool.UnsafeQueueUserWorkItem(continuation, state, preferLocal: true); } break; case SynchronizationContext sc: sc.Post(s => { var tuple = (Tuple <Action <object>, object>)s; tuple.Item1(tuple.Item2); }, Tuple.Create(continuation, state)); break; case TaskScheduler ts: Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); break; } } }
/// <summary> /// Executes an action for each element in the collection in paralel and transactionally, and showing the progress in the Console. /// <param name="action">Use LogWriter to write in the Console and the file at the same time</param> /// </summary> private static void ProgressForeachParallel <T>(this IEnumerable <T> collection, Func <T, string> elementID, LogWriter writer, ParallelOptions paralelOptions, bool transactional, bool showProgress, Action <T> action ) { try { var col = collection.ToProgressEnumerator(out IProgressInfo pi); if (!Console.IsOutputRedirected && showProgress) { lock (SafeConsole.SyncKey) SafeConsole.WriteSameLine(pi.ToString()); } Exception stopException = null; using (ExecutionContext.SuppressFlow()) Parallel.ForEach(col, paralelOptions ?? new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, (item, state) => { using (HeavyProfiler.Log("ProgressForeach", () => elementID(item))) try { if (transactional) { using (Transaction tr = Transaction.ForceNew()) { action(item); tr.Commit(); } } else { action(item); } } catch (Exception e) { writer(ConsoleColor.Red, "{0:u} Error in {1}: {2}", DateTime.Now, elementID(item), e.Message); writer(ConsoleColor.DarkRed, e.StackTrace.Indent(4)); if (StopOnException != null && StopOnException(elementID(item), e)) { stopException = e; } } if (!Console.IsOutputRedirected && showProgress) { lock (SafeConsole.SyncKey) SafeConsole.WriteSameLine(pi.ToString()); } if (stopException != null) { state.Break(); } }); if (stopException != null) { throw stopException; } } finally { if (!Console.IsOutputRedirected && showProgress) { SafeConsole.ClearSameLine(); } } }
private void Init(ExecutionContext executionContext) { InitRequest(executionContext.Request); InitParameterCollection(executionContext.Request); }
public override async Task InvokeAsync <TResult>(ExecutionContext executionContext) { Init(executionContext); await InvokeNextAsync <TResult>(executionContext); }
public override void Invoke <TResult>(ExecutionContext executionContext) { Init(executionContext); InvokeNext <TResult>(executionContext); }
private object ExecuteProcedure(string SpName, ExecutionContext Context) { object result = null; List <SpOutParam> ListOutParam = new List <SpOutParam>(); using (SqlConnection con = new SqlConnection(_ConnectionString)) { using (SqlCommand cmd = new SqlCommand(SpName, con)) { cmd.CommandType = CommandType.StoredProcedure; foreach (var item in Context._params) { var SqlParam = cmd.Parameters.AddWithValue("@" + item.Key, item.Value.PValue); if (item.Value.IsOutParam) { SqlParam.Direction = ParameterDirection.Output; ListOutParam.Add(new SpOutParam { ParamObj = SqlParam, ParamName = item.Key, Parameter = item.Value }); } } cmd.CommandType = CommandType.StoredProcedure; if (Context.ReturnType == typeof(DataTable)) { #region ReturnDataTable DataTable DataTableResult = new DataTable(); using (var da = new SqlDataAdapter(cmd)) { cmd.CommandType = CommandType.StoredProcedure; da.Fill(DataTableResult); } result = DataTableResult; #endregion } else if (typeof(IEnumerable).IsAssignableFrom(Context.ReturnType)) { #region ReturnListDTO con.Open(); using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { var RegisteredDelegate = RegisterDTOMapper.GetDelegate(SpName); if (RegisteredDelegate.IsValidDelegate(Context.ReturnType)) { result = (object)RegisteredDelegate.Invoke(reader); } else { result = reader.ToDTOList(Context.ReturnType); } } con.Close(); #endregion } SpOutParam.FixOutputParam(ListOutParam, Context._params); //changeing Out Parameter value in parameter Object. DataHelper.ChangeOutParamInDTO(ListOutParam, Context.ParamDTO); } } return(result); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { string output = string.Empty; bool isSuccessful = true; dynamic ffmpegResult = new JObject(); string errorText = string.Empty; int exitCode = 0; log.LogInformation("C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(Helpers.Helpers.ReturnErrorException(log, ex)); } var ffmpegArguments = (string)data.ffmpegArguments; var sasInputUrl = (string)data.sasInputUrl; if (sasInputUrl == null) { return(Helpers.Helpers.ReturnErrorException(log, "Error - please pass sasInputUrl in the JSON")); } var sasOutputUrl = (string)data.sasOutputUrl; if (sasOutputUrl == null) { return(Helpers.Helpers.ReturnErrorException(log, "Error - please pass sasOutputUrl in the JSON")); } log.LogInformation("Arguments : "); log.LogInformation(ffmpegArguments); try { var folder = context.FunctionDirectory; var tempFolder = Path.GetTempPath(); string inputFileName = System.IO.Path.GetFileName(new Uri(sasInputUrl).LocalPath); string pathLocalInput = System.IO.Path.Combine(tempFolder, inputFileName); string outputFileName = System.IO.Path.GetFileName(new Uri(sasOutputUrl).LocalPath); string pathLocalOutput = System.IO.Path.Combine(tempFolder, outputFileName); foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.IsReady)) { log.LogInformation($"{drive.Name}: {drive.TotalFreeSpace / 1024 / 1024} MB"); } /* Downloads the original video file from blob to local storage. */ log.LogInformation("Dowloading source file from blob to local"); using (FileStream fs = System.IO.File.Create(pathLocalInput)) { try { var readBlob = new CloudBlob(new Uri(sasInputUrl)); await readBlob.DownloadToStreamAsync(fs); log.LogInformation("Downloaded input file from blob"); } catch (Exception ex) { log.LogError("There was a problem downloading input file from blob. " + ex.ToString()); } } log.LogInformation("Encoding..."); var file = System.IO.Path.Combine(folder, "..\\ffmpeg\\ffmpeg.exe"); System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = file; process.StartInfo.Arguments = (ffmpegArguments ?? " -i {input} {output} -y") .Replace("{input}", "\"" + pathLocalInput + "\"") .Replace("{output}", "\"" + pathLocalOutput + "\"") .Replace("'", "\""); log.LogInformation(process.StartInfo.Arguments); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += new DataReceivedEventHandler( (s, e) => { log.LogInformation("O: " + e.Data); } ); process.ErrorDataReceived += new DataReceivedEventHandler( (s, e) => { log.LogInformation("E: " + e.Data); } ); //start process process.Start(); log.LogInformation("process started"); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); exitCode = process.ExitCode; ffmpegResult = output; log.LogInformation("Video Converted"); /* Uploads the encoded video file from local to blob. */ log.LogInformation("Uploading encoded file to blob"); using (FileStream fs = System.IO.File.OpenRead(pathLocalOutput)) { try { var writeBlob = new CloudBlockBlob(new Uri(sasOutputUrl)); await writeBlob.UploadFromStreamAsync(fs); log.LogInformation("Uploaded encoded file to blob"); } catch (Exception ex) { log.LogInformation("There was a problem uploading converted file to blob. " + ex.ToString()); } } System.IO.File.Delete(pathLocalInput); System.IO.File.Delete(pathLocalOutput); } catch (Exception e) { isSuccessful = false; errorText += e.Message; } if (exitCode != 0) { isSuccessful = false; } var response = new JObject { { "isSuccessful", isSuccessful }, { "ffmpegResult", ffmpegResult }, { "errorText", errorText } }; return(new OkObjectResult( response )); }
public async static Task Run([TimerTrigger("0 */10 * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context) { log.LogInformation($"The SftpTest Azure Function is beginning at: {DateTime.Now}"); var sftpParms = getSftpParms(context); using (var sftpTestLibEntry = new SftpTestLibEntry()) { var result = await sftpTestLibEntry.Run(log, sftpParms); log.LogInformation(result.Report); } log.LogInformation($"The SftpTest Azure Function is beginning at: {DateTime.Now}"); }
static void Main() { string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string assemblyPath = Path.Combine(folderPath, IntPtr.Size == 8 ? "x64" : "x86"); SetDllDirectory(assemblyPath); //AppDomain currentDomain = AppDomain.CurrentDomain; //currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder); ClientInfo.TypeOfProgram = typeof(Program); if (StringUtil.IsDevelopMode() == false) { ClientInfo.PrepareCatchException(); } // http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows context = ExecutionContext.Capture(); mutex = new Mutex(true, "{CF1B7B4A-C7ED-4DB8-B5CC-59A067880F92}", out bool createdNew); try { List <string> args = StringUtil.GetCommandLineArgs(); if (createdNew || args.IndexOf("newinstance") != -1) { // ClientInfo.AddShortcutToStartupGroup("dp2-RFID中心"); ClientInfo.RemoveShortcutFromStartupGroup("dp2-RFID中心"); ProgramUtil.SetDpiAwareness(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); _mainForm = new MainForm(); Application.Run(_mainForm); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { API.SetForegroundWindow(process.MainWindowHandle); if (API.IsIconic(process.MainWindowHandle)) { // API.ShowWindow(process.MainWindowHandle, API.SW_SHOW); API.ShowWindow(process.MainWindowHandle, API.SW_RESTORE); } else { // 用 .net remoting 通讯 MainForm.CallActivate("ipc://RfidChannel/RfidServer"); } } } } } finally { if (mutex != null) { mutex.Close(); } } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, null, Route = "{*url}")] HttpRequestMessage req, TraceWriter log, ExecutionContext context) { var ip = req.GetClientIpString(); var reqEntity = new RequestEntity(ip); log.Info($"Request from ip: {req.GetClientIpString()}"); var storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("StorageConnectionString")); var tableClient = storageAccount.CreateCloudTableClient(); var table = tableClient.GetTableReference(Environment.GetEnvironmentVariable("RequestsTableName")); if (req.RequestUri.Segments.Length != 4) { return(null); } if (!CheckClientValid(ip, table)) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } var email = $"{req.RequestUri.Segments[1].Replace("/", "")}" + $"@{req.RequestUri.Segments[2].Replace("/", "")}" + $".{req.RequestUri.Segments[3].Replace("/", "")}"; var formData = req.GetQueryNameValuePairs(); var formDataFormatted = string.Join($"<br /><br />", formData.Select(kv => kv.Key + ": " + "<b>" + kv.Value + "</b>")); var apiKey = Environment.GetEnvironmentVariable("SendGridApiKey"); var client = new SendGridClient(apiKey); var from = new EmailAddress(email); const string subject = "New form submission"; var to = new EmailAddress(email); const string plainTextContent = ""; var htmlContent = "<h1>New form submission</h1>" + $"{formDataFormatted} <br /> <br /> <br />"; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var response = await client.SendEmailAsync(msg); if (response.StatusCode == HttpStatusCode.Accepted) { InsertRequest(reqEntity, table); var httpResponse = new HttpResponseMessage(HttpStatusCode.OK); var responseMessage = Environment.GetEnvironmentVariable("ResponseMessage"); var html = $@"<html> <script> alert(""{responseMessage}""); window.history.back(); </script> </html>"; httpResponse.Content = new StringContent(html); httpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); return(httpResponse); } else { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
/// <summary> /// This method is used to execute the plug-in during the build process /// </summary> /// <param name="context">The current execution context</param> public void Execute(ExecutionContext context) { XmlDocument toc; XPathNavigator root, navToc, tocEntry, tocParent; bool hasParent; // Scan the XML comments files. The files aren't available soon // after this step and by now everything that other plug-ins may // have added to the collection should be there. if (context.BuildStep == BuildStep.CopyStandardContent) { builder.ReportProgress("Searching for comment members containing <tocexclude />..."); foreach (XmlCommentsFile f in builder.CommentsFiles) { foreach (XmlNode member in f.Members.SelectNodes("member[count(.//tocexclude) > 0]/@name")) { exclusionList.Add(member.Value); } } builder.ReportProgress("Found {0} members to exclude from the TOC", exclusionList.Count); return; } if (exclusionList.Count == 0) { builder.ReportProgress("No members found to exclude"); return; } builder.ReportProgress("Removing members from the TOC"); toc = new XmlDocument(); toc.Load(builder.WorkingFolder + "toc.xml"); navToc = toc.CreateNavigator(); // If a root namespace container node is present, we need to look // in it rather than the document root node. root = navToc.SelectSingleNode("topics/topic[starts-with(@id, 'R:')]"); if (root == null) { root = navToc.SelectSingleNode("topics"); } foreach (string id in exclusionList) { tocEntry = root.SelectSingleNode("//topic[@id='" + id + "']"); // Ignore if null, it was probably excluded by the API filter if (tocEntry != null) { // Remove the entry. If this results in the parent // being an empty node, remove it too. do { tocParent = tocEntry.Clone(); hasParent = tocParent.MoveToParent(); builder.ReportProgress(" Removing '{0}'", tocEntry.GetAttribute("id", String.Empty)); tocEntry.DeleteSelf(); } while(hasParent && !tocParent.HasChildren); } } toc.Save(builder.WorkingFolder + "toc.xml"); }
public static void ExecutionContext(ExecutionContext context) { Context = context; }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("C# HTTP trigger function processed a request."); string connectionsJson = File.ReadAllText(Path.Combine(context.FunctionAppDirectory, "Connections.json")); JObject ConnectionsObject = JObject.Parse(connectionsJson); string connectionString = ConnectionsObject["AZURE_STORAGE_URL"].ToString(); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("virtualroomconfig"); await table.CreateIfNotExistsAsync(); var room = req.Headers["room"]; if (string.IsNullOrEmpty(room)) { room = req.Query["room"]; } if (string.IsNullOrEmpty(room)) { return(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Please pass a room name on the query string or in the header") }); } var partitionKey = "Demo"; var rowKey = room; try { // get the room from the table var getRoom = TableOperation.Retrieve <VirtualRoomConfig>(partitionKey, rowKey); var query = await table.ExecuteAsync(getRoom); var currRoomConfig = (VirtualRoomConfig)query.Result; // if room not exist, create a record using default config if (currRoomConfig == null) { var defaultRoom = new VirtualRoomConfig(partitionKey, rowKey); var createRoom = TableOperation.Insert(defaultRoom); await table.ExecuteAsync(createRoom); currRoomConfig = (VirtualRoomConfig)(await table.ExecuteAsync(getRoom)).Result; } var operation = req.Query["operation"].ToString().ToLower(); var updated = false; if (!string.IsNullOrEmpty(operation)) { if (operation.Equals("reset")) { currRoomConfig.LoadDefaultConfig(); updated = true; } else if (operation.Equals("turn")) { var item = req.Query["item"].ToString().ToLower(); var instance = req.Query["instance"].ToString().ToLower(); var value = req.Query["value"].ToString().ToLower(); bool?valueBool = (value.Equals("on") || value.Equals("open")) ? true : ((value.Equals("off") || value.Equals("close")) ? (bool?)false : null); if (valueBool == null) { updated = false; } else if (item.Equals("lights")) { if (instance.Equals("all")) { currRoomConfig.Lights_bathroom = (bool)valueBool; currRoomConfig.Lights_room = (bool)valueBool; currRoomConfig.Message = "All lights " + value; updated = true; } else if (instance.Equals("room")) { currRoomConfig.Lights_room = (bool)valueBool; currRoomConfig.Message = "room light " + value; updated = true; } else if (instance.Equals("bathroom")) { currRoomConfig.Lights_bathroom = (bool)valueBool; currRoomConfig.Message = "bathroom light " + value; updated = true; } } else if (item.Equals("tv")) { currRoomConfig.Television = (bool)valueBool; currRoomConfig.Message = "TV " + value; updated = true; } else if (item.Equals("blinds")) { currRoomConfig.Blinds = (bool)valueBool; currRoomConfig.Message = (bool)valueBool ? "blinds opened" : "blinds closed"; updated = true; } else if (item.Equals("ac")) { currRoomConfig.AC = (bool)valueBool; currRoomConfig.Message = "AC " + value; updated = true; } } else if (operation.Equals("settemperature")) { currRoomConfig.Temperature = int.Parse(req.Query["value"]); currRoomConfig.Message = "set temperature to " + req.Query["value"]; updated = true; } else if (operation.Equals("increasetemperature")) { currRoomConfig.Temperature += int.Parse(req.Query["value"]); currRoomConfig.Message = "raised temperature by " + req.Query["value"] + " degrees"; updated = true; } else if (operation.Equals("decreasetemperature")) { currRoomConfig.Temperature -= int.Parse(req.Query["value"]); currRoomConfig.Message = "decreased temperature by " + req.Query["value"] + " degrees"; updated = true; } } if (updated) { var updateRoom = TableOperation.Replace(currRoomConfig as VirtualRoomConfig); await table.ExecuteAsync(updateRoom); log.LogInformation("successfully updated the record"); } return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(currRoomConfig, Formatting.Indented), Encoding.UTF8, "application/json") }); } catch (Exception e) { log.LogError(e.Message); return(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Failed to process request") }); } }
public static async Task <int> SendMessagesDownstreamAsync(string nsgMessagesString, ExecutionContext executionContext, Binder cefLogBinder, ILogger log) { string outputBinding = Util.GetEnvironmentVariable("outputBinding"); if (outputBinding.Length == 0) { log.LogError("Value for outputBinding is required. Permitted values are: 'arcsight', 'splunk', 'eventhub', 'loganalytics'."); return(0); } StringBuilder sb = StringBuilderPool.Allocate(); string newClientContent = ""; try { sb.Append("{\"records\":[").Append(nsgMessagesString).Append("]}"); newClientContent = sb.ToString(); } finally { StringBuilderPool.Free(sb); } string logIncomingJSON = Util.GetEnvironmentVariable("logIncomingJSON"); Boolean flag; if (Boolean.TryParse(logIncomingJSON, out flag)) { if (flag) { Util.logIncomingRecord(newClientContent, cefLogBinder, log).Wait(); } } int bytesSent = 0; switch (outputBinding) { //case "logstash": // await Util.obLogstash(newClientContent, log); // break; case "arcsight": bytesSent = await Util.obArcsightNew(newClientContent, executionContext, cefLogBinder, log); break; case "splunk": bytesSent = await Util.obSplunk(newClientContent, log); break; case "eventhub": bytesSent = await Util.obEventHub(newClientContent, log); break; case "loganalytics": bytesSent = await Util.obLogAnalytics(newClientContent, log); break; } return(bytesSent); }
public static void Run([TimerTrigger("0 15 19 * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context) { _logger = log; _config = BuildConfig(context); try { var isBackupOk = CheckBackup(); if (!isBackupOk) { SendWarning(); } } catch (Exception e) { _logger.LogError(e, e.Message); } }
public static AppendObjectCommand Create(IServiceClient client, Uri endpoint, ExecutionContext context, AppendObjectRequest request) { OssUtils.CheckBucketName(request.BucketName); OssUtils.CheckObjectKey(request.Key); if (request.Content == null) { throw new ArgumentNullException("request.Content"); } request.ObjectMetadata = request.ObjectMetadata ?? new ObjectMetadata(); if (request.ObjectMetadata.ContentType == null) { request.ObjectMetadata.ContentType = HttpUtils.GetContentType(request.Key, null); } var conf = OssUtils.GetClientConfiguration(client); var originalStream = request.Content; var streamLength = request.Content.Length; // setup progress var callback = request.StreamTransferProgress; if (callback != null) { originalStream = OssUtils.SetupProgressListeners(originalStream, conf.ProgressUpdateInterval, client, callback); } // wrap input stream in MD5Stream if (conf.EnalbeMD5Check) { var hashStream = new MD5Stream(originalStream, null, streamLength); request.Content = hashStream; context.ResponseHandlers.Add(new MD5DigestCheckHandler(hashStream)); } return(new AppendObjectCommand(client, endpoint, context, DeserializerFactory.GetFactory().CreateAppendObjectReusltDeserializer(), request)); }
public override void NotifyReceipients(ExecutionContext context, MeshDataCommand command) { }
public static async Task Run([QueueTrigger("custommsg", Connection = "AzureWebJobsStorage")] string messageItem, ILogger log, ExecutionContext context) { log.LogInformation($"C# Queue trigger function processed: {messageItem}"); var config = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var cosmosClient = new CosmosClient(config["CosmosDbServiceEndpoint"], config["CosmosDbPrimaryKey"]); var messageRepository = new MessageRepository(cosmosClient, "szkchm"); await messageRepository.CreateMessage(messageItem, DateTime.Now); }
protected abstract void Execute(ExecutionContext context, Snippet snippet);
private void EnableTimer(float pollingIntervalInSeconds) { Debug.Assert(Monitor.IsEntered(s_counterGroupLock)); if (pollingIntervalInSeconds <= 0) { _pollingIntervalInMilliseconds = 0; } else if (_pollingIntervalInMilliseconds == 0 || pollingIntervalInSeconds * 1000 < _pollingIntervalInMilliseconds) { _pollingIntervalInMilliseconds = (int)(pollingIntervalInSeconds * 1000); ResetCounters(); // Reset statistics for counters before we start the thread. _timeStampSinceCollectionStarted = DateTime.UtcNow; #if ES_BUILD_STANDALONE // Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever bool restoreFlow = false; try { if (!ExecutionContext.IsFlowSuppressed()) { ExecutionContext.SuppressFlow(); restoreFlow = true; } #endif _nextPollingTimeStamp = DateTime.UtcNow + new TimeSpan(0, 0, (int)pollingIntervalInSeconds); // Create the polling thread and init all the shared state if needed if (s_pollingThread == null) { s_pollingThreadSleepEvent = new AutoResetEvent(false); s_counterGroupEnabledList = new List <CounterGroup>(); s_pollingThread = new Thread(PollForValues) { IsBackground = true, Name = ".NET Counter Poller" }; #if ES_BUILD_STANDALONE s_pollingThread.Start(); #else s_pollingThread.UnsafeStart(); #endif } if (!s_counterGroupEnabledList !.Contains(this)) { s_counterGroupEnabledList.Add(this); } // notify the polling thread that the polling interval may have changed and the sleep should // be recomputed s_pollingThreadSleepEvent !.Set(); #if ES_BUILD_STANDALONE } finally { // Restore the current ExecutionContext if (restoreFlow) { ExecutionContext.RestoreFlow(); } } #endif } }
protected override void OnExecute(Command command, ExecutionContext context, Rectangle buttonRect) { MessageBox.Show($"Not yet", "Info"); }
public Task ClientEvent(string eventId, string eventName, string eventData, string location) { _logger.Debug($"ClientEvent {eventId} {eventName}"); var variables = new Dictionary <string, object>(); var userName = Context.User?.Identity?.Name; if (!string.IsNullOrEmpty(userName)) { variables.Add("user", userName); } if (!string.IsNullOrEmpty(location)) { location = Encoding.UTF8.GetString(Convert.FromBase64String(location)); var locationObject = JsonConvert.DeserializeObject <Location>(location); variables.Add("Location", locationObject); } if (bool.TryParse(eventData, out bool data)) { variables.Add("EventData", data); } else { variables.Add("EventData", eventData); } variables.Add("UDConnectionManager", _connectionManager); variables.Add("EventId", eventId); variables.Add("MemoryCache", _memoryCache); try { var sessionId = _connectionManager.GetSessionId(Context.ConnectionId); var endpoint = _dashboardService.EndpointService.Get(eventId, sessionId); if (endpoint == null) { _logger.Warn($"Endpoint {eventId} not found."); throw new Exception($"Endpoint {eventId} not found."); } var executionContext = new ExecutionContext(endpoint, variables, new Dictionary <string, object>(), Context.User); executionContext.ConnectionId = Context.ConnectionId; executionContext.SessionId = sessionId; return(Task.Run(() => { try { dynamic result = _executionService.ExecuteEndpoint(executionContext, endpoint); if (result.Error is Error error) { Clients.Client(Context.ConnectionId).SendAsync("showError", new { message = error.Message }); } } catch (RuntimeBinderException) { } catch (Exception ex) { _logger.Error("Failed to execute action. " + ex.Message); throw; } })); } catch (Exception ex) { _logger.Warn($"Failed to execute endpoint. " + ex.Message); throw; } }
bool CanDebug(DotNetCoreExecutionCommand command, ExecutionContext context) { return(command.IsExecutable || (command.IsAssembly && IsDebug(context) && VSCodeDebuggerEngine.Exists())); }
public static Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, Route = "/{*proxy}")] HttpRequest request, ExecutionContext executionContext, ILogger logger) => Server.ProcessRequestAsync(request, executionContext, logger);
/// <inheritdoc /> public Task Execute(IMessage message, ExecutionContext context) { context.Complete(); return(Task.FromResult(0)); }
bool IsDebug(ExecutionContext context) { return(context.ExecutionHandler != null && context.ExecutionHandler.GetType().Name == "DebugExecutionHandlerFactory"); }
public override bool Accept(ExecutionContext context, IWebhookDefinition webhookDefinition) { return(true); }
protected override bool OnGetCanExecute(ExecutionContext context, ConfigurationSelector configuration) { return(true); }