Пример #1
0
    /// <summary>
    /// read requested header and validated
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var identity = FetchFromHeader(actionContext);

        if (identity != null)
        {
            if (LoginService.TokenAuthentication(identity))
            {
                CurrentThread.SetPrincipal(new GenericPrincipal(new GenericIdentity(identity), null), null, null);

                //IPrincipal principal = new GenericPrincipal(new GenericIdentity(identity), new string[] { "myRole" });
                //Thread.CurrentPrincipal = principal;
                //HttpContext.Current.User = principal;
            }
            else
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }
        }
        else
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            return;
        }
        base.OnAuthorization(actionContext);
    }
Пример #2
0
        /// <inheritdoc/>
        public Task StartSTATask(Action func)
        {
            var tcs = new TaskCompletionSource <object>();

            var thread = new Thread(() =>
            {
                var id = CurrentThread.GetId();
                try
                {
                    _pool.Add(id);
                    func();
                    tcs.SetResult(null !);
                }
                catch (Exception e)
                {
                    tcs.SetException(e);
                }
                finally
                {
                    _pool.Remove(id);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);

            if (_pool.Count > _maxNumberOfModals)
            {
                tcs.SetResult(null !);
                return(tcs.Task);
            }

            thread.Start();

            return(tcs.Task);
        }
Пример #3
0
        public void ContextSwitch()
        {
            ContextSwitchNeeded = false;

            LastContextSwitchTime = PerformanceCounter.ElapsedMilliseconds;

            if (CurrentThread != null)
            {
                CoreManager.Reset(CurrentThread.Context.Work);
            }

            CurrentThread = SelectedThread;

            if (CurrentThread != null)
            {
                long CurrentTime = PerformanceCounter.ElapsedMilliseconds;

                CurrentThread.TotalTimeRunning += CurrentTime - CurrentThread.LastScheduledTime;
                CurrentThread.LastScheduledTime = CurrentTime;

                CurrentThread.ClearExclusive();

                CoreManager.Set(CurrentThread.Context.Work);

                CurrentThread.Context.Execute();
            }
        }
    /// <summary>
    /// read requested header and validated
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var identity = FetchFromHeader(actionContext);

        if (identity != null)
        {
            //get the user based on the identity
            var user = TokenService.getUserFromToken(identity);
            if (user)
            {
                CurrentThread.SetPrincipal(new GenericPrincipal(new GenericIdentity(user), null), null, null);
            }
            else
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }
        }
        else
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            return;
        }
        base.OnAuthorization(actionContext);
    }
Пример #5
0
        public void ContextSwitch()
        {
            ContextSwitchNeeded = false;

            LastContextSwitchTime = PerformanceCounter.ElapsedMilliseconds;

            if (CurrentThread != null)
            {
                _coreManager.Reset(CurrentThread.HostThread);
            }

            CurrentThread = SelectedThread;

            if (CurrentThread != null)
            {
                long currentTime = PerformanceCounter.ElapsedMilliseconds;

                CurrentThread.TotalTimeRunning += currentTime - CurrentThread.LastScheduledTime;
                CurrentThread.LastScheduledTime = currentTime;

                _coreManager.Set(CurrentThread.HostThread);

                CurrentThread.Execute();
            }
        }
Пример #6
0
        /// <summary>
        /// Forks this current task (actually takes the current thread)
        /// </summary>
        /// <returns>The new PID (zero for child, >0 for childs PID)</returns>
        public int Fork()
        {
            Task newTask = Clone();

            newTask.AddThread(CurrentThread.Clone());
            Tasking.ScheduleTask(newTask);
            return(newTask.PID != PID ? newTask.PID : 0);
        }
Пример #7
0
 public void Stop()
 {
     State.Reset();
     if (CurrentThread != null)
     {
         CurrentThread.Abort();
     }
 }
        public void RunTask_CreatesATaskAndStartsIt()
        {
            var executed = false;
            var current = new CurrentThread();
            current.Run(() => executed = true);

            Assert.That(executed, Is.True);
        }
Пример #9
0
 public void StartAll()
 {
     CurrentThread.Start();
     Dispatcher.Start();
     Immediate.Start();
     NewThread.Start();
     ThreadPool.Start();
     TaskPool.Start();
 }
        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStepBuilder"/>.
        /// </returns>
        public static IStepBuilder x(this string text, Func <IStepContext, Task> body)
        {
            var stepDef = new StepDefinition {
                Text = text, Body = body
            };

            CurrentThread.Add(stepDef);
            return(stepDef);
        }
Пример #11
0
        public void Sleep_When_NotCancelled_Then_ElapsedTimeShouldBeWithInRange()
        {
            var testee    = new CurrentThread();
            var stopwatch = Stopwatch.StartNew();

            testee.Sleep(10, CancellationToken.None);

            stopwatch.Stop();
            stopwatch.ElapsedMilliseconds.Should().BeInRange(9, 20);
        }
Пример #12
0
        public void Sleep_Then_ElapsedTimeShouldBeWithInRange()
        {
            var testee    = new CurrentThread();
            var stopwatch = Stopwatch.StartNew();

            testee.Sleep(10);

            stopwatch.Stop();
            stopwatch.ElapsedMilliseconds.Should().BeInRange(9, 25);
        }
        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStepBuilder"/>.
        /// </returns>
        public static IStepBuilder x(this string text, Func <Task> body)
        {
            var stepDef = new StepDefinition
            {
                Text = text,
                Body = body == null ? NullBodyCallback : c => body(),
            };

            CurrentThread.Add(stepDef);
            return(stepDef);
        }
Пример #14
0
        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStepBuilder"/>.
        /// </returns>
        public static IStepBuilder x(this string text, Func <Task> body)
        {
            var stepDefinition = new StepDefinition
            {
                Text = text,
                Body = body == null ? (Func <IStepContext, Task>)null : c => body(),
            };

            CurrentThread.Add(stepDefinition);
            return(stepDefinition);
        }
Пример #15
0
        public void Sleep_When_Cancelled_Then_ElapsedTimeShouldBeWithInRange()
        {
            var testee    = new CurrentThread();
            var stopwatch = Stopwatch.StartNew();

            using var cancellationTokenSource = new CancellationTokenSource(20);

            testee.Sleep(60, cancellationTokenSource.Token);

            stopwatch.Stop();
            stopwatch.ElapsedMilliseconds.Should().BeInRange(19, 60);
        }
Пример #16
0
        public string FormatType(TargetType type)
        {
            string formatted;

            try {
                formatted = CurrentThread.PrintType(
                    interpreter.Style, type);
            } catch {
                formatted = "<cannot display type>";
            }
            return(formatted);
        }
Пример #17
0
 /// <summary>
 /// Executes an action on the main thread.
 /// </summary>
 public static void InvokeOnMainThread(Action action)
 {
     if (CurrentThread.IsMain())
     {
         action();
     }
     else
     {
         // Now we use unified way on iOS and PC platform
         lock (scheduledActionsSync) {
             scheduledActions += action;
         }
     }
 }
        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStepBuilder"/>.
        /// </returns>
        public static IStepBuilder x(this string text, Action <IStepContext> body)
        {
            var stepDef = new StepDefinition
            {
                Text = text,
                Body = body == null ? NullBodyCallback : c =>
                {
                    body(c);
                    return(Task.FromResult(0));
                },
            };

            CurrentThread.Add(stepDef);
            return(stepDef);
        }
Пример #19
0
        public void Start()
        {
            lock (mLifecycleLock)
            {
                if (mStarted)
                {
                    return;
                }

                mStarted  = true;
                IsRunning = true;
            }

            CurrentThread.Start();
        }
Пример #20
0
        public void Start()
        {
            lock (this)
            {
                if (mStarted)
                {
                    return;
                }

                mStarted  = true;
                IsRunning = true;
            }

            CurrentThread.Start();
        }
Пример #21
0
        static void Main(string[] args)
        {
            WriteLine($"1:{CurrentThread.NameOrId()}");
            Task.Run(() =>
            {
                //Thread.Sleep(5000);
                Task.Delay(5000).Wait();

                // Task.Run use new thread (from threadpool)
                WriteLine($"2:{CurrentThread.NameOrId()}");
            });
            WriteLine($"3:{CurrentThread.NameOrId()}");

            ReadLine();
        }
Пример #22
0
        // Called when opCpp Stop Build command is executed
        private void StopBuildCallback(object sender, EventArgs e)
        {
            if (bAddinLocked)
            {
                return;
            }

            //Stop the build if it's going...
            if (CurrentThread != null)
            {
                CurrentThread.Stop();
                CurrentThread = null;
            }

            LogCompile("opC++ Build Stopped.");
        }
Пример #23
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            AliveModuleIntances.Remove(this);

            if (disposing && (components != null))
            {
                components.Dispose();
            }

            if (CurrentThread != null)
            {
                CurrentThread.Stop();
            }

            base.Dispose(disposing);
        }
Пример #24
0
#pragma warning disable IDE1006 // Naming Styles
        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStepBuilder"/>.
        /// </returns>
        public static IStepBuilder x(this string text, Action body)
        {
            var stepDefinition = new StepDefinition
            {
                Text = text,
                Body = body == null
                    ? (Func <IStepContext, Task>)null
                    : c =>
                {
                    body();
                    return(Task.FromResult(0));
                },
            };

            CurrentThread.Add(stepDefinition);
            return(stepDefinition);
        }
Пример #25
0
        /// <summary>
        /// Executes an action on the main thread.
        /// </summary>
        public static void InvokeOnMainThread(Action action)
        {
            if (CurrentThread.IsMain())
            {
                action();
            }
            else
            {
#if UNITY
                throw new NotImplementedException();
#else
                // Now we use unified way on iOS and PC platform
                lock (scheduledActionsSync) {
                    scheduledActions += action;
                }
#endif
            }
        }
Пример #26
0
 private async void coreInkIndependentInputSource_PointerHovering(CoreInkIndependentInputSource sender, PointerEventArgs args)
 {
     if (GeometryHelper.PointIsInPolygon(P1, P2, P3, args.CurrentPoint.RawPosition) == true)
     {
         await CurrentThread.RunAsync(CoreDispatcherPriority.High, () =>
         {
             Geodreieck.IsHitTestVisible = true;
         });
     }
     else
     {
         await CurrentThread.RunAsync(CoreDispatcherPriority.High, () =>
         {
             ScrollViewer_InkCanvas.VerticalScrollMode   = ScrollMode.Enabled;
             ScrollViewer_InkCanvas.HorizontalScrollMode = ScrollMode.Enabled;
             ScrollViewer_InkCanvas.ZoomMode             = ZoomMode.Enabled;
         });
     }
 }
Пример #27
0
        /// <summary>
        /// Processes a signal
        /// </summary>
        /// <param name="signal">The signal</param>
        /// <returns>The errorcode</returns>
        public unsafe ErrorCode ProcessSignal(Signal signal)
        {
            if (signal <= 0 || (int)signal >= Signals.NSIG)
            {
                return(ErrorCode.EINVAL);
            }

            // Get handler, if no handler is set, use default handler
            SignalAction action = m_signalActions[(int)signal];

            if (action == null)
            {
                Signals.DefaultAction defaultAction = Signals.DefaultActions[(int)signal];
                switch (defaultAction)
                {
                case Signals.DefaultAction.Continue:
                    RemoveFlag(TaskFlag.STOPPED);
                    break;

                case Signals.DefaultAction.Stop:
                    AddFlag(TaskFlag.STOPPED);
                    // Do a task switch because the task may not run until a continue is received
                    Tasking.Yield();
                    break;

                case Signals.DefaultAction.Core:
                case Signals.DefaultAction.Terminate:
                    Console.WriteLine(Signals.SignalNames[(int)signal]);
                    Tasking.RemoveTaskByPID(PID);
                    break;
                }
            }
            else
            {
                if (action.Sigaction.Handler != (void *)Signals.SIG_IGN)
                {
                    CurrentThread.ProcessSignal(action);
                }
            }

            return(ErrorCode.SUCCESS);
        }
Пример #28
0
        private ThreadPageMetadata LoadPageNumberDelegate(object state)
        {
            try
            {
                int pageNumber = (int)state;
                var page       = _pageCache.GetPage(CurrentThread, pageNumber);

                if (page == null)
                {
                    UpdateStatus("Loading Page...");
                    page = CurrentThread.Page(pageNumber);
                }

                return(page);
            }
            catch (InvalidCastException)
            {
                throw new Exception("Expected type int from state.");
            }
        }
Пример #29
0
        public void ContextSwitch()
        {
            ContextSwitchNeeded = false;

            if (CurrentThread != null)
            {
                CoreManager.GetThread(CurrentThread.Thread.Work).Pause();
            }

            CurrentThread = SelectedThread;

            if (CurrentThread != null)
            {
                CurrentThread.ClearExclusive();

                CoreManager.GetThread(CurrentThread.Thread.Work).Unpause();

                CurrentThread.Thread.Execute();
            }
        }
Пример #30
0
        private async Task <RunSummary> InvokeScenarioMethodAsync(object scenarioClassInstance)
        {
            var backgroundStepDefinitions = new List <IStepDefinition>();
            var scenarioStepDefinitions   = new List <IStepDefinition>();

            await this.aggregator.RunAsync(async() =>
            {
                using (CurrentThread.EnterStepDefinitionContext())
                {
                    foreach (var backgroundMethod in this.scenario.TestCase.TestMethod.TestClass.Class
                             .GetMethods(false)
                             .Where(candidate => candidate.GetCustomAttributes(typeof(BackgroundAttribute)).Any())
                             .Select(method => method.ToRuntimeMethod()))
                    {
                        await this.timer.AggregateAsync(() =>
                                                        backgroundMethod.InvokeAsync(scenarioClassInstance, null));
                    }

                    backgroundStepDefinitions.AddRange(CurrentThread.StepDefinitions);
                }

                using (CurrentThread.EnterStepDefinitionContext())
                {
                    await this.timer.AggregateAsync(() =>
                                                    this.scenarioMethod.InvokeAsync(scenarioClassInstance, this.scenarioMethodArguments));

                    scenarioStepDefinitions.AddRange(CurrentThread.StepDefinitions);
                }
            });

            var runSummary = new RunSummary {
                Time = this.timer.Total
            };

            if (!this.aggregator.HasExceptions)
            {
                runSummary.Aggregate(await this.InvokeStepsAsync(backgroundStepDefinitions, scenarioStepDefinitions));
            }

            return(runSummary);
        }
Пример #31
0
        protected override void InitializeModuleData()
        {
            base.InitializeModuleData();
            CurrentThread = new WorkerThread(delegate
            {
                while (!CurrentThread.AbortRequest)
                {
                    try
                    {
                        using (var ctrlSA = new SAController())
                        {
                            DataContainer alertContainer;
                            ctrlSA.ExecuteAlert(out alertContainer, ModuleInfo.ModuleID, ModuleInfo.SubModule);

                            var rows = alertContainer.DataTable.Rows;

                            if (rows.Count > 0)
                            {
                                m_LastResultRow = alertContainer.DataTable.Rows[0];
                            }
                        }
                    }
                    catch (FaultException ex)
                    {
                        m_LastException = ex;
                    }
                    catch (Exception ex)
                    {
                        m_LastException = ErrorUtils.CreateErrorWithSubMessage(ERR_SYSTEM.ERR_SYSTEM_UNKNOWN, ex.Message);
                    }

                    CurrentThread.ExecuteUpdateGUI();
                    Thread.Sleep(AlertInfo.SleepTime);
                }
            }, MainProcess.GetMainForm());
            CurrentThread.DoUpdateGUI += CurrentThread_DoUpdateGUI;
            CurrentThread.Start();
        }