Beispiel #1
0
        public void CanPersistAndRestore()
        {
            IWorkflowEntity toReturn = new WorkflowEntity();

            _workflowPersister.Expect(p => p.CreateEmptyWorkflowEntity(Guid.Empty)).IgnoreArguments().Return(toReturn);
            _workflowPersister.Expect(p => p.Save(new WorkflowEntity())).IgnoreArguments().Callback <IWorkflowEntity>(x =>
            {
                toReturn = x;
                return(true);
            });
            IStateMachineContext machineContext = _workflowService.Start(@"testStateMachine.boo");

            Assert.IsNotNull(machineContext);
            Assert.IsTrue(machineContext.IsStarted);
            Assert.IsNotNull(toReturn);
            Assert.That(Guid.Empty == toReturn.WorkflowId, Is.Not.True);

            Assert.AreEqual("Initial", machineContext.CurrentState.StateName);
            Assert.AreNotEqual(Guid.Empty, machineContext.Id);

            _workflowPersister.Expect(p => p.Load(new Guid())).IgnoreArguments().Return(toReturn);

            IStateMachineContext restoredMachine = _workflowService.Load(machineContext.Id);

            Assert.AreNotSame(restoredMachine, _workflowService);

            Assert.IsTrue(restoredMachine.IsStarted);
            Assert.AreEqual(machineContext.CurrentState.StateName, restoredMachine.CurrentState.StateName);

            _workflowPersister.VerifyAllExpectations();
        }
Beispiel #2
0
        public void CanCreateSaveUpdateAndComplete()
        {
            IWorkflowEntity toReturn = new WorkflowEntity();

            _workflowPersister.Expect(p => p.CreateEmptyWorkflowEntity(Guid.Empty)).IgnoreArguments().Repeat.Times(1).Return(toReturn);
            _workflowPersister.Expect(p => p.Load(Guid.Empty)).IgnoreArguments().Repeat.Times(2).Return(toReturn);
            _workflowPersister.Expect(p => p.Save(toReturn));
            _workflowPersister.Expect(p => p.Update(toReturn));
            _workflowPersister.Expect(p => p.Complete(toReturn));

            IStateMachineContext machineContext = _workflowService.Start(@"simplestatemachine.boo");

            Assert.IsNotNull(machineContext);
            Assert.IsTrue(machineContext.IsStarted);

            Assert.AreEqual("Initial", machineContext.CurrentState.StateName);

            // should trigger the Update
            machineContext.HandleEvent(1);

            Assert.AreEqual("First", machineContext.CurrentState.StateName);

            // should trigger the Complete
            machineContext.HandleEvent(3);

            _workflowPersister.VerifyAllExpectations();
        }
        public static List <IStateMachineEventAction> GetMatchingEventActions(this IStateMachineContext context, object eventIdentifier)
        {
            var actions = new List <IStateMachineEventAction>();

            if (context == null || context.StateMachine == null)
            {
                return(actions);
            }

            if (context.StateMachine.EventActions != null)
            {
                foreach (IStateMachineEventAction action in context.StateMachine.EventActions)
                {
                    if (action.Matches(context, eventIdentifier))
                    {
                        actions.Add(action);
                    }
                }
            }

            if (context.CurrentState != null && context.CurrentState.EventActions != null)
            {
                foreach (IStateMachineEventAction action in context.CurrentState.EventActions)
                {
                    if (action.Matches(context, eventIdentifier))
                    {
                        actions.Add(action);
                    }
                }
            }

            return(actions);
        }
        public static IStateMachineContext UseLazyHandlerArgs(this IStateMachineContext context, Func <IPipeContext, object[]> argsFunc)
        {
            Func <IPipeContext, Func <IPipeContext, object[]> > lazyFunc = pipeContext => argsFunc;

            context.Properties.TryAdd(StateMachineKey.LazyHandlerArgsFunc, lazyFunc);
            return(context);
        }
        public static List <IStateTransitionAction> GetMatchingTransitionActions(this IStateMachineContext context,
                                                                                 StateTransitionPhase transitionPhase)
        {
            var actions = new List <IStateTransitionAction>();

            if (context == null || context.StateMachine == null)
            {
                return(actions);
            }

            if (context.StateMachine.StateTransitionActions != null)
            {
                foreach (IStateTransitionAction action in context.StateMachine.StateTransitionActions)
                {
                    if (action.Matches(context, transitionPhase))
                    {
                        actions.Add(action);
                    }
                }
            }

            if (context.CurrentState != null && context.CurrentState.StateTransitionActions != null)
            {
                foreach (IStateTransitionAction action in context.CurrentState.StateTransitionActions)
                {
                    if (action.Matches(context, transitionPhase))
                    {
                        actions.Add(action);
                    }
                }
            }

            return(actions);
        }
        public static IStateTransition FindFirstMatchingTransition(this IStateMachineContext context,
                                                                   IStateMachineEvent transitionEvent)
        {
            if (context == null || context.CurrentState == null)
            {
                return(null);
            }

            if (transitionEvent == null)
            {
                throw new ArgumentNullException("transitionEvent");
            }

            if (context.CurrentState.Transitions == null)
            {
                return(null);
            }

            foreach (IStateTransition transition in context.CurrentState.Transitions)
            {
                if (transition.Matches(transitionEvent, context))
                {
                    return(transition);
                }
            }
            return(null);
        }
        public static List <IStateTransition> FindMatchingTransitions(this IStateMachineContext context)
        {
            if (context == null || context.CurrentState == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.CurrentState.Transitions == null)
            {
                return(null);
            }

            List <IStateTransition> transitions = new List <IStateTransition>();

            foreach (IStateTransition transition in context.CurrentState.Transitions)
            {
                if (transition.Matches("NA", context))
                {
                    transitions.Add(transition);
                }
            }
            if (transitions.Count > 0)
            {
                return(transitions);
            }
            else
            {
                return(null);
            }
        }
Beispiel #8
0
 public StateBehaviourBuilder(IState <TState, TInput> source, IStateDictionary <TState, TInput> states, IStateMachineContext <TState, TInput> context)
 {
     _source      = source;
     _states      = states;
     _context     = context;
     _transitions = new List <TransitionInfo>();
 }
 private void BindToWorkflow(IStateMachineContext workflow)
 {
     _currentWorkflow = workflow;
     if (_currentWorkflow != null)
     {
         availableActionPanel1.Workflow     = _currentWorkflow;
         _currentWorkflow.StateInitialized += _currentWorkflow_StateInitialized;
     }
 }
Beispiel #10
0
 public StateMachine(string name, IStateMachineContext <TState, TInput> context)
 {
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
     Name         = name;
     this.context = context;
     states       = new StateDictionary <TState, TInput>(this.context);
 }
        public void LateUpdate(float deltaTime, StateMachine stateMachine, IStateMachineContext context)
        {
            if (!_contextType.IsAssignableFrom(context.GetType()))
            {
                // Log Or throw exception
                return;
            }

            LateUpdate(deltaTime, stateMachine, (TContext)context);
        }
        public void Exit(IStateMachineContext context)
        {
            if (!_contextType.IsAssignableFrom(context.GetType()))
            {
                // Log Or throw exception
                return;
            }

            Exit((TContext)context);
        }
 public void HandleStateTransition(IStateMachineContext <IState <Transitions>, Transitions> stateContext, Transitions transition)
 {
     if (transition == Transitions.Play)
     {
         stateContext.State = new Playing();
     }
     else
     {
         throw new InvalidStateTransitionException(transition);
     }
 }
        private void UnBindFromWorkflow()
        {
            if (_currentWorkflow == null)
            {
                return;
            }

            availableActionPanel1.Workflow     = null;
            _currentWorkflow.StateInitialized -= _currentWorkflow_StateInitialized;
            _currentWorkflow = null;
        }
        private void BindToWorkflow(IStateMachineContext workflow)
        {
            _workflow = workflow;
            if (_workflow != null)
            {
                _workflow.StateMachineStarted  += _workflow_StateMachineStarted;
                _workflow.StateMachineComplete += _workflow_StateMachineComplete;
                _workflow.StateInitialized     += _workflow_StateInitialized;

                RefreshButtonAvailability();
            }
        }
Beispiel #16
0
        public void CanCreateUsingWorkflowServiceTest()
        {
            IWorkflowEntity toReturn = new WorkflowEntity();

            _workflowPersister.Expect(p => p.CreateEmptyWorkflowEntity(Guid.Empty)).IgnoreArguments().Return(toReturn);
            IStateMachineContext machineContext = _workflowService.Start(@"testStateMachine.boo");

            Assert.IsNotNull(machineContext);
            Assert.IsTrue(machineContext.IsStarted);

            _workflowPersister.VerifyAllExpectations();
        }
        public void ChangeState(object sender, IState nextState, IStateMachineContext context)
        {
            if (!context.IsActive && sender != null)
            {
                return;
            }

            if (sender == context.CurrentState)
            {
                ChangeState(nextState, context);
            }
        }
        /// <summary>
        /// Calls in LateUpdate loop
        /// </summary>
        /// <param name="deltaTime"><see cref="Time.deltaTime"/></param>
        public void LateUpdate(float deltaTime, IStateMachineContext context)
        {
            if (!context.IsActive)
            {
                return;
            }

            if (context.CurrentState != null)
            {
                context.CurrentState.LateUpdate(deltaTime, this, context);
            }
        }
 public override async Task<StateResult> OnEntry(IStateMachineContext<IExecutionContext> context) {
     try {
         Interruptable = false;
         await DeActivateWorker(context.ExecutionContext);
         context.ExecutionContext.IsMaster = false;
         await ContactNeighbours(context.ExecutionContext);
         PostObit(context);
     }
     finally {
         Interruptable = true;
     }
     return FinalResult;
 }
        private void UnBindFromWorkflow()
        {
            if (_workflow != null)
            {
                _workflow.StateMachineStarted  -= _workflow_StateMachineStarted;
                _workflow.StateMachineComplete -= _workflow_StateMachineComplete;
                _workflow.StateInitialized     -= _workflow_StateInitialized;

                _workflow = null;

                _pnlButtonContainer.Controls.Clear();
            }
        }
Beispiel #21
0
 protected virtual void CoreExitImpl(IStateMachineContext <TState, TInput> context)
 {
     foreach (var exitAction in exitActions)
     {
         try
         {
             exitAction.Execute(context);
         }
         catch (Exception e)
         {
             context.HandleException(e);
         }
     }
 }
        /// <summary>
        /// Gets the domain context.
        /// </summary>
        /// <param name="workFlow">The work flow.</param>
        /// <returns></returns>
        private static object GetDomainContext(IStateMachineContext workFlow)
        {
            object domainContext;

            if (workFlow.DomainContext is ReflectiveDomainContextWrapper)
            {
                domainContext = ((ReflectiveDomainContextWrapper)workFlow.DomainContext).DomainContext;
            }
            else
            {
                domainContext = workFlow.DomainContext;
            }
            return(domainContext);
        }
Beispiel #23
0
        public void CanPersistAndRestoreDomainContextWithStatusProperty()
        {
            var user = new User();

            user.StatusChanged += user_StatusChanged;

            _domainContextRepository.Expect(x => x.GetId(user)).Return(user.Id);
            _domainContextRepository.Expect(x => x.GetTypeDescription(user)).Return("SimpleStateMachine.User");
            _domainContextRepository.Expect(x => x.Save(user));
            _domainContextRepository.Expect(x => x.Load("SimpleStateMachine.User", user.Id)).Return(new User());

            IWorkflowEntity toReturn = new WorkflowEntity();

            _workflowPersister.Expect(p => p.CreateEmptyWorkflowEntity(Guid.Empty)).IgnoreArguments().Return(toReturn);

            _workflowPersister.Expect(p => p.Save(new WorkflowEntity())).IgnoreArguments().Callback <IWorkflowEntity>(x =>
            {
                toReturn = x;
                return(true);
            });

            IStateMachineContext machineContext = _workflowService.Start(@"testStateMachine.boo", user, "CurrentStatus");

            Assert.IsNotNull(machineContext);
            Assert.IsTrue(machineContext.IsStarted);

            Assert.AreEqual(user.CurrentStatus, machineContext.CurrentState.StateIdentifier);
            Assert.AreEqual(1, _userStateChangedCount);

            _workflowPersister.Expect(p => p.Load(new Guid())).IgnoreArguments().Return(toReturn);

            IStateMachineContext restoredMachine = _workflowService.Load(machineContext.Id);

            Assert.IsAssignableFrom(typeof(ReflectiveDomainContextWrapper), restoredMachine.DomainContext);

            var contextWrapper = (ReflectiveDomainContextWrapper)restoredMachine.DomainContext;

            Assert.IsAssignableFrom(typeof(User), contextWrapper.DomainContext);

            // should be the newly loaded user.
            Assert.AreNotEqual(contextWrapper.DomainContext, user);
            Assert.AreNotEqual(((User)contextWrapper.DomainContext).Id, user.Id);

            // state changed should not have been called!
            // is it up to the domain context repository to restore the state of the domain context.
            Assert.AreEqual(1, _userStateChangedCount);

            _domainContextRepository.VerifyAllExpectations();
            _workflowPersister.VerifyAllExpectations();
        }
Beispiel #24
0
 public void HandleStateTransition(IStateMachineContext <IState <Transitions>, Transitions> stateContext, Transitions transition)
 {
     if (transition == Transitions.Pause)
     {
         stateContext.State = new Paused();
     }
     else if (transition == Transitions.Stop)
     {
         stateContext.State = new Stopped();
     }
     else
     {
         throw new InvalidStateTransitionException(transition);
     }
 }
        private void ChangeState(IState newState, IStateMachineContext context)
        {
            if (context.DebugStateMachine)
            {
                Debug.Log(context.GO.name + " " + context.GetType().Name + " " + newState.GetType().Name);
            }

            if (context.CurrentState != null)
            {
                context.CurrentState.Exit(context);
            }
            context.CurrentState = newState;
            if (context.CurrentState != null)
            {
                context.CurrentState.Enter(context);
            }
        }
Beispiel #26
0
 public UpdateHandler(
     ILifetimeScope lifetimeScope,
     IUpdateContext updateContext,
     IStateMachineConfigurationProvider configurationProvider,
     IStateMachineContext stateMachineContext,
     IIdentityStatesService identityStatesService,
     IEnumerable <IUpdateInterceptor> updateInterceptors,
     ILogger <UpdateHandler> logger)
 {
     _lifetimeScope         = lifetimeScope;
     _updateContext         = updateContext;
     _configurationProvider = configurationProvider;
     _stateMachineContext   = stateMachineContext;
     _identityStatesService = identityStatesService;
     _updateInterceptors    = updateInterceptors;
     _logger = logger;
 }
        public virtual bool Matches(object eventId, IStateMachineContext context)
        {
            if (TriggerEvent != null)
            {
                if (TriggerEvent.Matches(eventId) || (eventId is string && (eventId.ToString().Equals("NA"))))
                {
                    if (this.RolesRequired != null && this.RolesRequired.Count > 0)
                    {
                        foreach (string role in this.RolesRequired)
                        {
                            AFEContext afe = new AFEContext();
                            afe.Assignments = new List <AFEAssignment>();
                            afe.UserID      = 1;
                            afe.Assignments.Add(new AFEAssignment()
                            {
                                AfeRoleCode = "AAPR", Order = 1, UserID = 1
                            });
                            afe.Assignments.Add(new AFEAssignment()
                            {
                                AfeRoleCode = "AAPR", Order = 2, UserID = 2
                            });


                            bool IsLastUserInTheCurrentOrder = afe.IsLastUserInTheCurrentOrder(role);

                            bool IsLastPersonInTheCurrentRole = afe.IsLastPersonInTheCurrentRole(role);

                            if (afe.Assignments.FindAll(t => t.AfeRoleCode == role && t.UserID == afe.UserID).Count > 0)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        public static void SetState(this IStateMachineContext context, object stateIdentifier)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (stateIdentifier == null)
            {
                throw new ArgumentNullException("stateIdentifier");
            }

            IStateMachineState target = FindState(context.StateMachine, stateIdentifier);

            if (target != null)
            {
                context.SetState(target);
            }
        }
Beispiel #29
0
        public void CanPersistAndRestoreDomainContext()
        {
            var user = new User();

            user.StatusChanged += user_StatusChanged;

            _domainContextRepository.Expect(x => x.GetId(user)).Return(user.Id);
            _domainContextRepository.Expect(x => x.GetTypeDescription(user)).Return("SimpleStateMachine.User");
            _domainContextRepository.Expect(x => x.Save(user));
            _domainContextRepository.Expect(x => x.Load("SimpleStateMachine.User", user.Id)).Return(new User());

            IWorkflowEntity toReturn = new WorkflowEntity();

            _workflowPersister.Expect(p => p.CreateEmptyWorkflowEntity(Guid.Empty)).IgnoreArguments().Return(toReturn);
            _workflowPersister.Expect(p => p.Save(new WorkflowEntity())).IgnoreArguments().Callback <IWorkflowEntity>(x =>
            {
                toReturn = x;
                return(true);
            });

            IStateMachineContext machineContext = _workflowService.Start(@"testStateMachine.boo", user);

            Assert.IsNotNull(machineContext);
            Assert.IsTrue(machineContext.IsStarted);

            _workflowPersister.Expect(p => p.Load(new Guid())).IgnoreArguments().Return(toReturn);

            IStateMachineContext restoredMachine = _workflowService.Load(machineContext.Id);

            Assert.IsAssignableFrom(typeof(User), restoredMachine.DomainContext);

            // should be the newly loaded user.
            Assert.AreNotEqual(restoredMachine.DomainContext, user);
            Assert.AreNotEqual(((User)restoredMachine.DomainContext).Id, user.Id);
            // should have never been called
            Assert.AreEqual(0, _userStateChangedCount);

            _domainContextRepository.VerifyAllExpectations();
            _workflowPersister.VerifyAllExpectations();
        }
Beispiel #30
0
 public static Neighbour Fabricate(IStateMachineContext<IExecutionContext> context) {
     var cfg = new Configuration().WithAppropriateOverrides();
     var nexus = cfg.Get(Constants.Configuration.Nexus);
     var strength = cfg.Get(Constants.Configuration.MachineStrength);
     var actualStrength = string.IsNullOrEmpty(strength) ? MachineStrength.Compute : (MachineStrength)Enum.Parse(typeof(MachineStrength), strength, true);
     return new Neighbour {
         IsMaster = context.ExecutionContext.IsMaster,
         Name = context.ExecutionContext.HostName,
         UpTime = context.EnclosingMachine.UpTime,
         AbsoluteBootTime = context.EnclosingMachine.AbsoluteBootTime,
         Strength = actualStrength.ToString(),
         // Could be null if not yet interrogated
         Hardware = HardwareDetails.Instance ?? new HardwareDetails(),
         InEligibleForElection = context.ExecutionContext.InEligibleForElection,
         PendingEvents = context.EnclosingMachine.PendingEvents.Select(e => new PendingEvent { Id = e.Id, Name = e.EventName, CreatedOn = e.CreatedOn, AgeInSeconds = (DateTime.Now - e.CreatedOn).TotalSeconds }).ToArray(),
         HandledEvents = context.EnclosingMachine.StatisticsHandler.HandledEventsInNameOrder.ToArray(),
         WorkUnitsExecuted = context.ExecutionContext.WorkerExecutionUnits,
         NodeId = context.ExecutionContext.NodeId,
         SupposedNeighbours = string.IsNullOrEmpty(nexus) ? Enumerable.Empty<string>().ToArray() : nexus.Split(','),
         CurrentState = context.EnclosingMachine.CurrentState.IsNull() ? "None" : context.EnclosingMachine.CurrentState.Name
     };
 }
Beispiel #31
0
        public void IdOfContextMatchesIdOfLoadedMachineTest()
        {
            IWorkflowEntity toReturn = new WorkflowEntity();

            _workflowPersister.Expect(p => p.CreateEmptyWorkflowEntity(Guid.Empty)).IgnoreArguments().Return(toReturn);

            _workflowPersister.Expect(p => p.Save(new WorkflowEntity())).IgnoreArguments().Callback <IWorkflowEntity>(x =>
            {
                toReturn = x;
                return(true);
            });

            IStateMachineContext machineContext = _workflowService.Start(@"testStateMachine.boo");

            Assert.IsNotNull(machineContext);
            Assert.IsTrue(machineContext.IsStarted);

            _workflowPersister.Expect(p => p.Load(new Guid())).IgnoreArguments().Return(toReturn);

            IStateMachineContext restoredMachine = _workflowService.Load(machineContext.Id);

            Assert.AreEqual(restoredMachine.Id, machineContext.Id);
        }
Beispiel #32
0
 public override Task<StateResult> OnEntry(IStateMachineContext<IExecutionContext> context) {
     context.ExecutionContext.IsMaster = true;
     EnsureWorkerActive(context.ExecutionContext);
     return Task.FromResult(StateResult.None);
 }
Beispiel #33
0
 public static Neighbour CreateNeighbour(IStateMachineContext<IExecutionContext> ctx, Action<Neighbour> f = null) {
     Neighbour n = Neighbour.Fabricate(ctx);
     if (f != null)
         f(n);
     return n;
 }
Beispiel #34
0
 protected override void PostObit(IStateMachineContext<IExecutionContext> context) {
     //ChannelPrototype.Respond(context.CurrentEvent.ResponseContainer, "Accepted", Configuration.Get<int>(Constants.Configuration.ResponseLimit));
     context.ExecutionContext.InEligibleForElection = true;
     LogFacade.Instance.LogInfo("Marking self as IN-eligible for election");
 }
 protected virtual void PostObit(IStateMachineContext<IExecutionContext> context) { }
Beispiel #36
0
 public override async Task<StateResult> OnEntry(IStateMachineContext<IExecutionContext> context) {
     await DeActivateWorker(context.ExecutionContext);
     context.ExecutionContext.IsMaster = false;
     return StateResult.None;
 }
Beispiel #37
0
 public abstract void Setup(IStateMachineContext _context);