Пример #1
0
		public override BehaviorStatus UpdateTick(BehaviorContext context)
		{
			var unit = (Unit) context[_subjectVar];
			var targetStack = (Stack_Object) context[_targetStack];

			var potentialClues = unit.GetPotentialClues();

			if (potentialClues.Length == 0)
				return BehaviorStatus.Failure;


			if (targetStack.Count == 0)
			{
				targetStack = new Stack_Object(potentialClues);
				context[_targetStack] = targetStack;
			}
			else
			{
				for (var i = 0; i < potentialClues.Length; i++)
				{
					targetStack.Push(potentialClues[i]);
				}
			}

			return BehaviorStatus.Success;
		}
Пример #2
0
        public void Invoke(BehaviorContext context, Action next)
        {
            // for now we cheat and pull it from the behavior context:
            var callbackInvoked = context.Get<bool>(CallbackInvocationBehavior.CallbackInvokedKey);
            var messageHandlers = new LoadedMessageHandlers();

            foreach (var messageToHandle in context.Get<LogicalMessages>())
            {
                var handlerTypedToInvoke = HandlerRegistry.GetHandlerTypes(messageToHandle.MessageType).ToList();

                if (!callbackInvoked && !handlerTypedToInvoke.Any())
                {
                    var error = string.Format("No handlers could be found for message type: {0}", messageToHandle.MessageType);
                    throw new InvalidOperationException(error);
                }

                foreach (var handlerType in handlerTypedToInvoke)
                {
                    messageHandlers.AddHandler(messageToHandle.MessageType, context.Builder.Build(handlerType));
                }
            }

            context.Set(messageHandlers);

            next();
        }
        public void Invoke(BehaviorContext context, Action next)
        {
            var messageWasHandled = HandleCorrelatedMessage(context.TransportMessage, context.Get<LogicalMessages>());

            context.Set(CallbackInvokedKey, messageWasHandled);

            next();
        }
Пример #4
0
		public BehaviorContext GetNewContext()
		{
			var newContext = new BehaviorContext();

			behaviorContexts.Add(new WeakReferenceT<BehaviorContext>(newContext));

			return newContext;
		}
Пример #5
0
        void DispatchMessageToHandlersBasedOnType(IBuilder builder, LogicalMessage toHandle, LoadedMessageHandlers loadedHandlers, BehaviorContext context)
        {
            foreach (var loadedHandler in loadedHandlers.GetHandlersFor(toHandle.MessageType))
            {
                if (loadedHandler.InvocationDisabled)
                    continue;

                var handlerInstance = loadedHandler.Instance;
                try
                {
                    //until we have a outgoing pipeline that inherits context from the main one
                    if (handlerInstance is ISaga)
                    {
                        SagaContext.Current = (ISaga) handlerInstance;
                    }

                    var handlerTypeToInvoke = handlerInstance.GetType();

                    //for backwards compatibility (users can have registered their own factory
                    var factory = GetDispatcherFactoryFor(handlerTypeToInvoke, builder);

                    if (factory != null)
                    {
                        var dispatchers = factory.GetDispatcher(handlerTypeToInvoke, builder, toHandle.Instance).ToList();

                        dispatchers.ForEach(dispatch =>
                        {
                            log.DebugFormat("Dispatching message '{0}' to handler '{1}'", toHandle.MessageType, handlerTypeToInvoke);
                            try
                            {
                                dispatch();
                            }
                            catch (Exception e)
                            {
                                log.Warn(handlerTypeToInvoke.Name + " failed handling message.", e);

                                throw new TransportMessageHandlingFailedException(e);
                            }
                        });
                    }
                    else
                    {
                        loadedHandler.Invocation(handlerInstance, toHandle.Instance);
                    }

                    //for now we have to check of the chain is aborted but this will go away when we refactor the handlers to be a subpipeline
                    if (context.ChainAborted)
                    {
                        log.DebugFormat("Handler {0} requested downstream handlers of message {1} to not be invoked", handlerTypeToInvoke,toHandle.MessageType);
                        return;
                    }
                }
                finally
                {
                    SagaContext.Current = null;
                }
            }
        }
Пример #6
0
        internal IncomingContext(BehaviorContext parentContext, TransportMessage transportMessage)
            : base(parentContext)
        {
            handleCurrentMessageLaterWasCalled = false;

            Set(IncomingPhysicalMessageKey, transportMessage);

            LogicalMessages = new List<LogicalMessage>();
        }
        public void Invoke(BehaviorContext context, Action next)
        {
            var msg = context.TransportMessage;
            log.DebugFormat("Received message with ID {0} from sender {1}", msg.Id, msg.ReplyToAddress);

            next();

            log.Debug("Finished handling message.");
        }
Пример #8
0
        public void InvokeBehavior(IBuilder builder)
        {
            var runner = new UnitOfWorkBehavior();

            using (var context = new BehaviorContext(builder, new TransportMessage(), new BehaviorContextStacker()))
            {
                runner.Invoke(context, () => { });
            }
        }
        public ReceivePhysicalMessageContext(BehaviorContext parentContext, TransportMessage transportMessage, bool messageHandlingDisabled)
            : base(parentContext)
        {
            handleCurrentMessageLaterWasCalled = false;

            Set(IncomingPhysicalMessageKey, transportMessage);
            Set("MessageHandlingDisabled", messageHandlingDisabled);

            LogicalMessages = new List<LogicalMessage>();
        }
        public void Invoke(BehaviorContext context, Action next)
        {
            var mutators = context.Builder.BuildAll<IMutateIncomingTransportMessages>();

            foreach (var mutator in mutators)
            {
                mutator.MutateIncoming(context.TransportMessage);
            }

            next();
        }
Пример #11
0
		public virtual void Initialize(GameController gameController)
		{
			_gameController = gameController;
			
			var bState = gameController.behaviorState;

			_behaviorContext = bState.GetNewContext();

			InitializeBehaviorContext(_behaviorContext);


			InitializeBehaviorTree(bState);

		}
Пример #12
0
        public void Invoke(BehaviorContext context, Action next)
        {
            var messageHandlers = context.Get<LoadedMessageHandlers>();

            foreach (var messageToHandle in context.Get<LogicalMessages>())
            {
                ExtensionMethods.CurrentMessageBeingHandled = messageToHandle.Instance;

                DispatchMessageToHandlersBasedOnType(context.Builder, messageToHandle, messageHandlers,context);
            }

            ExtensionMethods.CurrentMessageBeingHandled = null;

            next();
        }
Пример #13
0
        public override BehaviorPriority DeterminePriority(BehaviorContext context)
        {
            foreach (Entity other in context.OtherEntities)
            {
                if (other.IsAiControlled) continue;

                var offset = Entity.PositionData.Placement.Pos - other.PositionData.Placement.Pos;

                if (offset.Length < 4)
                {
                    return BehaviorPriority.Value(4);
                }
            }

            return BehaviorPriority.NA;
        }
Пример #14
0
        public void Invoke(BehaviorContext context, Action next)
        {
            next();

            if (ForwardReceivedMessagesTo != null && ForwardReceivedMessagesTo != Address.Undefined)
            {
                MessageSender.ForwardMessage(context.TransportMessage, TimeToBeReceivedOnForwardedMessages, ForwardReceivedMessagesTo);
            }
            //To cope with people hacking UnicastBus.ForwardReceivedMessagesTo at runtime. will be removed when we remove UnicastBus.ForwardReceivedMessagesTo
            if (UnicastBus.ForwardReceivedMessagesTo != ForwardReceivedMessagesTo)
            {
                if (UnicastBus.ForwardReceivedMessagesTo != null && UnicastBus.ForwardReceivedMessagesTo != Address.Undefined)
                {
                    MessageSender.ForwardMessage(context.TransportMessage, UnicastBus.TimeToBeReceivedOnForwardedMessages, UnicastBus.ForwardReceivedMessagesTo);
                }
            }
        }
Пример #15
0
        public override void Behave(BehaviorContext context)
        {
            var horizontal = Entity.PositionData.Placement.Orientation.Horizontal;
            if (context.ElapsedDuration.Seconds >= 10.0 * Rng.NextExp())
            {
                horizontal = Rng.NextDouble() * 2 * Math.PI;
            }
            else if (context.ElapsedDuration.Seconds > 1.0 * Rng.NextExp())
            {
                horizontal += (Rng.NextDouble() * 2 - 1) * 0.25;
            }

            var orientation = Entity.PositionData.Placement.Orientation = new EntityOrientation(horizontal, 0);
            var velocity = -0.125 * context.PhysicsValues.PlayerMovementSpeed * (EntityOffset)orientation;
            Entity.PositionData.Velocity.X = velocity.X;
            Entity.PositionData.Velocity.Z = velocity.Z;
        }
        public void Invoke(BehaviorContext context, Action next)
        {
            foreach (var logicalMessage in context.Get<LogicalMessages>())
            {

                foreach (var mutator in context.Builder.BuildAll<IMutateIncomingMessages>())
                {
                    var current = logicalMessage.Instance;

                    //message mutators may need to assume that this has been set (eg. for the purposes of headers).
                    ExtensionMethods.CurrentMessageBeingHandled = current;

                    logicalMessage.UpdateMessageInstance(mutator.MutateIncoming(current));
                }
            }

            next();
        }
Пример #17
0
        public void Invoke(BehaviorContext context, Action next)
        {
            var principal = ExtractIncomingPrincipal.GetPrincipal(context.TransportMessage);

            if (principal == null)
            {
                next();
                return;
            }

            var previousPrincipal = Thread.CurrentPrincipal;
            try
            {
                Thread.CurrentPrincipal = principal;
                next();
            }
            finally
            {
                Thread.CurrentPrincipal = previousPrincipal;
            }
        }
Пример #18
0
        public void Invoke(BehaviorContext context, Action next)
        {
            try
            {
                foreach (var uow in context.Builder.BuildAll<IManageUnitsOfWork>())
                {
                    unitsOfWork.Push(uow);
                    uow.Begin();
                }

                next();

                while (unitsOfWork.Count > 0)
                {
                    unitsOfWork.Pop().End();
                }
            }
            catch (Exception exception)
            {
                AppendEndExceptionsAndRethrow(exception);
            }
        }
        public void Invoke(BehaviorContext context, Action next)
        {
            var logicalMessages = new LogicalMessages();

            context.Set(logicalMessages);

            if (SkipDeserialization || UnicastBus.SkipDeserialization)
            {
                return;
            }

            var transportMessage = context.TransportMessage;

            object[] rawMessages;

            try
            {
                rawMessages = Extract(transportMessage);
            }
            catch (Exception exception)
            {
                throw new SerializationException(string.Format("An error occurred while attempting to extract logical messages from transport message {0}", transportMessage), exception);
            }

            if (!transportMessage.IsControlMessage() && !rawMessages.Any())
            {
                log.Warn("Received an empty message - ignoring.");
                return;
            }

            foreach (var rawMessage in rawMessages)
            {
                var messageType = MessageMapper.GetMappedTypeFor(rawMessage.GetType());

                logicalMessages.Add(new LogicalMessage(messageType,rawMessage));
            }

            next();
        }
 private void LogOrderReceived(BehaviorContext <BurgerOrderStateInstance, OrderCreated> context)
 {
     _logger.LogInformation("Order recieved: {0}", context.Data.AggregateId);
 }
 public KafkaMessageSender(IRoutingTopology routingTopology, IChannelProvider channelProvider, BehaviorContext context)
 {
     this.routingTopology = routingTopology;
     this.channelProvider = channelProvider;
     this.context = context;
 }
Пример #22
0
		protected virtual void InitBehaviourTree()
		{

			const string SUBJECT = "S_SUBJECT";

			_behaviorContext = new BehaviorContext();
			_behaviorContext[SUBJECT] = this;

			if (BehaviorTreeGlobals.behaviorTrees.ContainsKey(BaseUnitBehaviorTreeKey)
				&& BehaviorTreeGlobals.behaviorTrees[BaseUnitBehaviorTreeKey].IsAlive)
			{
				behaviourTree = BehaviorTreeGlobals.behaviorTrees[BaseUnitBehaviorTreeKey].Target;
			}
			else
			{
				behaviourTree = new EntryNode(
					new IsNullNode("Ghello")
				, BaseUnitBehaviorTreeKey);
			}



//			BehaviorTreeGlobals.EntryNodes.Add(new WeakReferenceT<INode>(behaviourTree));
			BehaviorTreeGlobals.behaviorContexts.Add(new WeakReferenceT<BehaviorContext>(_behaviorContext));
		}
Пример #23
0
 public static Task RespondAsync <TInstance, TData, T>(this BehaviorContext <TInstance, TData> context, object values)
     where T : class
 {
     return(GetConsumeContext(context).RespondAsync <T>(values));
 }
Пример #24
0
 public static Task Publish <TInstance, TData, T>(this BehaviorContext <TInstance, TData> context, T message, IPipe <SendContext <T> > sendPipe)
     where T : class
 {
     return(GetConsumeContext(context).Publish(message, sendPipe));
 }
Пример #25
0
 public static Task Publish <TInstance, TData>(this BehaviorContext <TInstance, TData> context, object message, Type messageType,
                                               IPipe <SendContext> sendPipe)
 {
     return(GetConsumeContext(context).Publish(message, messageType, sendPipe));
 }
Пример #26
0
 public static Task <ISendEndpoint> GetSendEndpoint <TInstance, TData>(this BehaviorContext <TInstance, TData> context, Uri address)
 {
     return(GetConsumeContext(context).GetSendEndpoint(address));
 }
Пример #27
0
 Task Behavior <TInstance> .Execute <T>(BehaviorContext <TInstance, T> context)
 {
     return(_next.Faulted(_context));
 }
Пример #28
0
 Task Activity <TInstance> .Execute <TData>(BehaviorContext <TInstance, TData> context, Behavior <TInstance, TData> next)
 {
     return(next.Execute(context));
 }
Пример #29
0
 Task Behavior <TInstance> .Execute <T>(BehaviorContext <TInstance, T> context)
 {
     return(TaskUtil.Completed);
 }
Пример #30
0
 protected override bool OnExecute(BehaviorContext context)
 {
     return(!child.Execute(context));
 }
Пример #31
0
        public static Task Faulted <TInstance, TData>(Behavior <TInstance, TData> behavior, BehaviorContext <TInstance, TData> context,
                                                      Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            return(GetOrAdd(exception.GetType()).Faulted(behavior, context, exception));
        }
        private void Initialize(BehaviorContext <BurgerOrderStateInstance, SubmitBurgerOrder> context)
        {
            _logger.LogInformation("Initializing: {0}", context.Data.OrderId);

            InitializeInstance(context.Instance, context.Data);
        }
 private void LogOrderProcessed(BehaviorContext <BurgerOrderStateInstance, BurgerOrderProcessed> context)
 {
     _logger.LogInformation("Order processed: {0}", context.Data.OrderId);
 }
Пример #34
0
 /// <summary>
 /// Creates a new instance of <see cref="OutgoingContext"/>.
 /// </summary>
 /// <param name="parentContext">The parent context.</param>
 /// <param name="deliveryOptions">The delivery options.</param>
 /// <param name="message">The actual message to be sent out.</param>
 public OutgoingContext(BehaviorContext parentContext, DeliveryOptions deliveryOptions, LogicalMessage message)
     : base(parentContext)
 {
     Set(deliveryOptions);
     Set(OutgoingLogicalMessageKey, message);
 }
        public void OnSavingChild(BehaviorContext context)
        {
            if (!syncEnabled)
            {
                return;
            }

            var child  = context.AffectedItem;
            var parent = context.Parent;

            var initialState      = parent.ChildState;
            var childInducedState = child.GetCollectionState();

            if (parent.ChildState == CollectionState.IsEmpty)
            {
                // no previous child state
                parent.ChildState = childInducedState;
                context.UnsavedItems.Add(parent);
                return;
            }

            if (Is(initialState, CollectionState.IsLarge))
            {
                CollectionState newState = CollectionState.IsLarge;
                if (parent.Children.FindCount(Parameter.IsNull("ZoneName") & Parameter.Equal("Visible", true) & Parameter.Equal("AlteredPermissions", Permission.None)) > 0)
                {
                    newState |= CollectionState.ContainsVisiblePublicPages;
                }
                if (parent.Children.FindCount(Parameter.IsNull("ZoneName") & Parameter.Equal("Visible", false) & Parameter.Equal("AlteredPermissions", Permission.None)) > 0)
                {
                    newState |= CollectionState.ContainsHiddenPublicPages;
                }
                if (parent.Children.FindCount(Parameter.IsNull("ZoneName") & Parameter.Equal("Visible", true) & Parameter.NotEqual("AlteredPermissions", Permission.None)) > 0)
                {
                    newState |= CollectionState.ContainsVisibleSecuredPages;
                }
                if (parent.Children.FindCount(Parameter.IsNull("ZoneName") & Parameter.Equal("Visible", false) & Parameter.NotEqual("AlteredPermissions", Permission.None)) > 0)
                {
                    newState |= CollectionState.ContainsHiddenSecuredPages;
                }

                if (parent.Children.FindCount(Parameter.IsNotNull("ZoneName") & Parameter.Equal("AlteredPermissions", Permission.None)) > 0)
                {
                    newState |= CollectionState.ContainsPublicParts;
                }
                if (parent.Children.FindCount(Parameter.IsNotNull("ZoneName") & Parameter.NotEqual("AlteredPermissions", Permission.None)) > 0)
                {
                    newState |= CollectionState.ContainsSecuredParts;
                }

                if (newState != initialState)
                {
                    parent.ChildState = newState;
                    context.UnsavedItems.Add(parent);
                }
                return;
            }

            var reducedState = ReduceExistingStates(null, parent, initialState);

            if (reducedState == CollectionExtensions.None)
            {
                if (Is(initialState, childInducedState))
                {
                    // unchanged child state
                    return;
                }

                // added child state
                parent.ChildState |= childInducedState;
            }
            else
            {
                // changed child state
                parent.ChildState ^= reducedState;
                parent.ChildState |= childInducedState;
            }

            context.UnsavedItems.Add(parent);
        }
Пример #36
0
 protected WriterBase(BehaviorContext behaviorContext)
 {
     BehaviorContext = behaviorContext;
 }
Пример #37
0
 public static Task Publish <TInstance, TData, T>(this BehaviorContext <TInstance, TData> context, object values, IPipe <SendContext> sendPipe)
     where T : class
 {
     return(GetConsumeContext(context).Publish <T>(values, sendPipe));
 }
        public async Task Execute <T>(BehaviorContext <TInstance, T> context, Behavior <TInstance, T> next)
        {
            await Execute(context);

            await next.Execute(context);
        }
Пример #39
0
 public static Task Publish <TInstance, TData>(this BehaviorContext <TInstance, TData> context, object message)
 {
     return(GetConsumeContext(context).Publish(message));
 }
 public HandlerInvocationContext(BehaviorContext parentContext, MessageHandler messageHandler)
     : base(parentContext)
 {
     Set(messageHandler);
 }
Пример #41
0
 public static void Respond <TInstance, TData, T>(this BehaviorContext <TInstance, TData> context, T message)
     where T : class
 {
     GetConsumeContext(context).Respond(message);
 }
 public Task Execute(BehaviorContext <TInstance, Fault <TRequest> > context, Behavior <TInstance, Fault <TRequest> > next)
 {
     request.Accessor.SetFaulted(context, request.GetItem(context, context.CreateConsumeContext().RequestId.Value), context.Data);
     return(next.Execute(context));
 }
Пример #43
0
 void ISavingBehavior.OnSaving(BehaviorContext context)
 {
 }
Пример #44
0
 public static Task RespondAsync <TInstance, TData>(this BehaviorContext <TInstance, TData> context, object message, IPipe <SendContext> sendPipe)
 {
     return(GetConsumeContext(context).RespondAsync(message, sendPipe));
 }
 public SendPhysicalMessageContext(BehaviorContext parentContext, SendOptions sendOptions, TransportMessage message)
     : base(parentContext)
 {
     Set(sendOptions);
     Set(message);
 }
Пример #46
0
 public override void Behave(BehaviorContext context)
 {
     Entity.PositionData.Velocity.X = 0;
     Entity.PositionData.Velocity.Z = 0;
 }
 public void Invoke(BehaviorContext context, Action next)
 {
     UnicastBus.OnMessageReceived(context.TransportMessage);
     next();
 }
 // 실제 이 Activity 에서의 수행내용.
 protected abstract Task Execute(BehaviorContext <TInstance> context);
Пример #49
0
		protected override void InitializeBehaviorContext(BehaviorContext behaviorContext)
		{
			base.InitializeBehaviorContext(behaviorContext);

			behaviorContext[U_SQUAD] = _squad;
			behaviorContext.DefineStack(STACK_POTENTIAL_CLUES);
		}
 public void OnAdding(BehaviorContext context)
 {
 }
Пример #51
0
 public static Task RespondAsync <TInstance, TData>(this BehaviorContext <TInstance, TData> context, object message, Type messageType)
 {
     return(GetConsumeContext(context).RespondAsync(message, messageType));
 }
Пример #52
0
 public HandlerInvocationContext(BehaviorContext parentContext, MessageHandler messageHandler)
     : base(parentContext)
 {
     Set(messageHandler);
 }
 public SendLogicalMessagesContext(BehaviorContext parentContext, SendOptions sendOptions,IEnumerable<LogicalMessage> messages)
     : base(parentContext)
 {
     Set(sendOptions);
     Set(messages);
 }
Пример #54
0
 public static Task RespondAsync <TInstance, TData, T>(this BehaviorContext <TInstance, TData> context, T message, IPipe <SendContext> sendPipe)
     where T : class
 {
     return(GetConsumeContext(context).RespondAsync(message, sendPipe));
 }
 public override Task Execute(BehaviorContext <DeleteDocumentState, DocumentDeletedEmailSentEvent> context, Behavior <DeleteDocumentState, DocumentDeletedEmailSentEvent> next)
 {
     return(Execute(context, next, context.Data.PayLoad.ToEmptyDocumentWithId()));
 }
 public void OnRemoving(BehaviorContext context)
 {
 }
Пример #57
0
 public override BehaviorPriority DeterminePriority(BehaviorContext context)
 {
     return BehaviorPriority.Value(1);
 }
Пример #58
0
        async Task Activity <TInstance> .Execute <T>(BehaviorContext <TInstance, T> context, Behavior <TInstance, T> next)
        {
            await Execute(context).ConfigureAwait(false);

            await next.Execute(context).ConfigureAwait(false);
        }
 public ReceiveLogicalMessageContext(BehaviorContext parentContext, LogicalMessage message)
     : base(parentContext)
 {
     Set(message);
 }
Пример #60
0
 Task Behavior <TInstance> .Execute <T>(BehaviorContext <TInstance, T> context)
 {
     return(_activity.Execute(context, Behavior.Empty <TInstance, T>()));
 }