示例#1
0
        protected async override void Run()
        {
            if (DebuggingService.IsPaused)
            {
                DebuggingService.Resume();
                return;
            }

            if (!IdeApp.ProjectOperations.CurrentRunOperation.IsCompleted)
            {
                if (!MessageService.Confirm(GettextCatalog.GetString("An application is already running. Do you want to stop it?"), AlertButton.Stop))
                {
                    return;
                }
                StopHandler.StopBuildOperations();
                await IdeApp.ProjectOperations.CurrentRunOperation.Task;
            }

            if (IdeApp.Workspace.IsOpen)
            {
                var target = GetRunTarget();
                if (target != null)
                {
                    IdeApp.ProjectOperations.Debug(target);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Open a connection to the DOB.
        /// <para/>
        /// The connection uses the OnDoDispatch callback to signal that there is incoming data available.
        /// When OnDoDispatch is called the application shall set an event or similar and then call
        /// Dispatch() in this class from the thread that owns (has called Open)
        /// the connection.
        /// <para/>
        /// There can be a number of contexts in the DOB. A connection is linked to the context specified in Open.
        /// All operations using a connection is affecting only the context linked to that connection.
        /// The intended primary usage is for recording/replay functionality. 0 is defined as the default
        /// context.
        /// <para/>
        /// Note that connectionNameCommonPart together with connectionNameInstancePart must be unique
        /// in the node.
        /// <para/>
        /// If null is passed as the stopHandler argument the connection will not receive a stop order.
        /// Normally only the main thread of an application should pass a non-null stopHandler, and it
        /// should then tell other parts of the application to exit. If multiple stop handlers are specified
        /// there is NO guaranteed order between which gets called first when a process receives a stop signal.
        /// <para/>
        /// </summary>
        /// <param name="connectionNameCommonPart">Name that identifies the program but not any particular
        ///                                        program instance.</param>
        /// <param name="connectionNameInstancePart">Name that identifies a particular program instance.</param>
        /// <param name="context">Context functionality not implemented yet!</param>
        /// <param name="stopHandler">Object that implements the StopHandler interface.</param>
        /// <param name="dispatcher">Object that implements the Dispatcher interface.</param>
        /// <exception cref="Safir.Dob.NotOpenException">The connection name is already used by someone else.
        ///                                              Try another!</exception>
        public void Open(string connectionNameCommonPart,
                         string connectionNameInstancePart,
                         System.Int32 context,
                         StopHandler stopHandler,
                         Dispatcher dispatcher)
        {
            // This check guarantees that there will be no call to DoseC_Connect if the connection is already opened.
            // This solves the problem with dropping the incremented refrences in case of a NOP.
            if (IsOpen())
            {
                return;
            }

            System.IntPtr nameCommonPart   = Dob.Typesystem.Internal.InternalOperations.CStringOf(connectionNameCommonPart);
            System.IntPtr nameInstancePart = Dob.Typesystem.Internal.InternalOperations.CStringOf(connectionNameInstancePart);

            byte success;

            Interface.DoseC_Connect(m_ctrl,
                                    nameCommonPart,
                                    nameInstancePart,
                                    context,
                                    Interface.DOSE_LANGUAGE_DOTNET,
                                    ConsumerHandler.Instance.AddReference(stopHandler),
                                    ConsumerHandler.Instance.AddReference(dispatcher),
                                    Callbacks.onDispatchCb,
                                    Callbacks.onStopOrderCb,
                                    Callbacks.onNewEntityCb,
                                    Callbacks.onUpdatedEntityCb,
                                    Callbacks.onDeletedEntityCb,
                                    Callbacks.onCreateRequestCb,
                                    Callbacks.onUpdateRequestCb,
                                    Callbacks.onDeleteRequestCb,
                                    Callbacks.onServiceRequestCb,
                                    Callbacks.onResponseCb,
                                    Callbacks.onMessageCb,
                                    Callbacks.onRegisteredCb,
                                    Callbacks.onUnregisteredCb,
                                    Callbacks.onRevokedRegistrationCb,
                                    Callbacks.onCompletedRegistrationCb,
                                    Callbacks.onInjectedNewEntityCb,
                                    Callbacks.onInjectedUpdatedEntityCb,
                                    Callbacks.onInjectedDeletedEntityCb,
                                    Callbacks.onInitialInjectionsDoneCb,
                                    Callbacks.onNotRequestOverflowCb,
                                    Callbacks.onNotMessageOverflowCb,
                                    Callbacks.onDropReferenceCb,
                                    out success);

            Marshal.FreeHGlobal(nameCommonPart);
            Marshal.FreeHGlobal(nameInstancePart);

            if (!Interface.BoolOf(success))
            {
                ConsumerHandler.Instance.DropReference(stopHandler);
                ConsumerHandler.Instance.DropReference(dispatcher);

                Safir.Dob.Typesystem.LibraryExceptions.Instance.Throw();
            }
        }
示例#3
0
 private void StopThread()
 {
     if (this.btnStart.InvokeRequired)
     {
         StopHandler sh = new StopHandler(StopThread);
         this.Invoke(sh, new object[] {});
     }
     else
     {
         this.btnStart.Enabled = true;
     }
 }
示例#4
0
 private static void OnStopOrder(System.IntPtr connectionOwner, out byte success)
 {
     success = Interface.ByteOf(false);
     try
     {
         StopHandler cons =
             (StopHandler)ConsumerHandler.ToConsumer(connectionOwner);
         cons.OnStopOrder();
         success = Interface.ByteOf(true);
     }
     catch (System.Exception exc)
     {
         Typesystem.LibraryExceptions.Instance.Set(exc);
     }
 }
        public WitConversation(string token, string conversationId, T initialContext,
                               MergeHandler merge, SayHandler say, ActionHandler action, StopHandler stop)
        {
            if (token == null || conversationId == null || merge == null || say == null || action == null)
            {
                throw new Exception("Please check WitConversation constructor parameters.");
            }

            client = new WitClient(token);
            this.conversationId = conversationId;
            _merge  = merge;
            _say    = say;
            _action = action;
            _stop   = stop;
            context = initialContext;
        }
示例#6
0
 public async Task Stop()
 {
     await Task.Run(() =>
     {
         var mr = new ManualResetEvent(false);
         StopHandler stopAction = null;
         stopAction             = () =>
         {
             _listener.SCPStopped -= stopAction;
             mr.Set();
         };
         _listener.SCPStopped += stopAction;
         _tokenSource.Cancel();
         _listener.Stop();
         mr.WaitOne();
     });
 }
示例#7
0
        public Executor(string[] args)
        {
            m_instance        = int.Parse(args[0]);
            m_instanceString  = m_instance.ToString();
            m_partnerEntityId = new Safir.Dob.Typesystem.EntityId(DoseTest.Partner.ClassTypeId,
                                                                  new Safir.Dob.Typesystem.InstanceId(m_instance));
            m_controlConnectionName = m_identifier + "_control";
            m_testConnectionName    = "partner_test_connection";
            m_callbackActions       = new Dictionary <Safir.Dob.CallbackId.Enumeration, List <DoseTest.Action> >();
            foreach (Safir.Dob.CallbackId.Enumeration cb in Enum.GetValues(typeof(Safir.Dob.CallbackId.Enumeration)))
            {
                m_callbackActions.Add(cb, new List <DoseTest.Action>());
            }

            m_controlDispatcher = new ControlDispatcher(m_controlDispatchEvent);
            m_testDispatcher    = new Dispatcher(m_testDispatchEvent);
            m_testStopHandler   = new StopHandler();
            m_actionReceiver    = new ActionReceiver(m_instance, m_dataReceivedEvent);
        }
示例#8
0
        /// <summary>
        /// Starts the timer with the given timeout value and timeout handler function.
        /// </summary>
        /// <param name="timeoutValue">
        /// The timeout handler function will be called by the AlarmClockThread if this amount of time elapses without stopping
        /// the timer object.
        /// </param>
        /// <param name="timeoutHandler">The handler function that will be called in case of timeout.</param>
        /// <param name="stopHandler">The handler function that will be called in case of stop.</param>
        /// <remarks>
        /// This function can only be called from another thread.
        /// </remarks>
        public void Start(int timeoutValue, TimeoutHandler timeoutHandler, StopHandler stopHandler)
        {
            if (timeoutValue < 0)
            {
                throw new ArgumentOutOfRangeException("timeoutValue");
            }
            if (timeoutHandler == null)
            {
                throw new ArgumentNullException("timeoutHandler");
            }
            if (stopHandler == null)
            {
                throw new ArgumentNullException("stopHandler");
            }

            lock (this.lockObject)
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("AlarmClockThread");
                }
                if (RCThread.CurrentThread == this.timeoutThread)
                {
                    throw new DssException("Unable to access AlarmClockThread.Start from the current thread!");
                }
                if (this.timerRunning)
                {
                    throw new DssException("The timer is currently running!");
                }

                this.currentTimeoutValue   = timeoutValue;
                this.currentTimeoutHandler = timeoutHandler;
                this.currentStopHandler    = stopHandler;
                this.timerRunning          = true;
                this.startEvent.Set();
            }
        }
示例#9
0
        private void ExecuteAction(DoseTest.Action action)
        {
            switch (action.ActionKind.Val)
            {
            case DoseTest.ActionEnum.Enumeration.Reset:
                if (m_isActive)
                {
                    m_testConnection.Close();

                    Dispatcher oldDispatcher = m_testDispatcher; //keep this for a while, so we get a new dispatcher address.
                    m_testDispatcher = new Dispatcher(m_testDispatchEvent);
                    if (oldDispatcher != null)                   //add a check to avoid a warning from mono
                    {
                        oldDispatcher = null;
                    }

                    StopHandler oldStopHandler = m_testStopHandler;      //keep this for a while, so we get a new stopHandler address.
                    m_testStopHandler = new StopHandler();
                    if (oldStopHandler != null)
                    {
                        oldStopHandler = null;
                    }

                    m_testConnection.Open(m_testConnectionName, m_instanceString, m_defaultContext, null, m_testDispatcher);
                    using (Safir.Dob.EntityProxy ep = m_controlConnection.Read(m_partnerEntityId))
                    {
                        DoseTest.Partner partner = ep.Entity as DoseTest.Partner;
                        if (partner.Incarnation.IsNull())
                        {
                            partner.Incarnation.Val = 0;
                        }
                        else
                        {
                            partner.Incarnation.Val = partner.Incarnation.Val + 1;
                        }
                        m_controlConnection.SetChanges(partner, m_partnerEntityId.InstanceId, new Safir.Dob.Typesystem.HandlerId(m_instance));
                    }
                    Consumer[] oldCons = m_consumers;     //keep these for a while, so we get new consumer addresses.
                    m_consumers = new Consumer[3];

                    for (int i = 0; i < 3; ++i)
                    {
                        m_consumers[i] = new Consumer(i, m_testConnectionName, m_instanceString);
                    }

                    if (oldCons != null)    //avoid warning...
                    {
                        oldCons = null;
                    }

                    foreach (KeyValuePair <Safir.Dob.CallbackId.Enumeration, List <DoseTest.Action> > cbActions
                             in m_callbackActions)
                    {
                        cbActions.Value.Clear();
                    }
                }
                break;

            case DoseTest.ActionEnum.Enumeration.CheckReferences:
                if (m_isActive)
                {
                    if (m_consumers != null)
                    {
                        m_consumers = null;
                    }

                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();

                    // After releasing the executor's references and a garabage collection, there should be no
                    // Consumer instances
                    if (Consumer.instanceCount != 0)
                    {
                        Logger.Instance.WriteLine("Expected 0 consumer instances, but there is " + Consumer.instanceCount);
                    }

                    // restore consumers
                    m_consumers = new Consumer[3];
                    for (int i = 0; i < 3; ++i)
                    {
                        m_consumers[i] = new Consumer(i, m_testConnectionName, m_instanceString);
                    }
                }
                break;

            case DoseTest.ActionEnum.Enumeration.CloseAndCheckReferences:
                if (m_isActive)
                {
                    m_testConnection.Close();

                    if (m_consumers != null)
                    {
                        m_consumers = null;
                    }

                    if (m_testDispatcher != null)
                    {
                        m_testDispatcher = null;
                    }

                    if (m_testStopHandler != null)
                    {
                        m_testStopHandler = null;
                    }

                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();

                    // After releasing the executor's references and a garabage collection, there should be no
                    // Consumer instances and no Dispatcher instances
                    if (Consumer.instanceCount != 0)
                    {
                        Logger.Instance.WriteLine("Expected 0 consumer instances, but there is " + Consumer.instanceCount);
                    }
                    if (Dispatcher.instanceCount != 0)
                    {
                        Logger.Instance.WriteLine("Expected 0 dispatcher instances, but there is " + Dispatcher.instanceCount);
                    }
                    if (StopHandler.instanceCount != 0)
                    {
                        Logger.Instance.WriteLine("Expected 0 stopHandler instances, but there is " + StopHandler.instanceCount);
                    }

                    // Restore dispatcher
                    m_testDispatcher = new Dispatcher(m_testDispatchEvent);

                    m_testConnection.Open(m_testConnectionName, m_instanceString, 0, null, m_testDispatcher);

                    // Restore consumers
                    m_consumers = new Consumer[3];
                    for (int i = 0; i < 3; ++i)
                    {
                        m_consumers[i] = new Consumer(i, m_testConnectionName, m_instanceString);
                    }

                    // Restore stopHandler
                    m_testStopHandler = new StopHandler();
                }
                break;

            case DoseTest.ActionEnum.Enumeration.RunGarbageCollector:
                if (m_isActive)
                {
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                }
                break;

            case DoseTest.ActionEnum.Enumeration.Open:
            {
                if (m_isActive)
                {
                    System.Int32 context = m_defaultContext;
                    if (!action.Context.IsNull())
                    {
                        context = action.Context.Val;
                    }

                    string connName = m_testConnectionName;
                    if (!action.ConnectionName.IsNull())
                    {
                        connName = action.ConnectionName.Val;
                    }
                    m_testConnection.Open(connName, m_instanceString, context, m_testStopHandler, m_testDispatcher);
                }
            }
            break;

            case DoseTest.ActionEnum.Enumeration.Close:
            {
                if (m_isActive)
                {
                    m_testConnection.Close();
                }
            }
            break;

            case DoseTest.ActionEnum.Enumeration.InhibitDispatch:
                if (m_isActive)
                {
                    m_dispatchTestConnection = !action.Inhibit.Val;
                    Logger.Instance.WriteLine("InhibitDispatch set to " + m_dispatchTestConnection);
                }
                break;

            case DoseTest.ActionEnum.Enumeration.InhibitOutgoingTraffic:
                if (m_isActive)
                {
                    byte success;
                    InhibitOutgoingTraffic(ByteOf(action.Inhibit.Val), out success);
                    Logger.Instance.WriteLine("InhibitOutgoingTraffic set to " + ByteOf(action.Inhibit.Val));
                }
                break;

            case DoseTest.ActionEnum.Enumeration.Print:
                if (m_isActive)
                {
                    Logger.Instance.WriteLine(action.PrintString.Val);
                }
                break;

            case DoseTest.ActionEnum.Enumeration.ResetCallbackActions:
                foreach (KeyValuePair <Safir.Dob.CallbackId.Enumeration, List <DoseTest.Action> > cbActions
                         in m_callbackActions)
                {
                    cbActions.Value.Clear();
                }
                break;

            case DoseTest.ActionEnum.Enumeration.Sleep:
            {
                if (m_isActive)
                {
                    System.Console.WriteLine("Sleeping " + action.SleepDuration.Val + " seconds");
                    System.Threading.Thread.Sleep((int)(action.SleepDuration.Val * 1000.0));
                }
            }
            break;

            default:
                Logger.Instance.WriteLine("Got unexpected action " + action.ActionKind.Val);
                break;
            }
        }
示例#10
0
 /// <summary>
 /// Closes all the handlers for the imageServer (invoked when service is terminated)..
 /// </summary>
 public void CloseImageServer()
 {
     StopHandler.Invoke(this, new DirectoryCloseEventArgs("*", null));
 }
示例#11
0
        /// <summary>
        /// Method responsible for the optimization.
        /// </summary>
        /// <returns>An object containing the optimized values of the parameters as well as other characteristics of the optimization process.</returns>
        public Result Optimize(ArrayList ElementsTrans)
        {
            bool genRand = ElementsTrans == null;

            // Create a list object for elementes.
            Elements = new ArrayList();
            if (!genRand)
            {
                // Transfer elements importing
                foreach (BaseElement Element in ElementsTrans)
                {
                    Elements.Add(GetNewElement(FitnessFunction, Element.Position));
                }
            }
            // Create a random number generator object.
            RNG = new Random();
            // The ordinal number of the actual generation.
            Generation = 1;
            // Define a logical variable that keeps track of the current state.
            Stop = false;
            // Start execturion timer
            var timer = new System.Diagnostics.Stopwatch();

            timer.Reset();
            timer.Start();
            if (genRand)
            {
                // Put the first element into the pool.
                Elements.Add(GetNewElement(FitnessFunction, InitialParameters));
            }
            // Initializing the first element takes an evaluation, so we initialize to one
            Evaluation = 1;
            // Check if the stopping condition was met
            if (StopHandler != null)
            {
                Stop = StopHandler.Invoke(this, Elements);
            }
            else
            {
                CheckStop();
            }
            // Create an object for the returned information.
            Info = new Dictionary <InfoTypes, object>();
            // Add the affinity (performance) corresponding to the initial parameter values.
            Info.Add(InfoTypes.InitialFitness, ((BaseElement)Elements[0]).Fitness);
            if (genRand)
            {
                // Create the rest of the initial pool (first generation) of elementes creating elementes at random positions.
                CreateRandomElements(NumberOfElements - 1);
            }
            // Raise GenerationCreated event if there are any subscribers.
            GenerationCreated?.Invoke(this, Elements, GetFitnesses());
            ArrayList BestAffinities = new ArrayList();

            BestAffinities.Add(((BaseElement)Elements[0]).Fitness);
            if (StopHandler != null)
            {
                Stop = StopHandler.Invoke(this, Elements);
            }
            else
            {
                CheckStop();
            }

            //Begin the optimization process
            while (!Stop)
            {
                if (Slow)
                {
                    System.Threading.Thread.Sleep(100);
                }
                Generation++;
                // Create next generation.
                CreateNextGeneration();
                BestAffinities.Add(((BaseElement)Elements[0]).Fitness);
                // Raise GenerationCreated event if there are any subscribers.
                GenerationCreated?.Invoke(this, Elements, GetFitnesses());
                // Stop if the stopping criteria is the number of generations and the number of allowed generations is reached
                if (StopHandler != null)
                {
                    Stop = StopHandler.Invoke(this, Elements);
                }
                else
                {
                    CheckStop();
                }
            }
            // Stop timer
            timer.Stop();
            // Create an array for the parameters (position) of the best antibody.
            var Best = new ArrayList();

            for (int dim = 0; dim < InitialParameters.Count; dim++)
            {
                Best.Add(((BaseElement)Elements[0])[dim]);
            }
            // Add the affinity (performance) value of the best antibody to the returned information.
            Info.Add(InfoTypes.FinalFitness, ((BaseElement)Elements[0]).Fitness);
            // Add munber of generations.
            Info.Add(InfoTypes.Generations, Generation);
            // Add number of affinity evaluations.
            Info.Add(InfoTypes.Evaluations, Evaluation);
            // Define returned values.
            Info.Add(InfoTypes.Affinities, BestAffinities);
            // Add execution time to result info
            Info.Add(InfoTypes.ExecutionTime, timer.ElapsedMilliseconds);
            var res = new Result(Best, Info);

            return(res);
        }