/// <summary>
    /// Calculates result of applying operator to operands.
    /// </summary>
    /// <returns>Calculation result</returns>
    /// <exception cref="System.NullReferenceException">Thrown in case of first operand being undefined</exception>
    public double?Calculate()
    {
        State = ExecutorState.ResultCalculated;

        if (FirstOperand == null)
        {
            throw new System.NullReferenceException();
        }

        if (Operator == null)
        {
            return(FirstOperand);
        }

        if (Operator == OperatorType.Inversion ||
            Operator == OperatorType.SquareRoot)
        {
            return(MakeArithmeticCalculation());
        }

        if (SecondOperand == null)
        {
            SecondOperand = FirstOperand;
        }

        return(MakeArithmeticCalculation());
    }
Example #2
0
 protected Process(Guid correlationId)
 {
     CancellationTokenSource = new CancellationTokenSource();
     ChannelState            = ChannelState.Disconnected;
     ExecutorState           = ExecutorState.Ok;
     CorrelationId           = correlationId;
 }
 /// <summary>
 /// Clears current class state.
 /// </summary>
 public void Clear()
 {
     FirstOperand  = null;
     SecondOperand = null;
     Operator      = null;
     State         = ExecutorState.FirstOperandInput;
 }
        /// <summary>
        /// Runs the tests.
        /// </summary>
        /// <param name="tests">Which tests should be run.</param>
        /// <param name="context">Context in which to run tests.</param>
        /// <param param name="framework">Where results should be stored.</param>
        public void RunTests(IEnumerable<TestCase> tests, IRunContext context, IFrameworkHandle framework)
        {
            _state = ExecutorState.Running;

            foreach (var test in tests)
            {
                if (_state == ExecutorState.Cancelling)
                {
                    _state = ExecutorState.Cancelled;
                    return;
                }

                try
                {
                    var reportDocument = RunOrDebugCatchTest(test.Source, test.FullyQualifiedName, context, framework);
                    var result = GetTestResultFromReport(test, reportDocument, framework);
                    framework.RecordResult(result);
                }
                catch (Exception ex)
                {
                    // Log it and move on. It will show up to the user as a test that hasn't been run.
                    framework.SendMessage(TestMessageLevel.Error, "Exception occured when processing test case: " + test.FullyQualifiedName);
                    framework.SendMessage(TestMessageLevel.Informational, "Message: " + ex.Message + "\nStacktrace:" + ex.StackTrace);
                }
            }
        }
        /// <summary>
        /// Runs the tests.
        /// </summary>
        /// <param name="tests">Which tests should be run.</param>
        /// <param name="context">Context in which to run tests.</param>
        /// <param param name="framework">Where results should be stored.</param>
        public void RunTests(IEnumerable <TestCase> tests, IRunContext context, IFrameworkHandle framework)
        {
            _state = ExecutorState.Running;

            foreach (var test in tests)
            {
                if (_state == ExecutorState.Cancelling)
                {
                    _state = ExecutorState.Cancelled;
                    return;
                }

                try
                {
                    var reportDocument = RunOrDebugCatchTest(test.Source, test.FullyQualifiedName, context, framework);
                    var result         = GetTestResultFromReport(test, reportDocument);
                    framework.RecordResult(result);
                }
                catch (Exception ex)
                {
                    // Log it and move on. It will show up to the user as a test that hasn't been run.
                    framework.SendMessage(TestMessageLevel.Error, "Exception occured when processing test case: " + test.FullyQualifiedName);
                    framework.SendMessage(TestMessageLevel.Informational, "Message: " + ex.Message + "\nStacktrace:" + ex.StackTrace);
                }
            }
        }
Example #6
0
        public override ExecutorState Conclude(out long outputProduced, out XDocument additionalInfo)
        {
            ExecutorState newState = (ExecutorState)_state.Clone();

            newState.HasWork      = false;
            newState.TimeCovered += DateTime.Now - _state.LastExecuted;
            additionalInfo        = new XDocument();
            outputProduced        = _lastInsertedId - _lastOldId;
            return(newState);
        }
        /// <summary>
        /// 检测配置
        /// </summary>
        /// <param name="profile">配置</param>
        public void Test(Profile profile)
        {
            Stopped = false;
            State   = ExecutorState.Testing;

            profile.Reset();
            new Thread(InternalTestWithCallback)
            {
                IsBackground = true
            }.Start(profile);
        }
Example #8
0
        public void LoadInterruptionHandlingProgram(string[] commands, string interruptName)
        {
            Timer.Stop();

            LogText(interruptName, LogLevel.Interrupt);
            Commands.Push(commands);
            CurrentIndices.Push(0);
            State = ExecutorState.Normal;

            Timer.Start();
        }
    /// <summary>
    /// Performs arithmetic calculation depending on operator.
    /// </summary>
    /// <returns>Calculation result</returns>
    /// <exception cref="System.NotSupportedException">Thrown in case of operator is not recognized</exception>
    private double MakeArithmeticCalculation()
    {
        if (Operator == OperatorType.Addition)
        {
            return(ArithmeticCalculator.Add((double)FirstOperand, (double)SecondOperand));
        }
        else if (Operator == OperatorType.Subtraction)
        {
            return(ArithmeticCalculator.Subtract((double)FirstOperand, (double)SecondOperand));
        }
        else if (Operator == OperatorType.Multiplication)
        {
            return(ArithmeticCalculator.Multiply((double)FirstOperand, (double)SecondOperand));
        }
        else if (Operator == OperatorType.Division)
        {
            try
            {
                return(ArithmeticCalculator.Divide((double)FirstOperand, (double)SecondOperand));
            }
            catch (System.DivideByZeroException)
            {
                State = ExecutorState.Error;
                return(0);
            }
        }
        else if (Operator == OperatorType.Inversion)
        {
            try
            {
                return(ArithmeticCalculator.Invert((double)FirstOperand));
            }
            catch (System.DivideByZeroException)
            {
                State = ExecutorState.Error;
                return(0);
            }
        }
        else if (Operator == OperatorType.SquareRoot)
        {
            try
            {
                return(ArithmeticCalculator.SquareRoot((double)FirstOperand));
            }
            catch (SquareRootOfNegativeException)
            {
                State = ExecutorState.Error;
                return(0);
            }
        }

        throw new System.NotSupportedException("unknown operation type");
    }
        private void InternalTestWithCallback(object obj)
        {
            Profile profile = obj as Profile;

            try
            {
                InternalTest(profile);
            }
            finally
            {
                State = ExecutorState.Idle;
                profile.Callback?.Invoke();
            }
        }
        private void RunTimes(Profile profile)
        {
            State = ExecutorState.Planning;

            while (!Stopped)
            {
                Thread.Sleep(1);
                if (DateTime.Now >= profile.RunTime)
                {
                    RunOnce(profile);
                    State = ExecutorState.Planning;
                }
            }
        }
Example #12
0
        public void ClearInterruptions()
        {
            if (Commands.Count == 1)
            {
                return;
            }

            Timer.Stop();

            State = ExecutorState.Reverse;
            LogText("Interruptions cleared, recovering state", LogLevel.Interrupt);

            Timer.Start();
        }
        protected override void _ExecuteGraph(Graph Graph)
        {
            context.Reset();

            SetupInitialisingTasks();
            if (!HasInitialisingTasks())
            {
                return;
            }

            EnqueueNextInitialisingTask();

            state = ExecutorState.ProcessingTasks;
            Loop();
        }
Example #14
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (State == ExecutorState.Normal)
            {
                var index = CurrentIndices.Peek();
                if (CurrentIndices.Peek() < Commands.Peek().Length)
                {
                    ProcessCommand(Commands.Peek()[index]);
                    CurrentIndices.Pop();
                    CurrentIndices.Push(index + 1);
                }
                else
                {
                    LogText("Program finished");
                    Timer.Stop();
                }
            }
            else if (State == ExecutorState.Reverse)
            {
                string command = "";
                do
                {
                    var index = CurrentIndices.Peek() - 1;

                    if (index < 0)
                    {
                        CurrentIndices.Pop();
                        Commands.Pop();
                        LogText("State recovered");

                        if (CurrentIndices.Count == 1)
                        {
                            State = ExecutorState.Normal;
                            LogText("Resuming execution");
                            return; //goto timer_tick
                        }
                    }
                    else
                    {
                        command = InvertCommand(Commands.Peek()[index]);
                        CurrentIndices.Pop();
                        CurrentIndices.Push(index);
                    }
                } while (command == "");

                ProcessCommand(command);
            }
        }
        private void RunOnce(Profile profile)
        {
            State = ExecutorState.Running;
            Logger.SetRptFile($"Report-{DateTime.Now:yyMMddHHmm}.csv");
            profile.Reset();
            InternalTest(profile);

            Parallel.ForEach(profile.Instances, new ParallelOptions()
            {
                MaxDegreeOfParallelism = (int)profile.Threads
            },
                             ins =>
            {
                profile.Executor.Execute(ins, this);
            });
        }
        protected override void _ContinueExecutionOn(Processable task)
        {
            if (state == ExecutorState.Idle)
            {
                state = ExecutorState.ProcessingTasks;
                context.Continue();

                context.QueueTask(task);

                Loop();
            }
            else
            {
                // We're already in the loop, just queue up the tasks
                context.QueueTask(task);
            }
        }
        public override ExecutorState Conclude(out long outputProduced, out XDocument additionalInfo)
        {
            ExecutorState newState = (ExecutorState)_state.Clone();

            newState.HasWork = false;
            if (_state.LastExecuted == DateTime.MinValue)
            {
                newState.TimeCovered = new TimeSpan(0);
            }
            else
            {
                newState.TimeCovered += DateTime.Now - _state.LastExecuted;
            }
            additionalInfo = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("ExecutionProtocol"));
            outputProduced = _lastInsertedId - _lastOldId;
            return(newState);
        }
        private void InternalRunWithCallback(object obj)
        {
            Profile profile = obj as Profile;

            try
            {
                if (profile.Mode == RunModes.Once)
                {
                    RunOnce(profile);
                }
                else
                {
                    RunTimes(profile);
                }
            }
            finally
            {
                State = ExecutorState.Idle;
                profile.Callback?.Invoke();
            }
        }
Example #19
0
        public void Handle(IEvent e)
        {
            switch (e)
            {
            case ExecutorFaulted _:
                ExecutorState = ExecutorState.Faulted;
                break;

            case ChannelActivated _:
                ChannelState = ChannelState.Active;
                break;

            case ChannelClosedByServer _:
                ChannelState = ChannelState.ClosedByServer;
                break;

            case ChannelConnected _:
                ChannelState = ChannelState.Connected;
                break;

            case ChannelDeactivated _:
                ChannelState = ChannelState.Inactive;
                break;

            case ChannelDisconnected _:
                ChannelState = ChannelState.Disconnected;
                break;

            case ChannelReachedEndOfTopic _:
                ChannelState = ChannelState.ReachedEndOfTopic;
                break;

            case ChannelUnsubscribed _:
                ChannelState = ChannelState.Unsubscribed;
                break;
            }
            ;

            CalculateState();
        }
Example #20
0
        public override IExecutorState GetExecutorState()
        {
            IConnection serverConnection = _serverConnectionBuilder.GetResult();

            // Если не удалось установить соедиение с севрером - вернем то же состояние без изменений
            if (serverConnection == null)
            {
                return(base.GetExecutorState());
            }

            IExecutorState executorState = new ExecutorState
            {
                ClientConnection = ClientConnection,
                ServerConnection = _serverConnectionBuilder.GetResult(),
                CommandFactory   = _remoteCommandFactory
            };

            executorState.ClientConnection.ConnectionClosed += executorState.CloseConnections;
            executorState.ServerConnection.ConnectionClosed += executorState.CloseConnections;

            return(executorState);
        }
        protected override void _ContinueExecutionOn(List <Processable> tasks)
        {
            if (state == ExecutorState.Idle)
            {
                state = ExecutorState.ProcessingTasks;
                context.Continue();

                for (int i = 0; i < tasks.Count; i++)
                {
                    context.QueueTask(tasks[i]);
                }

                Loop();
            }
            else
            {
                // We're already in the loop, just queue up the tasks
                for (int i = 0; i < tasks.Count; i++)
                {
                    context.QueueTask(tasks[i]);
                }
            }
        }
 /// <summary>
 /// Cancel test execution.
 /// </summary>
 public void Cancel()
 {
     _state = ExecutorState.Cancelling;
 }
 /// <summary>
 /// Cancel test execution.
 /// </summary>
 public void Cancel()
 {
     _state = ExecutorState.Cancelling;
 }
Example #24
0
        /// <summary>
        /// Starts thread execution.
        /// </summary>
        /// <param name="parameters">Parameters to pass to the method. Those to be injected can be ommited or should be null.</param>
        /// <exception cref="NotSupportedException">The common language runtime (CLR) is hosted, and the host does not support ThreadPool.QueueUserWorkItem action.</exception>
        public override void Execute(object[] parameters)
        {
            lock (this.finishedRunningLock)
            {
                this.executorState = ExecutorState.Running;
            }

            this.doneEvent.Reset();

            if (parameters == null)
            {
                parameters = new object[0];
            }

            parameters = this.InjectCommunicationFrameworkObject(parameters);
            if (this.parameterInfos != null)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    if (this.parameterInfos[i] && (parameters[i] is byte[]))
                    {
                        parameters[i] = ((byte[])parameters[i]).Deserialize<object>();
                    }
                }
            }

            var availableWorkerThreads = default(int);
            var availableCompletionPortThreads = default(int);
            var maxWorkerThreads = default(int);
            var maxCompletionPortThreads = default(int);
            ThreadPool.GetAvailableThreads(out availableWorkerThreads, out availableCompletionPortThreads);
            ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads);

            Log.TraceMessage(Log.Activity.Queueing_user_task, string.Format("Queueing user task. Available worker threads: {0}/{1}, available completion port threads: {2}/{3}.", availableWorkerThreads, maxWorkerThreads, availableCompletionPortThreads, maxCompletionPortThreads), Log.MessageType.Trace, keywords: this.Eid.EidAsLogKeywords());

            ThreadPool.QueueUserWorkItem(
                (threadContext) =>
                {
                    Log.TraceMessage(
                        Log.Activity.Local_executor_started_running_user_code,
                        "Local executor has started thread running user code.",
                        Log.MessageType.UserTaskStateChanged,
                        keywords: this.Eid.EidAsLogKeywords());

                    try
                    {
                        // Run user code
                        this.result = this.function(parameters);
                    }
                    catch (Exception ex)
                    {
                        // Handle exceptions that are caused by user code
                        this.Exception = ex;
                        Log.ExceptionMessage(
                            ex,
                            Log.Activity.Local_executor_caught_exception_in_user_code,
                            "Local executor caught exception in user code.",
                            Log.MessageType.UserCodeException | Log.MessageType.UserTaskStateChanged,
                            this.Eid.EidAsLogKeywords());
                    }

                    lock (this.finishedRunningLock)
                    {
                        this.executorState = this.Exception == null ? ExecutorState.Finished : ExecutorState.Faulted;
                        this.timeStopped = DateTime.Now;
                    }

                    Log.TraceMessage(
                        Log.Activity.Local_executor_finished_running_user_code,
                        "Local executor finished running user code.",
                        Log.MessageType.UserTaskStateChanged,
                        keywords: this.Eid.EidAsLogKeywords());

                    this.doneEvent.Set();
                });

            this.timeStarted = DateTime.Now;
            // this.thread.Name = string.Format("User code runner thread on executor '{0}'", this.Eid);
            // this.thread.Start();
        }
Example #25
0
 public LocalExecutor()
 {
     this.Eid = Guid.NewGuid();
     this.executorState = ExecutorState.NotStarted;
     Log.TraceMessage(Log.Activity.Local_executor_created, "Local executor created.", keywords: this.Eid.EidAsLogKeywords());
 }
Example #26
0
 public void EnableExecutor()
 {
     currentState = ExecutorState.Enabled;
 }
Example #27
0
 public void DisableExecutor()
 {
     currentState = ExecutorState.Disabled;
 }
 protected override void _Stop()
 {
     state = ExecutorState.Stopped;
     context.Stop();
 }
        public void Loop()
        {
            switch (state)
            {
            case ExecutorState.Stopped:
                return;

            case ExecutorState.Idle:
                throw new Exception("Executor attempted to run loop while in idle state");

            case ExecutorState.ProcessingTasks:
                if (p != null)
                {
                    // Process next and unhighlight
                    p.Process(context);

                    if (!p.HasMoreToProcess())
                    {
                        p.DebugUnhighlight();
                        p = null;
                    }

                    // Repeat loop
                    Loop();
                }
                else if (context.tasksEnumerator.MoveNext())
                {
                    // Get next node to process
                    p = context.tasksEnumerator.Current;

                    // Highlight the node
                    p.DebugHighlight();

                    // Repeat loop
                    Loop();
                }
                else     // Finished with the current tasks

                // Go back to queuing tasks
                {
                    state = ExecutorState.QueuingTasks;

                    // Repeat loop, no delay
                    Loop();
                }
                break;

            case ExecutorState.QueuingTasks:
                if (context.HasNewlyEnqueuedTasks())   // If there is something to process gathered from the previous processes, do them

                // Swap processing lists and clear the next processing list
                {
                    context.SwitchToNewlyEnqueuedTasks();

                    // Start processing again
                    state = ExecutorState.ProcessingTasks;

                    // Repeat loop, no delay
                    Loop();
                }
                else if (HasInitialisingTasks())     // Otherwise if there is data to process gathered from elsewhere, do that

                {
                    EnqueueNextInitialisingTask();

                    // Start processing again
                    state = ExecutorState.ProcessingTasks;

                    // Repeat loop, no delay
                    Loop();
                }
                else     // If there is no data, stop/idle the execution

                {
                    if (Graph.HasSubscriptions() || Graph.HasDelayedExecution())
                    {
                        // Idle if the graph is still has active external connections
                        state = ExecutorState.Idle;
                        if (Events.OnIdle != null)
                        {
                            Events.OnIdle.Invoke();
                        }
                    }
                    else
                    {
                        // Stop if there are no component externally connected
                        StopExecution();
                    }
                }
                break;
            }
        }