public async Task Execute(CodeBlockContext ctx)
    {
        ExecutionStarted.Invoke(this);
        await OnExecute(ctx);

        ExecutionEnded.Invoke(this);
    }
        public Completion Execute(Class m)
        {
            _current = m;
            if (_current == null)
            {
                return(null);
            }
            Completion c = Completion.Void;

            foreach (var func in _current.Functions)
            {
                if ("main".Equals(func.Format, StringComparison.OrdinalIgnoreCase))
                {
                    foreach (var v in _current.Variables)
                    {
                        RegisterValue(v.Name, v.Value);
                    }
                    var parameter = func.Params;
                    ExecutionEnvironment current = new ExecutionEnvironment(this);
                    ExecutionStarted?.Invoke(this, null);
                    foreach (var p in parameter)
                    {
                        current.RegisterValue(p.Name, null);
                    }
                    try
                    {
                        IsCompleted = false;
                        c           = func.Execute(current);
                        break;
                    }catch (Exception e)
                    {
                        IsCompleted = true;
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                        ExecutionAborted?.Invoke(this, new Completion(e.Message, CompletionType.Exception));
                        return(Completion.Void);
                    }
                }
            }
            IsCompleted = true;
            if (c.Type == CompletionType.Value)
            {
                ExecutionCompleted?.Invoke(this, c);
            }
            else if (c.Type == CompletionType.Exception)
            {
                ExecutionAborted?.Invoke(this, c);
            }
            else
            {
                ExecutionAborted?.Invoke(this, Completion.Exception("Unknown exception", null));
            }
            return(c);
        }
Exemple #3
0
        /// <summary>
        /// Data sources can use this to indicate an executionDetails has begun.
        /// </summary>
        /// <param name="executionDetails">The executionDetails.</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="state">User defined state, usually used for logging.</param>
        /// <exception cref="ArgumentNullException">executionDetails - executionDetails is null.</exception>
        protected void OnExecutionStarted(ExecutionToken executionDetails, DateTimeOffset startTime, object?state)
        {
            if (executionDetails == null)
            {
                throw new ArgumentNullException(nameof(executionDetails), $"{nameof(executionDetails)} is null.");
            }

            ExecutionStarted?.Invoke(this, new ExecutionEventArgs(executionDetails, startTime, state));
            if (!SuppressGlobalEvents)
            {
                GlobalExecutionStarted?.Invoke(this, new ExecutionEventArgs(executionDetails, startTime, state));
            }
        }
Exemple #4
0
        public void OnExecutionStarted(ExecutionEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e), $"{nameof(e)} is null.");
            }

            ExecutionStarted?.Invoke(this, e);
            if (!SuppressGlobalEvents && GlobalExecutionStarted != null)
            {
                GlobalExecutionStarted(this, e);
            }
        }
 private ExecutionCompleted RunWithoutAwaitingCompletion()
 {
     try
     {
         _process.Start();
         ExecutionStarted?.Invoke(this, new EventArgs());
         return(new ExecutionCompleted {
             Status = ExecutionStatus.Completed, ExitCode = 0
         });
     }
     catch
     {
         return(new ExecutionCompleted {
             Status = ExecutionStatus.CouldNotLaunch
         });
     }
 }
        private void ExecuteSong(NoteQuality hitNoteQuality, float beatTimeDiff, Song matchingSong)
        {
            NoteHit?.Invoke(hitNoteQuality, beatTimeDiff);
            if (_beatInputHandler == Constants.Noop)
            {
                // don't execute song if game has been finished with the last note
                return;
            }
            _streakScore += _currentQualities.Aggregate(0, (total, curQuality) => total + (int)curQuality);
            _streakPower  = Mathf.Min(_streakScore / Constants.REQUIRED_STREAK_SCORE, Constants.MAX_STREAK_POWER);
            _currentSong  = matchingSong;
            int curStreakPower = _streakPower;

            _currentSong.ExecuteCommand(hitNoteQuality, curStreakPower);
            _coroutineProvider.StartCoroutine(Coroutines.ExecuteAfterSeconds(HALF_NOTE_TIME, () => {
                ExecutionStarted?.Invoke(matchingSong, curStreakPower);
                DisableTouchHandler();
            }));
            ExecutionStarting?.Invoke(_currentSong, curStreakPower);
            _currentCommandUpdate = _currentSong.ExecuteCommandUpdate;
            ResetBeatAfterSeconds(NOTE_TIME * 4);
        }
Exemple #7
0
 protected void OnExecutionStarted()
 {
     IsInProgress = true;
     ExecutionStarted?.Invoke(this, new ClusteringStartedEventArgs(MaxIter));
 }
        public async Task <IResponse> StartAndObserveAsync(ConfirmTerminationOnTimeout shouldTerminateOnTimeout, CancellationToken cancellationToken)
        {
            if (!string.IsNullOrEmpty(_process.StartInfo.WorkingDirectory) && !Directory.Exists(_process.StartInfo.WorkingDirectory))
            {
                return new ExecutionCompleted
                       {
                           Status = ExecutionStatus.CouldNotLaunch,
                           Stderr = "Working directory \"" + _process.StartInfo.WorkingDirectory + "\" does not exist."
                       }
            }
            ;

            if (!_waitForCompletion)
            {
                return(RunWithoutAwaitingCompletion());
            }

            var processExitedTcs = new TaskCompletionSource <bool>();

            _process.Exited += (sender, args) => processExitedTcs.TrySetResult(true);
            cancellationToken.Register(() => processExitedTcs.TrySetCanceled());

            var(stdoutTask, stderrTask) = InitializeOutputCapture();

            var stopWatch = Stopwatch.StartNew();

            try
            {
                _process.Start();
                ExecutionStarted?.Invoke(this, new EventArgs());
                if (_process.StartInfo.RedirectStandardOutput)
                {
                    _process.BeginOutputReadLine();
                    _process.BeginErrorReadLine();
                }
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                return(new ExecutionCompleted {
                    Status = ExecutionStatus.CouldNotLaunch, Stderr = e.Message
                });
            }
            catch (InvalidOperationException e)
            {
                return(new ExecutionCompleted {
                    Status = ExecutionStatus.CouldNotLaunch, Stderr = e.Message
                });
            }

            var processTimeoutTcs = new TaskCompletionSource <bool>();

            if (_timeout != 0)
            {
                var timeoutTimer = new System.Timers.Timer {
                    AutoReset = false, Interval = _timeout * 1000.0                                          /* ms */
                };
                timeoutTimer.Elapsed += (sender, e) => processTimeoutTcs.SetResult(true);
                timeoutTimer.Start();
            }

            var completedTask = await Task.WhenAny(processExitedTcs.Task, processTimeoutTcs.Task);

            if (completedTask.IsCanceled || completedTask == processTimeoutTcs.Task)
            {
                // GetProcessTree call can take several seconds, it should not block the UI thread
                var processTree = await Task.Run(() => _process.GetProcessTree());

                if (completedTask.IsCanceled)
                {
                    ProcessUtils.TerminateProcessTree(processTree);
                    throw new OperationCanceledException(cancellationToken);
                }
                // The tree may be empty if the process has just exited
                if (processTree.Count > 0 && await shouldTerminateOnTimeout(processTree))
                {
                    var terminatedProcesses = ProcessUtils.TerminateProcessTree(processTree);
                    return(new ExecutionTerminatedResponse {
                        TerminatedProcessTree = terminatedProcesses.ToArray()
                    });
                }
                // If the process is still running and should not be terminated, wait for it to exit
                await processExitedTcs.Task;
            }

            var stdout = await stdoutTask;
            var stderr = await stderrTask;

            return(new ExecutionCompleted
            {
                Status = ExecutionStatus.Completed,
                ExitCode = _process.ExitCode,
                Stdout = stdout,
                Stderr = stderr,
                ExecutionTime = stopWatch.ElapsedMilliseconds
            });
        }
Exemple #9
0
        // Event invocation, break handling and so on
        private void Execute(IExecutionEnvironment environment, IList <IInstruction> instructions, int waitMs)
        {
            Reset();
            IsFinished = false;
            IsAborted  = false;
            IsHalted   = false;

            ExecutionStarted?.Invoke(this, new EventArgs());

            while (!IsFinished && !IsAborted)
            {
                // Set the instruction for this cycle
                SetCurrentInstruction(environment, instructions);

                // Check if instruction is marked as a breakpoint and if it is active
                if (_breakPoints.ContainsKey(CurrentInstruction) && _breakPoints[CurrentInstruction])
                {
                    BreakExecution(CurrentInstruction, instructions.IndexOf(CurrentInstruction));
                }
                else if (IsHalted)
                {
                    // If instruction is not a breakpoint and IsHalted was already true, we stepped one instruction further
                    ExecutionStepped?.Invoke(this, new InstructionExecuteEventArgs(CurrentInstruction, CurrentInstructionIndex));
                }

                // Halt the thread if a breakpoint was reached
                if (IsHalted)
                {
                    try
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    catch (ThreadInterruptedException)
                    {
                        // Through an interrupt, the thread will continue from here
                    }
                    catch (ThreadAbortException)
                    {
                        // The further execution will be aborted
                        IsAborted = true;
                        break;
                    }
                }

                // Execute instruction
                InstructionExecuting?.Invoke(this, new InstructionExecuteEventArgs(CurrentInstruction, CurrentInstructionIndex));

                Thread.Sleep(waitMs);
                try
                {
                    ExecuteInternal(environment, instructions);
                }
                catch (Exception e)
                {
                    // Abort execution when the instruction throws
                    Logger.Log(LogLevel.Fatal, e.Message);
                    AbortExecution(true);
                    break;
                }

                InstructionExecuted?.Invoke(this, new InstructionExecuteEventArgs(CurrentInstruction, CurrentInstructionIndex));
            }

            if (!IsAborted)
            {
                ExecutionFinished?.Invoke(this, new EventArgs());
            }
        }
Exemple #10
0
        protected override void OnMessage(MessageEventArgs e)
        {
            if (!e.IsText)
            {
                return;
            }

            var msg = e.Data;

            logger.Debug(new LogReceivedMessage
            {
                Message = msg,
                Session = ID
            }.ToJson());

            string msgType = null;

            try
            {
                msgType = JObject.Parse(msg)["type"]?.ToObject <string>();

                switch (msgType)
                {
                case "Authorization":
                    OnAuthorization?.Invoke(this, Authorization.FromJson(msg));
                    return;

                case "Client.Initialized":
                    OnClientInitialized?.Invoke(this, ClientInitialized.FromJson(msg));
                    return;

                case "Client.Register":
                    OnClientRegister?.Invoke(this, ClientRegister.FromJson(msg));
                    return;

                case "Config.Change":
                    if (Configurer)
                    {
                        OnConfigChange?.Invoke(this, ConfigChange.FromJson(msg));
                    }

                    return;

                case "Config.Register":
                    Configurer = true;
                    Subscriber = true;
                    OnConfigRegister?.Invoke(this);
                    return;

                case "Config.Start":
                    if (Configurer)
                    {
                        OnConfigStart?.Invoke(this);
                    }

                    return;

                case "Config.Stop":
                    if (Configurer)
                    {
                        OnConfigStop?.Invoke(this);
                    }

                    return;

                case "Execution.StartRequest":
                    OnExecutionRequest?.Invoke(this, ExecutionStartRequest.FromJson(msg));
                    return;

                case "Execution.Started":
                    OnExecutionStarted?.Invoke(this, ExecutionStarted.FromJson(msg));
                    return;

                case "Execution.Stopped":
                    OnExecutionStopped?.Invoke(this, ExecutionStopped.FromJson(msg));
                    return;

                case "Info.Message":
                    OnInfo?.Invoke(this, InfoMessage.FromJson(msg));
                    return;

                case "Info.Subscribe":
                    if (!Subscriber)
                    {
                        Subscriber = true;
                        OnSubscribe?.Invoke(this);
                    }

                    return;

                case "Info.Unsubscribe":
                    Subscriber = false;
                    return;

                default:
                    logger.Info(new LogReceivedUnknownMessageType
                    {
                        MessageType = msgType,
                        Session     = ID
                    }.ToJson());

                    return;
                }
            }
            catch (Exception ex)
            {
                //logger.Error()
                logger.Error(new LogMessageHandlingError
                {
                    Exception   = ex,
                    MessageType = msgType,
                    Session     = ID
                }.ToJson());
            }
        }
Exemple #11
0
        public Completion Execute(Class m)
        {
            IsAborting  = false;
            IsCompleted = false;
            _current    = m;
            if (_current == null)
            {
                return(null);
            }
            Completion           c           = Completion.Void;
            ExecutionEnvironment baseEnv     = this.GetBaseEnvironment();
            ExecutionEnvironment classEnv    = new ExecutionEnvironment(baseEnv);
            ExecutionEnvironment instanceEnv = new ExecutionEnvironment(classEnv);

            foreach (var v in m.Variables)
            {
                instanceEnv.RegisterValue(v.Name, v.Value);
            }
            foreach (var func in _current.Functions)
            {
                if ("main".Equals(func.Name, StringComparison.OrdinalIgnoreCase))
                {
                    var parameter = func.Params;
                    ExecutionEnvironment functionEnv = new ExecutionEnvironment(instanceEnv);
                    ExecutionStarted?.Invoke(this, null);
                    foreach (var p in parameter)
                    {
                        functionEnv.RegisterValue(p.Name, null);
                    }
                    foreach (var block in m.BlockStatements)
                    {
                        foreach (var s in block.Body)
                        {
                            if (s is ExpressionStatement)
                            {
                                Expression exp = (s as ExpressionStatement).Expression;
                                if (exp is VariableDeclarationExpression)
                                {
                                    exp.Execute(instanceEnv);
                                }
                            }
                        }
                    }
                    try
                    {
                        IsCompleted = false;
                        c           = func.Execute(functionEnv);
                        break;
                    }catch (Exception e)
                    {
                        IsCompleted = true;
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                        ExecutionAborted?.Invoke(this, new Completion(e.Message, CompletionType.Exception));
                        return(Completion.Void);
                    }
                }
            }
            IsCompleted = true;
            if (c.Type == CompletionType.Value)
            {
                ExecutionCompleted?.Invoke(this, c);
            }
            else if (c.Type == CompletionType.Exception)
            {
                ExecutionAborted?.Invoke(this, c);
            }
            else
            {
                ExecutionAborted?.Invoke(this, Completion.Exception(Properties.Language.UnknowException, null));
            }
            return(c);
        }