Esempio n. 1
0
        /// <summary>This method kills the current execution if it has the same id, and deletes all executions with this id in the queue</summary>
        public bool KillAllExecutions(int id)
        {
            if (!ThreadHelper.IsInMainThread)
            {
                throw new Exception("You only call this in the main thread because it contains enumeration of the queue.");
            }

            bool successful = false;

            Interlocked.Exchange(ref killingId, id);

            if (ExecutingId == id)
            {
                ExecutionThread.Abort();
                ExecutionThread = ThreadHelper.NewThread(ExecuteQueueingExecutions);

                successful = true;
            }

            executionQueue.ForEach(thisExecution => { if (thisExecution.id != id)
                                                      {
                                                          executionQueue.Enqueue(thisExecution);
                                                      }
                                                      else
                                                      {
                                                          successful = true;
                                                      } });
            Interlocked.Exchange(ref killingId, defaultValue);

            return(successful);
        }
Esempio n. 2
0
 /// <summary>
 /// Вызвать Native-функцию
 /// </summary>
 /// <param name="thread"></param>
 /// <param name="outerScope">Внешняя область локальных переменных</param>
 /// <param name="args">Список параметров</param>
 /// <returns></returns>
 public virtual JSValue Construct(ExecutionThread thread, VariableScope outerScope, JSValue[] args)
 {
     Contract.Requires(thread != null);
     Contract.Requires(outerScope != null);
     Contract.Requires(args != null);
     throw new NotSupportedException();
 }
Esempio n. 3
0
        /// <summary>
        /// EventHandler for input file button click
        /// </summary>
        /// <returns>void</returns>
        private void InputButton_Click(object sender, EventArgs e)
        {
            // Sets default parameters for Windows file section box
            OpenFileDialog openFile = new OpenFileDialog()
            {
                InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
                FileName         = "BankFile.txt",
                Filter           = "Text files (*.txt)|*.txt",
                Title            = "Open Bank Lineup File"
            };

            // Show the diaglog to the user
            DialogResult result = openFile.ShowDialog();

            // If user selects file and clicks 'ok'
            if (result == DialogResult.OK)
            {
                try {
                    // Run CheckFile
                    if (!CheckFile(openFile.FileName))
                    {
                        // Reset UI Changes
                        CheckLabel.Visible  = false;
                        InputButton.Visible = true;
                        label1.Visible      = true;
                        label2.Visible      = true;
                        label3.Visible      = true;
                        label4.Visible      = true;
                        label5.Visible      = true;
                        return;
                    }
                } catch (Exception ex) {
                    MessageBox.Show($"{ex.Message}\n\n {ex.StackTrace}");
                }
                // If user cancels input
            }
            else if (result == DialogResult.Cancel)
            {
                MessageBox.Show("User cancelled Bank Line input");
                return;
            }

            // Hide "Checking..." Label
            CheckLabel.Visible = false;

            // Show progress bar and set progrss bar values
            ProgressBar.Visible = true;
            ProgressBar.Maximum = (MaxPeople * 3);
            ProgressBarUpdate   = (int)((MaxPeople * 3) * ((double)(1d / 100d)));
            simulating.Visible  = true;

            // Read first arrival event from data file
            Event firstArrival = ReadNextArrival();

            // And put it in the event list
            EventList.Enqueue(firstArrival);

            // Run Main execution async from GUI thread, goes to ExecutionThread.DoWork()
            ExecutionThread.RunWorkerAsync();
        }
        public async Task <ExecutionThread> SaveExecutionThreadAsync(ExecutionThread executionThread)
        {
            var response = await httpClient.PutAsJsonAsync <ExecutionThread>("api/ExecutionThreads", executionThread);

            response.EnsureSuccessStatusCode();
            return(await response.Content.ReadAsAsync <ExecutionThread>());
        }
Esempio n. 5
0
        //public async Task<T> LoadComponentFromExecutionThreadAsync<T>(TXID txid) where T : Component, new()
        //{
        //    var executionThread = await AppExecution.LoadExecutionThreadAsync(txid.tid);
        //    return ExtractComponentFromExecutionThread<T>(executionThread, txid.xid);
        //}

        private T ExtractComponentFromExecutionThread <T>(ExecutionThread executionThread, int xid) where T : Component, new()
        {
            var t         = new T();
            var component = t as Component;

            if (component == null)
            {
                return(null);
            }

            var executingComponent = executionThread.ExecutingComponents.FirstOrDefault(e => e.ExecutingID == xid);

            if (string.IsNullOrEmpty(executingComponent.TypeFullname))
            {
                executingComponent.TypeFullname = typeof(T).FullName;
            }

            //Component.executionManager = this; // See constructor
            component.executionThread = executionThread;
            component.TXID            = new TXID(executionThread.ID, xid);
            component.ClientRef       = executingComponent.ClientRef;
            component.State           = executingComponent.State;

            return(t);
        }
Esempio n. 6
0
        public IComponent ExtractComponentFromExecutionThread(ExecutionThread executionThread, int xid)
        {
            Component component = new OutcomeComponent();

            var executingComponent = executionThread.ExecutingComponents.FirstOrDefault(e => e.ExecutingID == xid);

            Type componentType = null;

            try
            {
                componentType = CoreFunctions.GetType(executingComponent.TypeFullname);
            }
            catch (Exception)
            {
            }
            if (componentType != null)
            {
                component = Activator.CreateInstance(componentType) as Component;
            }

            component.executionThread = executionThread;
            component.TXID            = new TXID(executionThread.ID, xid);
            component.ClientRef       = executingComponent.ClientRef;
            component.State           = executingComponent.State;

            return(component);
        }
Esempio n. 7
0
        /// <summary>
        /// Returns URL of component instance after initiating a new execution thread.
        /// </summary>
        /// <param name="componentInterface"></param>
        /// <returns></returns>
        public async Task <string> RedirectLaunchAppAsync(string componentInterfaceFullname, string returnUrl) // Potentially more params to come inc. returnTaskId, forceContextSearch, etc
        {
            // Get info about the registered component.
            var registeredComponent = await AppRegisterApiClient.GetComponentByInterfaceFullName(componentInterfaceFullname);

            if (registeredComponent == null)
            {
                throw new Exception($"Component interface '{componentInterfaceFullname}' is not registered.");
            }
            var componentInterfaceName = componentInterfaceFullname.Split('.').LastOrDefault();

            var launcher = new LuLauncher()
            {
                ClientRef = componentInterfaceFullname, ReturnUrl = returnUrl
            };

            var thread = new ExecutionThread()
            {
                ExecutingComponents = new List <ExecutingComponent>()
                {
                    new ExecutingComponent()
                    {
                        ExecutingID       = 0,                           // Starts at 0 and will later be incremented for each additional component instance executing within the thread.
                        InterfaceFullname = typeof(LuLauncher).FullName, // a system Launcher Component is always the entry point to a thread
                        TypeFullname      = typeof(LuLauncher).FullName,
                        //URL = "?", // Relevant for LuLauncher??
                        Breadcrumb        = "LuLauncher(0)", // Includes ExecutingID.
                        ParentExecutingID = 0,               // No parent for entry point launcher
                        ClientRef         = launcher.ClientRef,
                        State             = launcher.State,
                        Title             = registeredComponent.Title
                    },
                    new ExecutingComponent()   // The root component (i.e. the component launched for execution).
                    {
                        ExecutingID       = 1, // Starts at 0 and is incremented for each component executed within the thread.
                        InterfaceFullname = componentInterfaceFullname,
                        //TypeFullname = "?", unknown until instantiated.
                        URL               = $"{registeredComponent.DomainName}/{registeredComponent.PrimaryAppRoute}",
                        Breadcrumb        = $"LuLauncher(0)/{componentInterfaceName}(1)",
                        ClientRef         = componentInterfaceName,
                        ParentExecutingID = 0, // LuLauncher acts as parent to root component.
                        State             = null,
                        Title             = registeredComponent.Title
                    }
                },
                ComponentExecutingID    = 1, // Execution starts at the root component.
                ExecutingComponentTitle = registeredComponent.Title,
                ExecutionStatus         = (int)LogicalUnitStatusEnum.Initialised,
                LaunchInputs            = null,
                LockDateTime            = DateTime.Now,
                LockUserID         = Guid.NewGuid().ToString(), // TODO: Determine user ID
                LockUserName       = "******",
                RootComponentTitle = registeredComponent.Title  //JH ,
                                                                //JHPendingOutcome = null
            };

            var persistedThread = await AppExecutionApiClient.SaveNewExecutionThreadAsync(thread);

            return(await RedirectResumeExecutionThreadAsync(persistedThread.ID));
        }
Esempio n. 8
0
        private void SaveComponentToExecutionThread(Component component, ExecutionThread executionThread)
        {
            var executingComponent = executionThread.ExecutingComponents.FirstOrDefault(e => e.ExecutingID == component.TXID.xid);

            executingComponent.State = component.State;
            executionThread          = AppExecutionApiClient.SaveExecutionThread(executionThread);
        }
Esempio n. 9
0
        private async Task SaveComponentToExecutionThreadAsync(Component component, ExecutionThread executionThread)
        {
            var executingComponent = executionThread.ExecutingComponents.FirstOrDefault(e => e.ExecutingID == component.TXID.xid);

            executingComponent.State = component.State;
            executionThread          = await AppExecutionApiClient.SaveExecutionThreadAsync(executionThread);
        }
Esempio n. 10
0
 /// <summary>
 /// Вызвать Native-функцию
 /// </summary>
 /// <param name="thread"></param>
 /// <param name="context">Контекст</param>
 /// <param name="outerScope">Внешняя область локальных переменных</param>
 /// <param name="args">Список параметров</param>
 /// <returns></returns>
 public virtual JSValue Invoke(ExecutionThread thread, JSObject context, VariableScope outerScope, JSValue[] args)
 {
     Contract.Requires(thread != null);
     Contract.Requires(context != null);
     Contract.Requires(outerScope != null);
     Contract.Requires(args != null);
     throw new NotSupportedException();
 }
Esempio n. 11
0
        public ExecutionThread SaveExecutionThread(ExecutionThread executionThread)
        {
            HttpResponseMessage response = null;
            Task task = Task.Run(async() => response = await httpClient.PutAsJsonAsync <ExecutionThread>("api/ExecutionThreads", executionThread));

            task.Wait();
            return(response.Content.ReadAsAsync <ExecutionThread>().Result);
        }
Esempio n. 12
0
        public async Task <ExecutionThread> SaveNewExecutionThreadAsync(ExecutionThread executionThread)
        {
            var response = await httpClient.PostAsJsonAsync <ExecutionThread>("api/ExecutionThreads", executionThread);

            response.EnsureSuccessStatusCode();
            //var newResourceLocation = response.Headers.Location;
            return(await response.Content.ReadAsAsync <ExecutionThread>());
        }
 public void stopCurrentExecution()
 {
     if (ExecutionThread.notNull() && ExecutionThread.IsAlive)
     {
         "ExecutionThread is alive, so stopping it".info();
         ExecutionThread.Abort();
         result_RichTextBox.textColor(Color.Red).set_Text("...current thread stopped...");
     }
 }
Esempio n. 14
0
        public static ExecutionThread Run([NotNull] string filename, [NotNull] Action <string> outputWriter)
        {
            ExecutionThread ex = new ExecutionThread(filename, outputWriter);
            Thread          t  = new Thread(() => ex.SafeRun(filename));

            t.Start();
            t.Name       = filename;
            ex._myThread = t;
            return(ex);
        }
        protected ThreeStateMachine()
        {
            //
            //    Задаём матрицу переходов
            //
            CreateTransitionMatrix();

            _stateChanged = new ManualResetEvent(false);
            _runnerTask   = ExecutionThread.StartNew(MachineProc);
        }
Esempio n. 16
0
        private ExecutionThread AddThread(ulong initialIdleTime)
        {
            var thread = new ExecutionThread(Threads.Count);

            Threads.Add(thread);

            thread.IdleTime = initialIdleTime;
            thread.EndTime  = initialIdleTime;
            return(thread);
        }
        private void Acceptor(IAsyncResult ar)
        {
            var client = _listener.EndAcceptTcpClient(ar);

            if (!NoAcceptMessage)
            {
                Qizarate.Output?.WriteLine("Accepted connection from {0}", client.Client.LocalEndPoint);
            }

            ExecutionThread.StartNew(RequestProc, client);
        }
Esempio n. 18
0
        public async Task <string> RedirectResumeExecutionThreadAsync(ExecutionThread executionThread)
        {
            var txid = new TXID(executionThread.ID, executionThread.ComponentExecutingID).ToString();
            var componentExecuting = executionThread.ExecutingComponents.FirstOrDefault(e => e.ExecutingID == executionThread.ComponentExecutingID);

            componentExecuting.URL          = $"{componentExecuting.URL}/{txid}";
            executionThread.ExecutionStatus = (int)LogicalUnitStatusEnum.Started;
            executionThread = await AppExecutionApiClient.SaveExecutionThreadAsync(executionThread);

            return(componentExecuting.URL);
        }
Esempio n. 19
0
        public void AddExecution(Action thisExecution, int id)
        {
            if (!ThreadHelper.IsInMainThread)
            {
                throw new Exception("You only call this in the main thread.");
            }

            executionQueue.Enqueue(new Execution(thisExecution, id));
            if (ExecutionThread.ThreadState == ThreadState.Unstarted)
            {
                ExecutionThread.Start();
            }
        }
        protected CalibratedPipe(int throughput)
        {
            if (throughput < 1)
            {
                throw new ArgumentOutOfRangeException("throughput", @"Expected 1 or greater (items per second).");
            }

            Throughput = throughput;

            _resolution = ONEK / throughput;
            _portion    = 1;

            ExecutionThread.StartNew(CalibratedTransfer);
        }
        public async Task <IHttpActionResult> PostExecutionThreadAsync(ExecutionThread executionThread)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var executionThreadDB = Map(executionThread);

            _dbContext.ExecutionThreads.Add(executionThreadDB);
            await _dbContext.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = executionThreadDB.ID }, Map(executionThreadDB)));
        }
Esempio n. 22
0
        /// <summary>
        /// Backgroundworker invokes control of UI thread and appends text to final summary output textbox
        /// </summary>
        /// <param name="progress"></param>
        private void AppendToSumBox(int progress)
        {
            string sumoutput = TextOutput.ToString();

            // Invoke method sourced from https://stackoverflow.com/questions/12837305/cross-thread-operation-not-valid-how-to-access-winform-elements-from-another-mo
            this.Invoke(new MethodInvoker(delegate {
                try {
                    this.FinalSummOutput.Text = sumoutput;
                } catch (OutOfMemoryException e) {
                    MessageBox.Show($"Out of memory exception thrown! Too many people placed in line\n\n{e.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }));
            TextOutput.Clear();
            ExecutionThread.ReportProgress(progress);
        }
        public async Task <IHttpActionResult> PutExecutionThreadAsync(ExecutionThread executionThread)
        {
            //return BadRequest("SHIT HAPPENS");

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var executionThreadDB = Map(executionThread);

            _dbContext.Entry(executionThreadDB).State = EntityState.Modified;
            await _dbContext.SaveChangesAsync();

            return(Ok(Map(executionThreadDB)));
        }
Esempio n. 24
0
        public override void CastToPrimitiveValue(ExecutionThread thread, Action <JSValue> onCompleteCallback)
        {
            var valueOf = GetMember("valueOf");

            if (valueOf == null)
            {
                onCompleteCallback(this);
                return;
            }
            thread.CallFunction(
                valueOf.RequireFunction(),
                this,
                JSFunction.EmptyArgumentList,
                true,
                () => onCompleteCallback(thread.CurrentFrame.Pop()));
        }
Esempio n. 25
0
            public override JSValue Invoke(ExecutionThread thread, JSObject context, VariableScope outerScope, JSValue[] args)
            {
                switch (args.Length)
                {
                case 0:
                    break;

                case 1:
                    Console.Out.WriteLine(args[0].CastToString());
                    break;

                default:
                    Console.Out.WriteLine(args[0].CastToString(), args.Skip(1).Select(a => (object)a.CastToString()).ToArray());
                    break;
                }
                return(Undefined);
            }
Esempio n. 26
0
        public override JSValue Construct(ExecutionThread thread, VariableScope outerScope, JSValue[] args)
        {
            IEnumerable <string> parameterNames;
            string functionBody;

            if (args.Length == 0)
            {
                parameterNames = Enumerable.Empty <string>();
                functionBody   = string.Empty;
            }
            else
            {
                parameterNames = args.Take(args.Length - 1).Select(arg => arg.CastToString());
                functionBody   = args[args.Length - 1].CastToString();
            }
            return(VM.NewFunction(outerScope, VM.Compiler.Compile("f", parameterNames, functionBody, false)));
        }
 private GOLD.AppExecution.DataAccess.ExecutionThread Map(ExecutionThread executionThread)
 {
     return(new GOLD.AppExecution.DataAccess.ExecutionThread()
     {
         ID = executionThread.ID,
         ComponentExecutingID = executionThread.ComponentExecutingID,
         ExecutingComponentsJson = JsonConvert.SerializeObject(executionThread.ExecutingComponents),
         ExecutingComponentTitle = executionThread.ExecutingComponentTitle,
         ExecutionStatus = executionThread.ExecutionStatus,
         LaunchCommandLineJson = executionThread.LaunchCommandLine, // TODO: Parse launch command somewhere sometime!
         LaunchInputsJson = JsonConvert.SerializeObject(executionThread.LaunchInputs),
         LockDateTime = executionThread.LockDateTime,
         LockUserID = executionThread.LockUserID,
         LockUserName = executionThread.LockUserName,
         PendingOutcomeJson = executionThread.PendingOutcomeJson,
         RootComponentTitle = executionThread.RootComponentTitle
     });
 }
Esempio n. 28
0
 public override void Stop()
 {
     if (IsRunning)
     {
         Active = false;
         while (IsRunning)
         {
             Thread.Sleep(10);
         }
         try
         {
             ExecutionThread.Join();
         }
         catch (Exception err)
         {
             Console.WriteLine("Failed to stop ThreadService: " + Name + " -> " + err.ToString());
         }
     }
 }
Esempio n. 29
0
        private T ExtractComponentInterfaceFromExecutionThread <T>(ExecutionThread executionThread, int xid) where T : class
        {
            var executingComponent = executionThread.ExecutingComponents.FirstOrDefault(e => e.ExecutingID == xid);

            T          proxy;
            IComponent component;

            if (executingComponent == null)
            {
                proxy          = CoreFunctions.CreateProxy <T>(typeof(IComponent));
                component      = proxy as IComponent;
                component.TXID = new TXID(executionThread.ID, executingComponent.ExecutingID);
            }
            else
            {
                var stateJson = JsonConvert.SerializeObject(executingComponent.State);
                proxy     = CoreFunctions.CreateProxy <T>(stateJson, typeof(IComponent));
                component = proxy as IComponent;
            }

            return(proxy);
        }
Esempio n. 30
0
        public static void Stop()
        {
            if (null != Stopping)
            {
                Stopping();
            }

            ////DbCommandRegistry.KillThemAll();

            Exiting = true;

            var sw = Stopwatch.StartNew();

            var killed = ExecutionThread.KillActiveTasks(KillTimeout);

            sw.Stop();

            if (0 != killed)
            {
                WriteLine(@"@PX Terminated {0} running tasks in {1}.", killed, sw.Elapsed);
            }
        }