Exemplo n.º 1
0
        public void MulipleMessageBind()
        {
            var res = 0;
            MessageBindDelegate <string> bindAction  = s => { res |= 1; };
            MessageBindDelegate <string> bindAction2 = s => { res |= 2; };

            var binder = new MessageBinder();

            Is.False.ApplyTo(binder.AnyBind("message"));

            binder.Bind <string>("message", bindAction);
            binder.Bind <string>("message1", bindAction2);

            Is.True.ApplyTo(binder.AnyBind("message"));
            Is.Not.Null.ApplyTo(binder.GetBinds("message"));

            Is.True.ApplyTo(binder.AnyBind("message1"));
            Is.Not.Null.ApplyTo(binder.GetBinds("message1"));

            Assert.AreEqual(1, binder.GetBinds("message").Count);
            Assert.AreEqual(1, binder.GetBinds("message1").Count);

            binder.GetBinds("message").First().BindAction(null);
            binder.GetBinds("message1").First().BindAction(null);

            Assert.AreEqual(3, res);
        }
Exemplo n.º 2
0
        public void MakeAwareOf(ActionExecutionContext context)
        {
            var targetType = context.Target.GetType();
            var guard      = targetType.GetMethod(MethodName);

            if (guard == null)
            {
                guard = targetType.GetMethod("get_" + MethodName);
            }

            if (guard == null)
            {
                return;
            }

            var oldCanExecute = context.CanExecute;

            context.CanExecute = () =>
            {
                if (oldCanExecute != null && !oldCanExecute())
                {
                    return(false);
                }

                return((bool)guard.Invoke(
                           context.Target,
                           MessageBinder.DetermineParameters(context, guard.GetParameters())
                           ));
            };
        }
Exemplo n.º 3
0
            internal static void InvokeAction(ActionExecutionContext context)
            {
                var decorators = context.GetFilters()
                                 .OfType <IDecorateCoroutineFilter>()
                                 .ToArray();

                // Use the default behaviour when no decorators are found
                if (!decorators.Any())
                {
                    BaseInvokeAction(context);
                    return;
                }

                var values      = MessageBinder.DetermineParameters(context, context.Method.GetParameters());
                var returnValue = context.Method.Invoke(context.Target, values);

                IEnumerable <IResult> coroutine;

                if (returnValue is IResult)
                {
                    coroutine = new[] { returnValue as IResult };
                }
                else if (returnValue is IEnumerable <IResult> )
                {
                    coroutine = returnValue as IEnumerable <IResult>;
                }
                else
                {
                    return;
                }

                coroutine = decorators.Aggregate(coroutine, (current, decorator) => decorator.Decorate(current, context));

                Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
            }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            MessageBinder.Bind(typeof(SayHiAdapter).Assembly);
            new NettyNetwork(6666).ListenAsync().Wait();

            Console.ReadKey();
        }
Exemplo n.º 5
0
        public static void InvokeAction(ActionExecutionContext context)
        {
            var values = MessageBinder.DetermineParameters(context, context.Method.GetParameters());
            var result = Coroutine.CreateParentEnumerator(ExecuteActionWithParameters(values).GetEnumerator());

            var wrappers = FilterManager.GetFiltersFor(context).OfType <IExecutionWrapper>();
            var pipeline = result.WrapWith(wrappers);

            //if pipeline has error, action execution should throw!
            pipeline.Completed += (o, e) =>
            {
                Execute.OnUIThread(() =>
                {
                    if (e.Error != null)
                    {
                        throw new Exception(
                            string.Format("An error occurred while executing {0}.",
                                          context.Message),
                            e.Error
                            );
                    }
                });
            };

            pipeline.Execute(context);
        }
Exemplo n.º 6
0
        public (TcpMessageServer, IMessageBinder, ISignal <IMessageSender>) CreateServerSide()
        {
            var binds         = new MessageBinder();
            var connectSignal = new Signal <IMessageSender>();
            var recv          = new MessageReceiver(binds, Serialier);
            var server        = new TcpMessageServer(recv, connectSignal, Serialier);

            return(server, binds, connectSignal);
        }
Exemplo n.º 7
0
        public (IMessageSender, IMessageBinder) CreateClientSide()
        {
            var binder   = new MessageBinder();
            var recv     = new MessageReceiver(binder, Serialier);
            var client   = new TcpClient("localhost", Port);
            var sender   = new TcpMessageSender(client, Serialier);
            var listener = new TcpMessageListener(recv, client, sender);

            return(sender, binder);
        }
Exemplo n.º 8
0
        public void EvaluateParameterCaseInsensitive()
        {
            MessageBinder.SpecialValues.Add("$sampleParameter", context => 42);
            var caseSensitiveValue = MessageBinder.EvaluateParameter("$sampleParameter", typeof(int), new ActionExecutionContext());

            Assert.NotEqual("$sampleParameter", caseSensitiveValue);

            var caseInsensitiveValue = MessageBinder.EvaluateParameter("$sampleparameter", typeof(int), new ActionExecutionContext());

            Assert.NotEqual("$sampleparameter", caseInsensitiveValue);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            MessageBinder.Bind(typeof(PingPongAdapter).Assembly);

            Server.ListenAsync().Wait();
            Client.ConnectAsync().Wait();

            PingPong();

            Console.ReadKey();
        }
Exemplo n.º 10
0
        /// <summary>
        ///   Attempts to inject query string parameters from the view into the view model.
        /// </summary>
        /// <param name="viewModel"> The view model.</param>
        /// <param name="parameter"> The parameter.</param>
        protected virtual void TryInjectParameters(object viewModel, object parameter)
        {
            var viewModelType = viewModel.GetType();

            var stringParameter     = parameter as string;
            var dictionaryParameter = parameter as IDictionary <string, object>;

            if (stringParameter != null && stringParameter.StartsWith("caliburn://"))
            {
                var uri = new Uri(stringParameter);
                if (!String.IsNullOrEmpty(uri.Query))
                {
                    var decorder = new WwwFormUrlDecoder(uri.Query);
                    foreach (var pair in decorder)
                    {
                        var property = viewModelType.GetPropertyCaseInsensitive(pair.Name);
                        if (property == null)
                        {
                            continue;
                        }

                        property.SetValue(viewModel, MessageBinder.CoerceValue(property.PropertyType, pair.Value, null));
                    }
                }
            }

            else if (dictionaryParameter != null)
            {
                foreach (var pair in dictionaryParameter)
                {
                    var property = viewModelType.GetPropertyCaseInsensitive(pair.Key);
                    if (property == null)
                    {
                        continue;
                    }

                    property.SetValue(viewModel, MessageBinder.CoerceValue(property.PropertyType, pair.Value, null));
                }
            }
            else
            {
                var property = viewModelType.GetPropertyCaseInsensitive("Parameter");
                if (property == null)
                {
                    return;
                }

                property.SetValue(viewModel, MessageBinder.CoerceValue(property.PropertyType, parameter, null));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Executes the specified this action on the specified target.
        /// </summary>
        /// <param name="actionMessage">The action message.</param>
        /// <param name="handlingNode">The node.</param>
        /// <param name="context">The context.</param>
        public override void Execute(ActionMessage actionMessage, IInteractionNode handlingNode, object context)
        {
            try
            {
                var parameters = MessageBinder.DetermineParameters(
                    actionMessage,
                    UnderlyingRequirements,
                    handlingNode,
                    context
                    );

                TryUpdateTrigger(actionMessage, handlingNode, true);

                foreach (var filter in UnderlyingFilters.PreProcessors)
                {
                    if (filter.Execute(actionMessage, handlingNode, parameters))
                    {
                        continue;
                    }

                    TryUpdateTrigger(actionMessage, handlingNode, false);
                    return;
                }

                var outcome = new MessageProcessingOutcome(
                    UnderlyingMethod.Invoke(handlingNode.MessageHandler.Unwrap(), parameters),
                    UnderlyingMethod.Info.ReturnType,
                    false
                    );

                foreach (var filter in UnderlyingFilters.PostProcessors)
                {
                    filter.Execute(actionMessage, handlingNode, outcome);
                }

                HandleOutcome(actionMessage, handlingNode, outcome);
            }
            catch (Exception ex)
            {
                TryUpdateTrigger(actionMessage, handlingNode, false);
                if (!TryApplyRescue(actionMessage, handlingNode, ex))
                {
                    Log.Error(ex);
                    throw;
                }
                OnCompleted();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// A static helper that can be used as prepare action in order to inject a parameter into the target view model
        /// </summary>
        /// <param name="target">The target view model</param>
        /// <param name="parameter">The parameter value to be injected.</param>
        /// <param name="propertyName">The name of the property to inject to.</param>
        public static void TryInjectParameter(object target, object parameter, string propertyName = "Parameter")
        {
            var viewModelType = target.GetType();
            var property      = viewModelType.GetPropertyCaseInsensitive(propertyName);

            if (property == null)
            {
                return;
            }

#if SILVERLIGHT
            property.SetValue(target, MessageBinder.CoerceValue(property.PropertyType, parameter, null), null);
#else
            property.SetValue(target, MessageBinder.CoerceValue(property.PropertyType, parameter, null));
#endif
        }
Exemplo n.º 13
0
        private static void StartServer(int parse)
        {
            var binder               = new MessageBinder();
            var recv                 = new MessageReceiver(binder, serializer);
            var connectSignal        = new Signal <IMessageSender>();
            var messageServer        = new TcpMessageServer(recv, connectSignal, serializer);
            var messageSernderAccess = new LoggedMessageSenderAccess(recv);

            var chatServer = new ChatServer(binder, messageSernderAccess, messageServer);

            chatServer.Listen(parse);

            Console.ReadKey();

            chatServer.Stop();
        }
        public static void Hook()
        {
            var oldPrepareContext = ActionMessage.PrepareContext;

            ActionMessage.PrepareContext = context =>
            {
                oldPrepareContext(context);
                FilterFrameworkCoreCustomization.PrepareContext(context);
            };

            ActionMessage.InvokeAction = context =>
            {
                var values = MessageBinder.DetermineParameters(context, context.Method.GetParameters());
                FilterFrameworkCoreCustomization.InvokeAction(context, values);
            };
        }
Exemplo n.º 15
0
        private static (ChatClient, TcpClient, TcpMessageListener) StartClientFactory(IPEndPoint server)
        {
            var binder = new MessageBinder();
            var recv   = new MessageReceiver(binder, serializer);
            var client = new TcpClient();

            client.Connect(server);
            var tcpClient         = new TcpMessageListener(recv, client);
            var sender            = new TcpMessageSender(client, serializer);
            var connectSignal     = new Signal <string>();
            var leaveSignal       = new Signal <string>();
            var messageRecvSignal = new Signal <(string, string)>();

            var chatClient = new ChatClient(sender, binder, messageRecvSignal, connectSignal, leaveSignal);

            return(chatClient, client, tcpClient);
        }
Exemplo n.º 16
0
        /// <summary>
        ///   Attempts to inject query string parameters from the view into the view model.
        /// </summary>
        /// <param name="viewModel"> The view model. </param>
        /// <param name="page"> The page. </param>
        protected virtual void TryInjectQueryString(object viewModel, Page page)
        {
            var viewModelType = viewModel.GetType();

            foreach (var pair in page.NavigationContext.QueryString)
            {
                var property = viewModelType.GetPropertyCaseInsensitive(pair.Key);
                if (property == null)
                {
                    continue;
                }

                property.SetValue(
                    viewModel,
                    MessageBinder.CoerceValue(property.PropertyType, pair.Value, page.NavigationContext),
                    null
                    );
            }
        }
Exemplo n.º 17
0
        public void ClassNamedAttributeBind()
        {
            var isCall = false;
            MessageBindDelegate <Foo> bindAction = s => isCall = true;;

            var binder = new MessageBinder();

            Is.False.ApplyTo(binder.AnyBind("foo"));

            binder.Bind(bindAction);

            Is.True.ApplyTo(binder.AnyBind("foo"));
            Is.Not.Null.ApplyTo(binder.GetBinds("foo"));

            Assert.AreEqual(1, binder.GetBinds("foo").Count);

            binder.GetBinds("foo")[0].BindAction(null);

            Assert.True(isCall);
        }
Exemplo n.º 18
0
        public void ClassNamedBind()
        {
            var isCall = false;
            MessageBindDelegate <string> bindAction = s => isCall = true;;

            var binder = new MessageBinder();

            Is.False.ApplyTo(binder.AnyBind(typeof(string).FullName));

            binder.Bind <string>(bindAction);

            Is.True.ApplyTo(binder.AnyBind(typeof(string).FullName));
            Is.Not.Null.ApplyTo(binder.GetBinds(typeof(string).FullName));

            Assert.AreEqual(1, binder.GetBinds(typeof(string).FullName).Count);

            binder.GetBinds(typeof(string).FullName)[0].BindAction(null);

            Assert.True(isCall);
        }
Exemplo n.º 19
0
        private void HandleOutcome(ActionMessage message, IInteractionNode handlingNode, MessageProcessingOutcome outcome)
        {
            var result = MessageBinder.CreateResult(outcome);

            result.Completed += (s, e) => {
                TryUpdateTrigger(message, handlingNode, false);

                if (e.Error != null)
                {
                    if (!TryApplyRescue(message, handlingNode, e.Error))
                    {
                        Log.Error(e.Error);
                        throw e.Error;
                    }
                }

                OnCompleted();
            };

            result.Execute(new ResultExecutionContext(serviceLocator, message, handlingNode));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Executes the specified this action on the specified target.
        /// </summary>
        /// <param name="actionMessage">The action message.</param>
        /// <param name="handlingNode">The node.</param>
        /// <param name="context">The context.</param>
        public override void Execute(ActionMessage actionMessage, IInteractionNode handlingNode, object context)
        {
            try
            {
                var parameters = MessageBinder.DetermineParameters(
                    actionMessage,
                    UnderlyingRequirements,
                    handlingNode,
                    context
                    );

                TryUpdateTrigger(actionMessage, handlingNode, true);

                CurrentTask = UnderlyingMethod.CreateBackgroundTask(handlingNode.MessageHandler.Unwrap(), parameters);

                foreach (var filter in UnderlyingFilters.PreProcessors)
                {
                    if (filter.Execute(actionMessage, handlingNode, parameters))
                    {
                        continue;
                    }

                    TryUpdateTrigger(actionMessage, handlingNode, false);
                    return;
                }

                DoExecute(actionMessage, handlingNode, parameters);
            }
            catch (Exception ex)
            {
                TryUpdateTrigger(actionMessage, handlingNode, false);
                if (!TryApplyRescue(actionMessage, handlingNode, ex))
                {
                    Log.Error(ex);
                    throw;
                }
                OnCompleted();
            }
        }
        public Task <ITriggerData> BindAsync(object value, ValueBindingContext context)
        {
            IValueProvider valueProvider;

            switch (TriggerParameterMode)
            {
            case TriggerParameterMode.Message:
                var message = value as TMessage;
                valueProvider = new MessageBinder(message);
                break;

            case TriggerParameterMode.ConsumeContext:
                var consumeContext = value as ConsumeContext <TMessage>;
                valueProvider = new ConsumeContextBinder(consumeContext);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var bindingData = CreateBindingData(ParameterInfo, valueProvider);

            return(Task.FromResult((ITriggerData) new TriggerData(valueProvider, bindingData)));
        }
Exemplo n.º 22
0
        public void MulipleHandlerBind()
        {
            var res = 0;
            MessageBindDelegate <string> bindAction  = s => { res |= 1; };
            MessageBindDelegate <string> bindAction2 = s => { res |= 2; };
            var binder = new MessageBinder();

            Is.False.ApplyTo(binder.AnyBind("message"));

            binder.Bind <string>("message", bindAction);
            binder.Bind <string>("message", bindAction2);

            Is.True.ApplyTo(binder.AnyBind("message"));
            Is.Not.Null.ApplyTo(binder.GetBinds("message"));

            Assert.AreEqual(2, binder.GetBinds("message").Count);

            foreach (var messageBindDelegate in binder.GetBinds("message"))
            {
                messageBindDelegate.BindAction(null);
            }

            Assert.AreEqual(3, res);
        }
Exemplo n.º 23
0
        public void MessageBinder_Throws_On_Null_Message()
        {
            Action a = () => MessageBinder.Bind(Saml2Binding.Get(Saml2BindingType.HttpPost), null);

            a.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("message");
        }
Exemplo n.º 24
0
        public void MessageBinder_Throws_On_Null_Binder()
        {
            Action a = () => MessageBinder.Bind(null, new Saml2AuthenticationRequest());

            a.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("binding");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Executes the core logic, specific to the action type.
        /// </summary>
        /// <param name="actionMessage">The action message.</param>
        /// <param name="handlingNode">The node.</param>
        /// <param name="parameters">The parameters.</param>
        protected void DoExecute(ActionMessage actionMessage, IInteractionNode handlingNode, object[] parameters)
        {
            CurrentTask.Completed +=
                (s, e) => Invocation.Execute.OnUIThread(
                    () => {
                Interlocked.Decrement(ref runningCount);
                if (e.Error != null)
                {
                    TryUpdateTrigger(actionMessage, handlingNode, false);
                    if (!TryApplyRescue(actionMessage, handlingNode, e.Error))
                    {
                        Log.Error(e.Error);
                        throw e.Error;
                    }
                    OnCompleted();
                }
                else
                {
                    try
                    {
                        var outcome = new MessageProcessingOutcome(
                            e.Cancelled ? null : e.Result,
                            UnderlyingMethod.Info.ReturnType,
                            e.Cancelled
                            );

                        foreach (var filter in UnderlyingFilters.PostProcessors)
                        {
                            filter.Execute(actionMessage, handlingNode, outcome);
                        }

                        var result = MessageBinder.CreateResult(outcome);

                        result.Completed += (r, arg) => {
                            TryUpdateTrigger(actionMessage, handlingNode, false);

                            if (arg.Error != null)
                            {
                                if (!TryApplyRescue(actionMessage, handlingNode, arg.Error))
                                {
                                    Log.Error(arg.Error);
                                    throw arg.Error;
                                }
                            }

                            OnCompleted();
                        };

                        result.Execute(new ResultExecutionContext(serviceLocator, actionMessage, handlingNode));
                    }
                    catch (Exception ex)
                    {
                        TryUpdateTrigger(actionMessage, handlingNode, false);
                        if (!TryApplyRescue(actionMessage, handlingNode, ex))
                        {
                            Log.Error(ex);
                            throw;
                        }
                        OnCompleted();
                    }
                }
            });

            Interlocked.Increment(ref runningCount);
            CurrentTask.Start(this);
            CurrentTask = null;
        }