private bool HandleExceptions(MeadowDebugAdapterThreadState threadState)
        {
            // Try to obtain an exception at this point
            if (threadState.CurrentStepIndex.HasValue)
            {
                // Obtain an exception at the current point.
                ExecutionTraceException traceException = threadState.ExecutionTraceAnalysis.GetException(threadState.CurrentStepIndex.Value);

                // If we have an exception, throw it and return the appropriate status.
                if (traceException != null)
                {
                    // Send our exception event.
                    var stoppedEvent = new StoppedEvent(StoppedEvent.ReasonValue.Exception)
                    {
                        Text     = traceException.Message,
                        ThreadId = threadState.ThreadId
                    };
                    Protocol.SendEvent(stoppedEvent);
                    return(true);
                }
            }

            // We did not find an exception here, return false
            return(false);
        }
예제 #2
0
        public static ChaosEvent FromNativeEvent(NativeTypes.FABRIC_CHAOS_EVENT nativeEvent)
        {
            switch (nativeEvent.Kind)
            {
            case NativeTypes.FABRIC_CHAOS_EVENT_KIND.FABRIC_CHAOS_EVENT_KIND_STARTED:
                return(StartedEvent.FromNative(nativeEvent.Value));

            case NativeTypes.FABRIC_CHAOS_EVENT_KIND.FABRIC_CHAOS_EVENT_KIND_EXECUTING_FAULTS:
                return(ExecutingFaultsEvent.FromNative(nativeEvent.Value));

            case NativeTypes.FABRIC_CHAOS_EVENT_KIND.FABRIC_CHAOS_EVENT_KIND_STOPPED:
                return(StoppedEvent.FromNative(nativeEvent.Value));

            case NativeTypes.FABRIC_CHAOS_EVENT_KIND.FABRIC_CHAOS_EVENT_KIND_TEST_ERROR:
                return(TestErrorEvent.FromNative(nativeEvent.Value));

            case NativeTypes.FABRIC_CHAOS_EVENT_KIND.FABRIC_CHAOS_EVENT_KIND_VALIDATION_FAILED:
                return(ValidationFailedEvent.FromNative(nativeEvent.Value));

            case NativeTypes.FABRIC_CHAOS_EVENT_KIND.FABRIC_CHAOS_EVENT_KIND_WAITING:
                return(WaitingEvent.FromNative(nativeEvent.Value));

            default:
                return(null);
            }
        }
        private void Run()
        {
            RunningThreads++;
            bool running = true;

            while (running)
            {
                imageProcessingActionsLock.AcquireWriterLock(1000);
                if (imageProcessingActions.Count > 0)
                {
                    Action currentTask = imageProcessingActions.First();
                    imageProcessingActions.RemoveFirst();
                    imageProcessingActionsLock.ReleaseWriterLock();

                    currentTask.Invoke();
                }
                else
                {
                    imageProcessingActionsLock.ReleaseWriterLock();
                    if (StopWhenTasksCompleted)
                    {
                        running = false;
                    }
                    else
                    {
                        Thread.Sleep(WaitTime);
                    }
                }
            }
            RunningThreads--;
            if (!Running)
            {
                StoppedEvent.Set();
            }
        }
 protected override void OnStop()
 {
     loggers.Debug("AutomateImportService is stopping.");
     Stopping = true;
     StoppedEvent.WaitOne();
     loggers.Debug("AutomateImportService has been stopped.");
 }
        protected override void OnStart(string[] args)
        {
            loggers.Debug("AutomateImportService has been started");
            KeepAlive.Interval  = double.Parse("60000");
            KeepAlive.Enabled   = true;
            KeepAlive.AutoReset = true;
            KeepAlive.Start();

            ThreadPool.QueueUserWorkItem(async state =>
            {
                loggers.Debug("Initializing PWatcher");
                var watcher = new PWatcher(_importService);
                while (!Stopping)
                {
                    try
                    {
                        await watcher.RunWatcherAsync();
                        loggers.Debug("Checking for more files in 5 seconds");
                        Thread.Sleep(5000);
                    }
                    catch (Exception ex)
                    {
                        loggers.Error(ex, $"An exception occurred trying to process inbound files.  We will attempt again in 20 seconds. {ex.Message}");
                        Thread.Sleep(20000);
                    }
                }
                KeepAlive.Stop();
                watcher   = null;
                KeepAlive = null;
                StoppedEvent.Set();
            });
        }
예제 #6
0
        public static ChaosEvent GetEventFromBytes(byte[] data)
        {
            ChaosEvent     e    = null;
            ChaosEventType type = (ChaosEventType)BitConverter.ToInt32(data, 0);

            switch (type)
            {
            case ChaosEventType.Started:
            {
                e = new StartedEvent();
            }

            break;

            case ChaosEventType.Stopped:
            {
                e = new StoppedEvent();
            }

            break;

            case ChaosEventType.ExecutingFaults:
            {
                e = new ExecutingFaultsEvent();
            }

            break;

            case ChaosEventType.ValidationFailed:
            {
                e = new ValidationFailedEvent();
            }

            break;

            case ChaosEventType.TestError:
            {
                e = new TestErrorEvent();
            }

            break;

            case ChaosEventType.Waiting:
            {
                e = new WaitingEvent();
            }

            break;
            }

            if (e != null)
            {
                byte[] eventData = new byte[data.Length - 4];
                Array.Copy(data, 4, eventData, 0, eventData.Length);
                e.FromBytes(eventData);
            }

            return(e);
        }
 public void Start()
 {
     StoppedEvent.Reset();
     for (int i = 0; i < maxThreads; i++)
     {
         Task task = new Task(Run);
         task.Start();
     }
 }
예제 #8
0
        /// <summary>
        ///     Stop feeder and block current thread until it's getting fully stopped
        /// </summary>
        /// <param name="ts">Maximum time to await</param>
        public void Stop(TimeSpan?ts = null)
        {
            if (_status == RunningStatus.Stopped)
            {
                return;
            }

            _status = RunningStatus.Stopped;


            _completionEvent.WaitOne();
            try
            {
                _completionEvent.Reset();

                lock (_stateLock)
                {
                    //while(_running)
                    //Monitor.Wait(_stateLock);

                    _timer.Change(-1, -1);

                    try
                    {
                        Disconnect();
                        _completeShutdownEvent.Set();

                        _initShutdownEvent.Set();
                        //if (_helperThread.IsAlive)
                        //{
                        //                    if (
                        //                        !_helperThread.Join
                        //                            (ts.HasValue
                        //                                 ? (int) ts.Value.TotalMilliseconds
                        //                                 : (int) TimeSpan.FromSeconds(3).TotalMilliseconds))
                        //                    {
                        //#if NET451
                        //                        _helperThread.Abort();
                        //#endif
                        //                    }
                        _completeShutdownEvent.WaitOne();
                        //}
                    }
                    finally
                    {
                        _timer = null;
                    }
                }

                UnloadNativeModule();
            }
            finally
            {
                _completionEvent.Set();
                StoppedEvent?.Invoke(this, null);
            }
        }
예제 #9
0
        public async void CycleProcess(Rack _rack)
        {
            if (!CmmOnline)
            {
                return;
            }

            Working = true;
            StartedEvent?.Invoke(this, null);
            _cts = new CancellationTokenSource();
            Tray tray = null;
            bool success;

            while (true)
            {
                if (_cts.IsCancellationRequested)
                {
                    break;
                }

                tray = await _traySelector.ExecuteAsync(_rack, _cts);

                if (tray == null)
                {
                    break;
                }

                if (_cts.IsCancellationRequested)
                {
                    tray.Status = TrayStatus.TS_Idle;
                    break;
                }

                SetupTray(tray);

                success = await _rootActivity.ExecuteAsync(CurrentTray, _cts).ConfigureAwait(false);

                if (!success)
                {
                    // 报告错误并跳出循环
                    tray.Status = TrayStatus.TS_Error;
                    break;
                }
                tray.Status = TrayStatus.TS_Measured;
            }
            // 如果运行到这里,设置离线可能会断不开连接
            // 在cmmControl中增加标志位,是否还在连接
            //if (!CmmOnline)
            //{
            //    _cmmControl.Offline();
            //}
            Working = false;
            StoppedEvent?.Invoke(this, null);
            _offlineWaitFlag.Set();
        }
예제 #10
0
        public void Init()
        {
            if (BlockChanged == null)
            {
                BlockChanged = new PerBlockEvent();
            }
            if (Started == null)
            {
                Started = new StartedEvent();
            }
            if (Stopped == null)
            {
                Stopped = new StoppedEvent();
            }

            StartBlock = 0;
            var musicPlayerInstance = new GameObject {
                name = "AudioSource"
            };

            if (pianoMixerGroup != null)
            {
                pianoPlayer = musicPlayerInstance.AddComponent <AudioSource>();
                pianoPlayer.outputAudioMixerGroup = pianoMixerGroup;
            }

            if (ePianoMixerGroup != null)
            {
                ePianoPlayer = musicPlayerInstance.AddComponent <AudioSource>();
                ePianoPlayer.outputAudioMixerGroup = ePianoMixerGroup;
            }

            if (stringMixerGroup != null)
            {
                stringPlayer = musicPlayerInstance.AddComponent <AudioSource>();
                stringPlayer.outputAudioMixerGroup = stringMixerGroup;
            }

            if (backingTrackMixerGroup != null)
            {
                backingTrackPlayers = new List <AudioSource>();
                foreach (AudioClip clip in data.BackingTracks)
                {
                    var backingTrackPlayer = musicPlayerInstance.AddComponent <AudioSource>();
                    backingTrackPlayer.outputAudioMixerGroup = backingTrackMixerGroup;
                    backingTrackPlayer.clip = clip;
                    backingTrackPlayers.Add(backingTrackPlayer);
                }
            }

            EntryPoint.Instance.Updated.AddListener(Update);

            ResetGrid();
        }
예제 #11
0
 public void VisitWaitTimeCommand(IWaitTimeCommand waitTimeCommand)
 {
     if (Client.Stopped)
     {
         return;
     }
     if (IsConditionFulfilled(waitTimeCommand.Condition))
     {
         State = MacroPlayerState.WaitingForTimeout;
         bool stopped = StoppedEvent.WaitOne(waitTimeCommand.TimeInMillis);
         State = MacroPlayerState.Running;
     }
 }
        /// <summary>
        /// <para>The event indicates that the execution of the debuggee has stopped due to some condition.</para>
        /// <para>This can be caused by a break point previously set, a stepping action has completed, by executing a debugger statement etc.</para>
        /// </summary>
        /// <param name="reason">
        /// <para>The reason for the event.</para>
        /// <para>For backward compatibility this string is shown in the UI if the 'description' attribute is missing (but it must not be translated).</para>
        /// <para>Values: 'step', 'breakpoint', 'exception', 'pause', 'entry', 'goto', 'function breakpoint', 'data breakpoint', etc.</para>
        /// </param>
        /// <param name="description">The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be translated.</param>
        /// <param name="threadId">The thread which was stopped.</param>
        /// <param name="preserveFocusHint">A value of true hints to the frontend that this event should not change the focus.</param>
        /// <param name="text">Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in the UI.</param>
        /// <param name="allThreadsStopped">
        /// <para>If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped.</para>
        /// <para>- The client should use this information to enable that all threads can be expanded to access their stacktraces.</para>
        /// <para>- If the attribute is missing or false, only the thread with the given threadId can be expanded.</para>
        /// </param>
        public static void SendStoppedEvent(this ProtocolServer server,
                                            string reason,
                                            string description     = null,
                                            long?threadId          = null,
                                            bool?preserveFocusHint = null,
                                            string text            = null,
                                            bool?allThreadsStopped = null
                                            )
        {
            StoppedEvent stoppedEvent = new StoppedEvent(new StoppedEvent.StoppedEventBody(reason, description, threadId, preserveFocusHint, text, allThreadsStopped));

            server.SendMessage(stoppedEvent);
        }
예제 #13
0
        public void AttachAsyncBreak(ITestSettings settings)
        {
            this.TestPurpose("Verifies attach and that breakpoints can be set from break mode.");
            this.WriteSettings(settings);

            IDebuggee debuggee        = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Attach);
            Process   debuggeeProcess = debuggee.Launch("-fNonTerminating", "-fCalling");

            using (ProcessHelper.ProcessCleanup(this, debuggeeProcess))
                using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
                {
                    this.Comment("Attach to debuggee");
                    runner.Attach(settings.DebuggerSettings, debuggeeProcess);
                    runner.ConfigurationDone();

                    this.Comment("Attempt to break all");
                    StoppedEvent breakAllEvent = new StoppedEvent(StoppedReason.Pause);
                    runner.Expects.Event(breakAllEvent)
                    .AfterAsyncBreak();

                    this.WriteLine("Break all stopped on:");
                    this.WriteLine(breakAllEvent.ActualEvent.ToString());

                    this.Comment("Set breakpoint while breaking code.");
                    runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.NonTerminating, 28));

                    this.Comment("Start running after the async break (since we have no idea where we are) and then hit the breakpoint");
                    runner.Expects.HitBreakpointEvent(SinkHelper.NonTerminating, 28)
                    .AfterContinue();

                    this.Comment("Evaluate the shouldExit member to true to stop the infinite loop.");
                    using (IThreadInspector threadInspector = runner.GetThreadInspector())
                    {
                        IFrameInspector firstFrame = threadInspector.Stack.First();
                        this.WriteLine(firstFrame.ToString());
                        firstFrame.GetVariable("shouldExitLocal").Value = "true";
                    }

                    this.Comment("Continue until debuggee exists");
                    runner.Expects.ExitedEvent(exitCode: 0).TerminatedEvent().AfterContinue();

                    this.Comment("Verify debugger and debuggee closed");
                    runner.DisconnectAndVerify();
                    Assert.True(debuggeeProcess.HasExited, "Debuggee still running.");
                }
        }
예제 #14
0
        public void ThreadingBreakpoint(ITestSettings settings)
        {
            this.TestPurpose("Test breakpoint on multiple threads.");
            this.WriteSettings(settings);

            IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Threading);

            using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
            {
                this.Comment("Launching debuggee. Set breakpoint in worker thread code.");
                runner.Launch(settings.DebuggerSettings, true, debuggee, "-fThreading");
                runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Threading, 16));

                // Turned on stop at entry, so should stop before anything is executed.
                // On Concord, this is a reason of "entry" versus "step" when it is hit.
                if (settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg)
                {
                    runner.Expects.HitEntryEvent().AfterConfigurationDone();
                }
                else
                {
                    runner.Expects.HitStepEvent()
                    .AfterConfigurationDone();
                }
                // Since there are 4 worker threads, expect to hit the
                // breakpoint 4 times, once on each thread.
                for (int i = 1; i <= 4; i++)
                {
                    StoppedEvent breakpointEvent = new StoppedEvent(StoppedReason.Breakpoint, SinkHelper.Threading, 16);
                    this.Comment("Run until breakpoint #{0}.", i);
                    runner.Expects.Event(breakpointEvent).AfterContinue();
                    this.WriteLine("Stopped on thread: {0}", breakpointEvent.ThreadId);

                    this.WriteLine("Ensure stopped thread exists in ThreadList");
                    IEnumerable <IThreadInfo> threadInfo = runner.GetThreads();
                    Assert.True(threadInfo.Any(thread => thread.Id == breakpointEvent.ThreadId), string.Format(CultureInfo.CurrentCulture, "ThreadId {0} should exist in ThreadList", breakpointEvent.ThreadId));
                }

                this.Comment("Run to end.");
                runner.Expects.TerminatedEvent().AfterContinue();

                runner.DisconnectAndVerify();
            }
        }
예제 #15
0
        private bool HandleExceptions(MeadowDebugAdapterThreadState threadState)
        {
            bool ShouldProcessException()
            {
                lock (_exceptionBreakpointFilters)
                {
                    if (_exceptionBreakpointFilters.Contains(EXCEPTION_BREAKPOINT_FILTER_ALL))
                    {
                        return(true);
                    }

                    if (!threadState.ExpectingException && _exceptionBreakpointFilters.Contains(EXCEPTION_BREAKPOINT_FILTER_UNHANDLED))
                    {
                        return(true);
                    }

                    return(false);
                }
            }

            // Try to obtain an exception at this point
            if (ShouldProcessException() && threadState.CurrentStepIndex.HasValue)
            {
                // Obtain an exception at the current point.
                ExecutionTraceException traceException = threadState.ExecutionTraceAnalysis.GetException(threadState.CurrentStepIndex.Value);

                // If we have an exception, throw it and return the appropriate status.
                if (traceException != null)
                {
                    // Send our exception event.
                    var stoppedEvent = new StoppedEvent(StoppedEvent.ReasonValue.Exception)
                    {
                        Text     = traceException.Message,
                        ThreadId = threadState.ThreadId
                    };
                    Protocol.SendEvent(stoppedEvent);
                    return(true);
                }
            }

            // We did not find an exception here, return false
            return(false);
        }
예제 #16
0
        public void Detach(ITestSettings settings)
        {
            this.TestPurpose("Verify debugger can detach and reattach to a debuggee.");
            this.WriteSettings(settings);

            this.Comment("Starting debuggee");
            IDebuggee debuggee        = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Attach);
            Process   debuggeeProcess = debuggee.Launch("-fNonTerminating", "-fCalling");

            using (ProcessHelper.ProcessCleanup(this, debuggeeProcess))
            {
                using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
                {
                    this.Comment("Attaching first time");
                    runner.Attach(settings.DebuggerSettings, debuggeeProcess);
                    runner.ConfigurationDone();

                    this.Comment("Attempt to break all");
                    StoppedEvent breakAllEvent = new StoppedEvent(StoppedReason.Pause);
                    runner.Expects.Event(breakAllEvent)
                    .AfterAsyncBreak();

                    this.WriteLine("Break all stopped on:");
                    this.WriteLine(breakAllEvent.ActualEvent.ToString());

                    this.Comment("Detach then verify debugger closed");
                    runner.DisconnectAndVerify();
                }

                Assert.False(debuggeeProcess.HasExited, "Debuggee should still be running.");

                using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
                {
                    this.Comment("Attaching second time");
                    runner.Attach(settings.DebuggerSettings, debuggeeProcess);
                    runner.ConfigurationDone();

                    this.Comment("Detach then verify debugger closed");
                    runner.DisconnectAndVerify();
                }
            }
        }
예제 #17
0
        public void ExecutionAsyncBreak(ITestSettings settings)
        {
            this.TestPurpose("Verify break all should work run function");
            this.WriteSettings(settings);

            this.Comment("Open the kitchen sink debuggee for execution tests.");
            IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Execution);

            using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
            {
                this.Comment("Configure launch");
                runner.Launch(settings.DebuggerSettings, debuggee, "-fNonTerminating", "-fCalling");

                this.Comment("Try to break all");
                StoppedEvent breakAllEvent = new StoppedEvent(StoppedReason.Pause);
                runner.Expects.Event(breakAllEvent).AfterAsyncBreak();

                this.WriteLine("Break all stopped on:");
                this.WriteLine(breakAllEvent.ActualEvent.ToString());

                this.Comment("Set a breakpoint while breaking code");
                runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.NonTerminating, 28));

                this.Comment("Start running after the async break and then hit the breakpoint");
                runner.Expects.HitBreakpointEvent(SinkHelper.NonTerminating, 28).AfterContinue();

                this.Comment("Evaluate the shouldExit member to true to stop the infinite loop.");
                using (IThreadInspector threadInspector = runner.GetThreadInspector())
                {
                    IFrameInspector firstFrame = threadInspector.Stack.First();
                    this.WriteLine(firstFrame.ToString());
                    firstFrame.GetVariable("shouldExit").Value = "true";
                }

                this.Comment("Continue running at the end of application");
                runner.Expects.ExitedEvent().TerminatedEvent().AfterContinue();

                this.Comment("Verify debugger and debuggee closed");
                runner.DisconnectAndVerify();
            }
        }
예제 #18
0
 protected virtual void OnStoppedEvent()
 {
     StoppedEvent?.Invoke(this, EventArgs.Empty);
 }
예제 #19
0
 /// <summary>
 /// Shuts the bot down entirely.
 /// </summary>
 public void Shutdown()
 {
     Client.StopAsync().Wait();
     Client.Dispose();
     StoppedEvent.Set();
 }
예제 #20
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="exception"></param>
 private void RaiseRecordingStopped(Exception exception)
 {
     this.captureTask = null;
     StoppedEvent?.Invoke(this, new WasapiStopEventArgs(exception));
 }
예제 #21
0
        public void TestFolderol(ITestSettings settings)
        {
            this.TestPurpose("This test checks a bunch of commands and events.");
            this.WriteSettings(settings);

            IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, HelloName, DebuggeeMonikers.HelloWorld.Sample);

            using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
            {
                this.Comment("Launch the debuggee");
                runner.Launch(settings.DebuggerSettings, debuggee);

                StoppedEvent stopAtBreak = new StoppedEvent(StoppedReason.Breakpoint);

                // VsDbg does not fire Breakpoint Change events when breakpoints are set.
                // Instead it sends a new breakpoint event when it is bound (after configuration done).
                bool bindsLate = (settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg);

                this.Comment("Set a breakpoint on line 8, but expect it to resolve to line 9.");
                runner.Expects.ConditionalEvent(!bindsLate, x => x.BreakpointChangedEvent(BreakpointReason.Changed, 9))
                .AfterSetBreakpoints(debuggee.Breakpoints(HelloSourceName, 8));

                this.Comment("Start debuggging until breakpoint is hit.");
                runner.Expects.ConditionalEvent(bindsLate, x => x.BreakpointChangedEvent(BreakpointReason.Changed, 9))
                .Event(stopAtBreak)
                .AfterConfigurationDone();

                Assert.Equal(HelloSourceName, stopAtBreak.ActualEventInfo.Filename);
                Assert.Equal(9, stopAtBreak.ActualEventInfo.Line);
                Assert.Equal(StoppedReason.Breakpoint, stopAtBreak.ActualEventInfo.Reason);

                this.Comment("Step forward twice until we have initialized variables");
                runner.Expects.StoppedEvent(StoppedReason.Step, HelloSourceName, 10)
                .AfterStepOver();
                runner.Expects.StoppedEvent(StoppedReason.Step, HelloSourceName, 11)
                .AfterStepIn();

                this.Comment("Inspect the stack and try evaluation.");
                using (IThreadInspector inspector = runner.GetThreadInspector())
                {
                    this.Comment("Get the stack trace");
                    IFrameInspector mainFrame = inspector.Stack.First();
                    inspector.AssertStackFrameNames(true, "main.*");

                    this.WriteLine("Main frame: {0}", mainFrame);

                    this.Comment("Get variables");
                    Assert.Subset(new HashSet <string>()
                    {
                        "x", "y", "argc", "argv"
                    }, mainFrame.Variables.ToKeySet());
                    mainFrame.AssertVariables(
                        "x", "6",
                        "argc", "1");

                    IVariableInspector argv = mainFrame.Variables["argv"];
                    Assert.Matches(HexNumberPattern, argv.Value);

                    this.Comment("Expand a variable (argv has *argv under it)");
                    string variableName = "*argv";
                    if (settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg)
                    {
                        variableName = String.Empty;
                    }
                    Assert.Contains(variableName, argv.Variables.Keys);
                    Assert.Matches(HexNumberPattern, argv.Variables[variableName].Value);

                    this.Comment("Evaluate with side effect");
                    string result = mainFrame.Evaluate("x = x + 1");
                    Assert.Equal("7", result);
                }

                this.Comment("Step to force stack info to refresh");
                runner.Expects.StoppedEvent(StoppedReason.Step).AfterStepOver();

                using (IThreadInspector inspector = runner.GetThreadInspector())
                {
                    this.Comment("Evaluation has side effect, make sure it propagates");
                    Assert.Equal("7", inspector.Stack.First().Variables["x"].Value);
                }

                runner.Expects.ExitedEvent(0).TerminatedEvent().AfterContinue();
                runner.DisconnectAndVerify();
            }
        }
예제 #22
0
 private void OnStoppedEvent()
 {
     StoppedEvent?.Invoke(this, EventArgs.Empty);
 }
예제 #23
0
 private void OnStoppedEvent()
 {
     StoppedEvent?.Invoke(this, EventArgs.Empty);
     CopyFileToFinalDestination();
     _currentRecording = null;
 }
예제 #24
0
        public void Execute(MacroEntry macro)
        {
            _macro = macro;

            if (Thread != null && Thread.IsAlive)
            {
                Stop();
            }

            _cancellationToken = new CancellationTokenSource();

            if (_importCache == null)
            {
                _importCache = InitializeImports(_engine);
            }

            ScriptSource source = _engine.CreateScriptSourceFromString(_macro.Macro, SourceCodeKind.Statements);

            Dictionary <string, object> importCache = new Dictionary <string, object>(_importCache);

            IsFaulted = false;

            Thread = new Thread(() =>
            {
                Thread = Thread.CurrentThread;

                try
                {
                    StartedEvent?.Invoke();

                    AliasCommands.SetDefaultAliases();

                    ScriptScope macroScope = _engine.CreateScope(importCache);

                    _stopWatch.Reset();
                    _stopWatch.Start();

                    do
                    {
                        _cancellationToken.Token.ThrowIfCancellationRequested();

                        source.Execute(macroScope);

                        _stopWatch.Stop();

                        bool willLoop = _macro.Loop && !IsFaulted && !_cancellationToken.IsCancellationRequested;

                        if (!willLoop)
                        {
                            break;
                        }

                        if (Options.CurrentOptions.Debug)
                        {
                            UO.Commands.SystemMessage(string.Format(Strings.Loop_time___0_, _stopWatch.Elapsed));
                        }

                        int diff = 50 - (int)_stopWatch.ElapsedMilliseconds;

                        if (diff > 0)
                        {
                            Thread.Sleep(diff);
                        }
                    }while (_macro.Loop && !IsFaulted);
                }
                catch (TaskCanceledException)
                {
                    IsFaulted = true;
                }
                catch (ThreadInterruptedException)
                {
                    IsFaulted = true;
                }
                catch (ThreadAbortException)
                {
                    IsFaulted = true;
                }
                catch (Exception e)
                {
                    IsFaulted = true;
                    Exception = e;

                    ExceptionEvent?.Invoke(e);
                }
                finally
                {
                    StoppedEvent?.Invoke();
                }
            })
            {
                IsBackground = true
            };

            try
            {
                Thread.Start();
                Thread.Join();
            }
            catch (ThreadStartException)
            {
                // TODO
            }
        }