public async Task Command_arguments_are_bound_by_name_to_method_parameters(
            Type type,
            string commandLine,
            object expectedValue)
        {
            var targetType = typeof(ClassWithMethodHavingParameter <>).MakeGenericType(type);

            var target = Activator.CreateInstance(targetType);

            var binder = new MethodBinder(
                targetType.GetMethod("HandleAsync"),
                () => target);

            var command = new Command("the-command")
            {
                Argument = new Argument
                {
                    Name         = "value",
                    ArgumentType = type
                }
            };
            var parser = new Parser(command);
            await binder.InvokeAsync(new InvocationContext(parser.Parse(commandLine), parser));

            object valueReceivedValue = ((dynamic)target).ReceivedValue;

            valueReceivedValue.Should().Be(expectedValue);
        }
Exemple #2
0
        private MetaObject MakeMethodIndexRule(string oper, MetaObject[] args)
        {
            MethodInfo[] defaults = GetMethodsFromDefaults(args[0].LimitType.GetDefaultMembers(), oper);
            if (defaults.Length != 0)
            {
                MethodBinder binder = MethodBinder.MakeBinder(
                    this,
                    oper == StandardOperators.GetItem ? "get_Item" : "set_Item",
                    defaults);

                MetaObject[]        selfWithArgs = args;
                ParameterExpression arg2         = null;

                if (oper == StandardOperators.SetItem)
                {
                    Debug.Assert(args.Length >= 2);

                    // need to save arg2 in a temp because it's also our result
                    arg2 = Ast.Variable(args[2].Expression.Type, "arg2Temp");

                    args[2] = new MetaObject(
                        Ast.Assign(arg2, args[2].Expression),
                        args[2].Restrictions
                        );
                }

                BindingTarget target = binder.MakeBindingTarget(CallTypes.ImplicitInstance, selfWithArgs);

                Restrictions restrictions = Restrictions.Combine(args);

                if (target.Success)
                {
                    if (oper == StandardOperators.GetItem)
                    {
                        return(new MetaObject(
                                   target.MakeExpression(),
                                   restrictions.Merge(Restrictions.Combine(target.RestrictedArguments))
                                   ));
                    }
                    else
                    {
                        return(new MetaObject(
                                   Ast.Block(
                                       new ParameterExpression[] { arg2 },
                                       target.MakeExpression(),
                                       arg2
                                       ),
                                   restrictions.Merge(Restrictions.Combine(target.RestrictedArguments))
                                   ));
                    }
                }

                return(MakeError(
                           MakeInvalidParametersError(target),
                           restrictions
                           ));
            }

            return(null);
        }
Exemple #3
0
        public void InvokeAction8 <A1, A2, A3, A4, A5, A6, A7, A8> (object d, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8)
        {
            Stats.Increment(StatsCounter.InvokeBinderInvoked);

            Action <A1, A2, A3, A4, A5, A6, A7, A8> a = d as Action <A1, A2, A3, A4, A5, A6, A7, A8>;

            if (a != null)
            {
                Stats.Increment(StatsCounter.InvokeBinderInvoked_Fast);

                a(a1, a2, a3, a4, a5, a6, a7, a8);
                return;
            }

            Stats.Increment(StatsCounter.InvokeBinderInvoked_Slow);

            Delegate del = (Delegate)d;

            sArgs [0] = a1;
            sArgs [1] = a2;
            sArgs [2] = a3;
            sArgs [3] = a4;
            sArgs [4] = a5;
            sArgs [5] = a6;
            sArgs [6] = a7;
            sArgs [7] = a8;
            bool canConvert = MethodBinder.ConvertArguments(del.Method, null, sArgs, 8, ref mConvertedArgs);

            Debug.Assert(canConvert, "Could not convert parameters");
            del.DynamicInvoke(mConvertedArgs);
        }
Exemple #4
0
        public TR InvokeFunc9 <A1, A2, A3, A4, A5, A6, A7, A8, A9, TR> (object d, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9)
        {
            Stats.Increment(StatsCounter.InvokeBinderInvoked);

            Func <A1, A2, A3, A4, A5, A6, A7, A8, A9, TR> f = d as Func <A1, A2, A3, A4, A5, A6, A7, A8, A9, TR>;

            if (f != null)
            {
                Stats.Increment(StatsCounter.InvokeBinderInvoked_Fast);

                return(f(a1, a2, a3, a4, a5, a6, a7, a8, a9));
            }

            Stats.Increment(StatsCounter.InvokeBinderInvoked_Slow);

            Delegate del = (Delegate)d;

            sArgs [0] = a1;
            sArgs [1] = a2;
            sArgs [2] = a3;
            sArgs [3] = a4;
            sArgs [4] = a5;
            sArgs [5] = a6;
            sArgs [6] = a7;
            sArgs [7] = a8;
            sArgs [8] = a9;
            bool canConvert = MethodBinder.ConvertArguments(del.Method, null, sArgs, 9, ref mConvertedArgs);

            Debug.Assert(canConvert, "Could not convert parameters");
            return((TR)del.DynamicInvoke(mConvertedArgs));
        }
Exemple #5
0
        public TR InvokeFunc4 <A1, A2, A3, A4, TR> (object d, A1 a1, A2 a2, A3 a3, A4 a4)
        {
            Stats.Increment(StatsCounter.InvokeBinderInvoked);

            Func <A1, A2, A3, A4, TR> f = d as Func <A1, A2, A3, A4, TR>;

            if (f != null)
            {
                Stats.Increment(StatsCounter.InvokeBinderInvoked_Fast);

                return(f(a1, a2, a3, a4));
            }

            Stats.Increment(StatsCounter.InvokeBinderInvoked_Slow);

            Delegate del = (Delegate)d;

            sArgs [0] = a1;
            sArgs [1] = a2;
            sArgs [2] = a3;
            sArgs [3] = a4;
            bool canConvert = MethodBinder.ConvertArguments(del.Method, null, sArgs, 4, ref mConvertedArgs);

            Debug.Assert(canConvert, "Could not convert parameters");
            return((TR)del.DynamicInvoke(mConvertedArgs));
        }
        private InvokerBase SelectMethod(object o)
        {
            // if only one method, then use it
            if (mMethodList.Length == 1)
            {
                mMethod        = mMethodList[0];
                mOverloadState = OverloadState.NoOverload;
                return(InvokerBase.UpdateOrCreate(mInvoker, o, mMethod.Method));
            }

            mOverloadState = OverloadState.HasOverload;

            // select method based on simple compatibility
            // TODO: this could change to use a rating system
            foreach (var method in mMethodList)
            {
                // late bound operations cannot be performed on types or methods
                // for which ContainsGenericParameters is true
                if (method.Method.ContainsGenericParameters)
                {
                    continue;
                }
                // is this method compatible?
                if (method.CheckArguments(mArgs))
                {
                    mMethod = method;
                    return(InvokerBase.UpdateOrCreate(mInvoker, o, mMethod.Method));
                }
            }

            throw new InvalidOperationException("Could not find suitable method to invoke: " + mName + " for type: " + mType);
        }
Exemple #7
0
        public void SimpleCaseTest()
        {
            var test1CalledCount = 0;
            var testObject       = new TestViewModel(0, () => test1CalledCount++, s => {});

            var binder = new MethodBinder();

            binder.Invoke((object)testObject, "Test1");
            test1CalledCount.Is(1);
            binder.Invoke((object)testObject, "Test1");
            test1CalledCount.Is(2);

            //System.Threading.Thread.Sleep(3000);

            //キャッシュが更新されないか目視
            testObject = new TestViewModel(0, () => test1CalledCount++, s => { });

            binder.Invoke((object)testObject, "Test1");
            test1CalledCount.Is(3);
            binder.Invoke((object)testObject, "Test1");
            test1CalledCount.Is(4);

            //System.Threading.Thread.Sleep(3000);

            //キャッシュ辞書からメソッドキャッシュを取得するか目視
            binder = new MethodBinder();
            binder.Invoke((object)testObject, "Test1");
            test1CalledCount.Is(5);
            binder.Invoke((object)testObject, "Test1");
            test1CalledCount.Is(6);
        }
    int IComparer.Compare(object m1, object m2)
    {
        var me1 = (MethodBase)m1;
        var me2 = (MethodBase)m2;

        if (me1.DeclaringType != me2.DeclaringType)
        {
            // m2's type derives from m1's type, favor m2
            if (me1.DeclaringType.IsAssignableFrom(me2.DeclaringType))
            {
                return(1);
            }
            // m1's type derives from m2's type, favor m1
            if (me2.DeclaringType.IsAssignableFrom(me1.DeclaringType))
            {
                return(-1);
            }
        }
        int p1 = MethodBinder.GetPrecedence((MethodBase)m1);
        int p2 = MethodBinder.GetPrecedence((MethodBase)m2);

        if (p1 < p2)
        {
            return(-1);
        }
        if (p1 > p2)
        {
            return(1);
        }
        return(0);
    }
Exemple #9
0
        public TR InvokeFunc1 <A1, TR> (object d, A1 a1)
        {
            Stats.Increment(StatsCounter.InvokeBinderInvoked);

            TypeLogger.LogType(d);

            Func <A1, TR> f = d as Func <A1, TR>;

            if (f != null)
            {
                Stats.Increment(StatsCounter.InvokeBinderInvoked_Fast);

                return(f(a1));
            }

            Stats.Increment(StatsCounter.InvokeBinderInvoked_Slow);

            Delegate del = (Delegate)d;

            sArgs [0] = a1;
            bool canConvert = MethodBinder.ConvertArguments(del.Method, null, sArgs, 1, ref mConvertedArgs);

            Debug.Assert(canConvert, "Could not convert parameters");
            return((TR)del.DynamicInvoke(mConvertedArgs));
        }
Exemple #10
0
 public BuiltinMethod(string name, MethodBase[] mg, bool foldable)
 {
     this.name     = name;
     this.methods  = mg;
     meth          = MethodBinder.MakeBinder(binder, name, mg, BinderType.Normal);
     this.foldable = foldable;
 }
        private bool TryNumericComparison(OperatorInfo info)
        {
            MethodInfo[] targets = FilterNonMethods(_types[0], Binder.GetMember(Action, _types[0], "Compare"));
            if (targets.Length > 0)
            {
                MethodBinder  mb     = MethodBinder.MakeBinder(Binder, targets[0].Name, targets);
                BindingTarget target = mb.MakeBindingTarget(CallTypes.None, _types);
                if (target.Success)
                {
                    Expression call = Ast.Convert(target.MakeExpression(_rule, _rule.Parameters), typeof(int));
                    switch (info.Operator)
                    {
                    case Operators.GreaterThan: call = Ast.GreaterThan(call, Ast.Constant(0)); break;

                    case Operators.LessThan: call = Ast.LessThan(call, Ast.Constant(0)); break;

                    case Operators.GreaterThanOrEqual: call = Ast.GreaterThanOrEqual(call, Ast.Constant(0)); break;

                    case Operators.LessThanOrEqual: call = Ast.LessThanOrEqual(call, Ast.Constant(0)); break;

                    case Operators.Equals: call = Ast.Equal(call, Ast.Constant(0)); break;

                    case Operators.NotEquals: call = Ast.NotEqual(call, Ast.Constant(0)); break;

                    case Operators.Compare:
                        break;
                    }
                    _rule.Target = _rule.MakeReturn(Binder, call);
                    return(true);
                }
            }
            return(false);
        }
 internal BindContext(FieldBinder field, MethodBinder method, LocalBinder local, ArgBinder arg)
 {
     this.field  = field;
     this.method = method;
     this.local  = local;
     this.arg    = arg;
 }
Exemple #13
0
        public void InvokeAction4 <A1, A2, A3, A4> (object d, A1 a1, A2 a2, A3 a3, A4 a4)
        {
            Stats.Increment(StatsCounter.InvokeBinderInvoked);

            Action <A1, A2, A3, A4> a = d as Action <A1, A2, A3, A4>;

            if (a != null)
            {
                Stats.Increment(StatsCounter.InvokeBinderInvoked_Fast);

                a(a1, a2, a3, a4);
                return;
            }

            Stats.Increment(StatsCounter.InvokeBinderInvoked_Slow);

            Delegate del = (Delegate)d;

            sArgs [0] = a1;
            sArgs [1] = a2;
            sArgs [2] = a3;
            sArgs [3] = a4;
            bool canConvert = MethodBinder.ConvertArguments(del.Method, null, sArgs, 4, ref mConvertedArgs);

            Debug.Assert(canConvert, "Could not convert parameters");
            del.DynamicInvoke(mConvertedArgs);
        }
Exemple #14
0
        public void InvokeAction2 <A1, A2> (object d, A1 a1, A2 a2)
        {
            Stats.Increment(StatsCounter.InvokeBinderInvoked);

            TypeLogger.LogType(d);

            Action <A1, A2> a = d as Action <A1, A2>;

            if (a != null)
            {
                a(a1, a2);
                return;
            }

            Stats.Increment(StatsCounter.InvokeBinderInvoked_Slow);

            Delegate del = (Delegate)d;

            sArgs [0] = a1;
            sArgs [1] = a2;
            bool canConvert = MethodBinder.ConvertArguments(del.Method, null, sArgs, 2, ref mConvertedArgs);

            Debug.Assert(canConvert, "Could not convert parameters");
            del.DynamicInvoke(mConvertedArgs);
        }
Exemple #15
0
        public static T GetIntercepted <T>(this Interceptor bindable)
        {
            StackTrace trace   = new StackTrace();
            StackFrame frame   = trace.GetFrame(1);
            Type       calling = frame.GetMethod().DeclaringType;

            return(MethodBinder.GetBoundFromType <T>(calling));
        }
        internal static BindingTarget /*!*/ ResolveOverload(string /*!*/ name, IList <MethodBase> /*!*/ overloads, CallArguments /*!*/ args,
                                                            bool includeSelf, bool selfIsInstance)
        {
            var methodBinder = MethodBinder.MakeBinder(args.RubyContext.Binder, name, overloads, SymbolId.EmptySymbols, NarrowingLevel.None, NarrowingLevel.All);
            var argTypes     = GetSignatureToMatch(args, includeSelf, selfIsInstance);

            return(methodBinder.MakeBindingTarget(CallTypes.None, argTypes));
        }
 public void Source_Gets_Disabled_When_Target_Command_Is_Disabled_During_Initialization_With_Expression()
 {
     var source = new MockEventSource();
     var target = new MockViewModelWithAction() { IsActionEnabled = false };
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => this.SetAction(), p => target.IsActionEnabled,target);
     binder.Bind();
     Assert.IsFalse(source.IsEnabled);
 }
Exemple #18
0
        public void TestThatAMethodWithNoArgumentsCanBeInvoked()
        {
            MethodBinder binder = new MethodBinder(
                typeof(BindingTester).GetMethod(nameof(BindingTester.EmptyBindableMethod)),
                new HeyRememberDto());

            binder.Invoke();
            Assert.AreEqual("Ok", BindingTester.S);
        }
Exemple #19
0
        public void TestThatWhenTheMethodCantBeBoundTheAndNoExceptionHandlerItMustThrow()
        {
            MethodBinder binder = new MethodBinder(_methodInfo, new HeyRememberDto()
            {
                DomainSpecificData = "[1, 2]"
            });

            Assert.Throws(Is.InstanceOf <Exception>(), () => binder.Invoke());
        }
 public void Source_Is_Disabled_When_Target_Command_Gets_Disabled_After_Initialization()
 {
     var source = new MockEventSource();
     var target = new MockViewModelWithAction() {IsActionEnabled = true};
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => target.Action(), p => target.IsActionEnabled,target);
     binder.Bind();
     target.IsActionEnabled = false;
     Assert.IsFalse(source.IsEnabled);
 }
        protected internal static MethodInfo MakeList(Expression[] args, bool proper)
        {
            Type[] types = Array.ConvertAll <Expression, Type>(args,
                                                               delegate(Expression e) { return(e.Type.IsArray ? e.Type.GetElementType() : e.Type); });

            MethodBinder listbinder = ((BuiltinMethod)Context.Scope.LookupName(((SymbolId)(proper ? list : liststar)))).Binder;

            return(listbinder.MakeBindingTarget(CallType.None, types).Target.Method as MethodInfo);
        }
        public void MethodBinder_Doesnt_Support_Parameters_On_Actions()
        {
            var target = new MockViewModelWithAction();

            AssertExt.ExpectException<NotSupportedException>(() =>
            {
                var binder = new MethodBinder<MockEventArgs>(new UserControl(), "MockEvent", e => target.Action("will fail"));
            });
        }
Exemple #23
0
        public void TestThatIfTheMethodIsCallableICreatesTheOkResponse()
        {
            MethodInfo   method = typeof(FactoryBindingTest).GetMethod(nameof(FactoryBindingTest.EmptyBindableMethod));
            MethodBinder binder = new MethodBinder(method, new HeyRememberDto());

            HeyResponseFactory factory  = new HeyResponseFactory(binder);
            IHeyResponse       response = factory.Make(BackgroundScheduleType.MakePrototype(), new CreatedHttpReturn());

            Assert.IsInstanceOf <OkHeyResponse>(response);
        }
Exemple #24
0
        public void TestThatIfTheMethodHasErrorOnParameterItReturnsNotOkResponse()
        {
            MethodInfo   method = typeof(FactoryBindingTest).GetMethod(nameof(FactoryBindingTest.WithParametersBindableMethod));
            MethodBinder binder = new MethodBinder(method, new HeyRememberDto());

            HeyResponseFactory factory  = new HeyResponseFactory(binder);
            IHeyResponse       response = factory.Make(BackgroundScheduleType.MakePrototype());

            Assert.IsInstanceOf <ParametersErrorHeyResponse>(response);
        }
Exemple #25
0
        internal MethodTarget(MethodBinder binder, MethodBase method, int parameterCount, ArgBuilder instanceBuilder, IList<ArgBuilder> argBuilders, ReturnBuilder returnBuilder) {
            this._binder = binder;
            this._method = method;
            this._parameterCount = parameterCount;
            this._instanceBuilder = instanceBuilder;
            this._argBuilders = argBuilders;
            this._returnBuilder = returnBuilder;

            //argBuilders.TrimExcess();
        }
Exemple #26
0
        private void MakeMethodBaseRule(MethodBase[] targets)
        {
            Type[]     argTypes; // will not include implicit instance argument (if any)
            SymbolId[] argNames; // will include ArgumentKind.Dictionary keyword names


            GetArgumentNamesAndTypes(out argNames, out argTypes);

            Type[]    bindingArgs = argTypes; // will include instance argument (if any)
            CallTypes callType    = CallTypes.None;

            if (_instance != null)
            {
                bindingArgs = ArrayUtils.Insert(InstanceType, argTypes);
                callType    = CallTypes.ImplicitInstance;
            }

            if (_reversedOperator && bindingArgs.Length >= 2)
            {
                // we swap the arguments before binding, and swap back before calling.
                ArrayUtils.SwapLastTwo(bindingArgs);
                if (argNames.Length >= 2)
                {
                    ArrayUtils.SwapLastTwo(argNames);
                }
            }

            // attempt to bind to an individual method
            MethodBinder  binder = MethodBinder.MakeBinder(Binder, GetTargetName(targets), targets, argNames, NarrowingLevel.None, _maxLevel);
            BindingTarget bt     = binder.MakeBindingTarget(callType, bindingArgs);

            if (bt.Success)
            {
                // if we succeed make the target for the rule
                MethodBase target       = bt.Method;
                MethodInfo targetMethod = target as MethodInfo;

                if (targetMethod != null)
                {
                    target = CompilerHelpers.GetCallableMethod(targetMethod, Binder.PrivateBinding);
                }

                Expression[] exprargs = FinishTestForCandidate(bt.ArgumentTests, argTypes);

                _rule.Target = _rule.MakeReturn(
                    Binder,
                    bt.MakeExpression(_rule, exprargs));
            }
            else
            {
                // make an error rule
                MakeInvalidParametersRule(bt);
            }
        }
Exemple #27
0
        internal MethodTarget(MethodBinder binder, MethodBase method, int parameterCount, ArgBuilder instanceBuilder, IList <ArgBuilder> argBuilders, ReturnBuilder returnBuilder)
        {
            this._binder          = binder;
            this._method          = method;
            this._parameterCount  = parameterCount;
            this._instanceBuilder = instanceBuilder;
            this._argBuilders     = argBuilders;
            this._returnBuilder   = returnBuilder;

            //argBuilders.TrimExcess();
        }
        public void When_method_binder_is_added_then_it_can_be_retrieved_by_its_event()
        {
            var button = new Button();
            var view = new UserControl();
            var vm = new MockViewModelWithAction();
            var buttonBinder = new MethodBinder<RoutedEventArgs>(button, "Click", p => vm.Action());
            var viewModelBinder = new ViewBinder<object>(view, vm);
            viewModelBinder.Add(buttonBinder);

            var binder = viewModelBinder.GetMethodBinder(button, "Click");
            Assert.AreEqual(buttonBinder, binder);
        }
Exemple #29
0
        public void TestThatBaseNativeTypesCandBeBindedAndInvoked()
        {
            MethodBinder binder = new MethodBinder(_methodInfo, new HeyRememberDto()
            {
                DomainSpecificData = "[1, \"banana\"]"
            });

            MethodExecutionResultEnum result = binder.Invoke();

            Assert.AreEqual(1, BindingTester.L);
            Assert.AreEqual("banana", BindingTester.S);
            Assert.AreEqual(MethodExecutionResultEnum.Ok, result);
        }
        private bool TryMakeInvertedBindingTarget(MethodInfo[] targets)
        {
            MethodBinder  mb     = MethodBinder.MakeBinder(Binder, targets[0].Name, targets);
            BindingTarget target = mb.MakeBindingTarget(CallTypes.None, _types);

            if (target.Success)
            {
                Expression call = target.MakeExpression(_rule, _rule.Parameters);
                _rule.Target = _rule.MakeReturn(Binder, Ast.Not(call));
                return(true);
            }
            return(false);
        }
        private bool TryMakeInvertedBindingTarget(MethodInfo[] targets)
        {
            MethodBinder    mb = MethodBinder.MakeBinder(Binder, targets[0].Name, targets, BinderType.Normal);
            MethodCandidate mc = mb.MakeBindingTarget(CallType.None, _types);

            if (mc != null)
            {
                Expression call = mc.Target.MakeExpression(Binder, _rule, _rule.Parameters, _types);
                _rule.SetTarget(_rule.MakeReturn(Binder, Ast.Not(call)));
                return(true);
            }
            return(false);
        }
Exemple #32
0
        public void TestThatWhenTheMethodCantBeBoundTheExceptionHandlerIsCalled()
        {
            Mock <IHeyExceptionHandler> exceptionHandlerMock = new Mock <IHeyExceptionHandler>();

            MethodBinder binder = new MethodBinder(_methodInfo, new HeyRememberDto()
            {
                DomainSpecificData = "[1, 2]"
            }, exceptionHandlerMock.Object);

            MethodExecutionResultEnum result = binder.Invoke();

            exceptionHandlerMock.Verify(handler => handler.Handle(It.IsAny <Exception>()));
            Assert.AreEqual(MethodExecutionResultEnum.Fail, result);
        }
Exemple #33
0
        public void TestThatIfTheMethodHasErrorOnParameterTypeItReturnsNotOkResponseWithTheNumberOfTheParameterThatGotError()
        {
            MethodInfo   method = typeof(FactoryBindingTest).GetMethod(nameof(FactoryBindingTest.WithParametersBindableMethod));
            MethodBinder binder = new MethodBinder(method, new HeyRememberDto()
            {
                DomainSpecificData = "[1, \"banana\"]"
            });

            HeyResponseFactory factory  = new HeyResponseFactory(binder);
            IHeyResponse       response = factory.Make(BackgroundScheduleType.MakePrototype());

            Assert.IsInstanceOf <ParametersErrorHeyResponse>(response);
            Assert.AreEqual(1, ((ParametersErrorHeyResponse)response).ParamNum);
        }
Exemple #34
0
        public IBinder Apply()
        {
            var source = new BindableSource <TSourceValue>(_source, _propertyName, BindingMode.OneWay);
            var binder = new MethodBinder <TSourceValue>(source, _action);

            if (Set == null)
            {
                throw new InvalidOperationException("Binding set is not set");
            }

            Set.Add(binder);
            binder.Start();
            return(binder);
        }
        public void Options_are_not_built_for_infrastructure_types_exposed_by_method_parameters(Type type)
        {
            var targetType = typeof(ClassWithMethodHavingParameter <>).MakeGenericType(type);

            var target = Activator.CreateInstance(targetType);

            var binder = new MethodBinder(
                targetType.GetMethod(nameof(ClassWithMethodHavingParameter <int> .Handle)),
                () => target);

            var options = binder.BuildOptions();

            options.Should()
            .NotContain(o => o.Argument.ArgumentType == type);
        }
		private void SelectMethod(object o, int argCount)
		{
			mDelegate = null;

			// if only one method, then use it
			if (mMethodList.Length == 1) {
				mMethod       = mMethodList[0];
				mIsOverloaded = false;
				return;
			}

			mIsOverloaded = true;

			// select method based on simple compatibility
			// TODO: this could change to use a rating system
			foreach (var method in mMethodList) {
				// is this method compatible?
				if (method.CheckArguments(mArgs)) {
					mMethod = method;
					return;
				}
			}

			// no methods compatible?

			// try to get method from dynamic class
			var dc = o as IDynamicClass;
			if (dc != null) {
				var func = dc.__GetDynamicValue(this.name) as Delegate;
				if (func != null) {
					// use function
					mDelegate = func;
					return;
				}
			}

			throw new InvalidOperationException("Could not find suitable method to invoke: " + this.name + " for type: " + mType);
		}
 public void Source_Is_Enabled_When_Target_Command_Is_Enabled_During_Initialization()
 {
     var source = new MockEventSource();
     var target = new MockViewModelWithAction() {IsActionEnabled = true};
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => this.SetAction(), p => target.IsActionEnabled,target);
     Assert.IsTrue(source.IsEnabled);
 }
 public void When_command_is_disabled_and_event_is_raised_then_action_is_not_called()
 {
     var source = new MockEventSource();
     var target = new MockViewModelWithAction() {IsActionEnabled = false};
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => this.SetAction(), p => target.IsActionEnabled,target);
     binder.Bind();
     source.RaiseMockEvent("foo");
     Assert.IsFalse(this._actionWasCalled);
 }
 public void When_constructed_with_an_expression_then_binds_to_vm_action()
 {
     var vm = new OrderViewModel();
     var view = new OrderView();
     var binder = new MethodBinder(p => vm.Save(), view,vm);
     Assert.AreEqual("Save", binder.ActionName);
 }
 public void When_constructed_with_action_disabled_then_source_gets_disabled()
 {
     var source = new MockEventSource();
     var target = new MockViewModelWithAction() {IsActionEnabled = false};
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => this.SetAction(), p => target.IsActionEnabled,target);
     binder.Bind();
     Assert.IsFalse(source.IsEnabled);
 }
 public void When_event_is_raised_then_action_is_called()
 {
     var source = new MockEventSource();
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => this.SetAction());
     binder.Bind();
     source.RaiseMockEvent("foo");
     Assert.IsTrue(this._actionWasCalled);
 }
Exemple #42
0
 public Dispatcher(MethodBinder binder)
 {
     _binder = binder;
 }
 public void When_constructed_then_subscribes_to_event()
 {
     var source = new MockEventSource();
     var binder = new MethodBinder<MockEventArgs>(source, "MockEvent", e => this.SetAction());
     binder.Bind();
     Assert.IsNotNull(source.EventHandler);
 }
 public void When_constructed_with_an_expression_then_binds_to_vm_is_enabled_action()
 {
     var vm = new OrderViewModel();
     var view = new OrderView();
     var binder = new MethodBinder(p => vm.Save(), view,vm);
     Assert.AreEqual("IsSaveEnabled", binder.IsEnabledBinder.TargetPath);
 }
 public void When_constructed_with_an_expression_then_binds_to_control()
 {
     var vm = new OrderViewModel();
     var view = new OrderView();
     var binder = new MethodBinder(p => vm.Save(),view, vm);
     Assert.AreEqual(view.Save, binder.ViewElement);
 }
 public void When_constructed_with_a_control_then_sets_event_name()
 {
     var button = new Button();
     button.Name = "Action";
     var vm = new MockViewModelWithAction();
     button.SetValue(ViewBinder.ModelProperty, vm);
     var binder = new MethodBinder(button,vm);
     Assert.AreEqual("Click",binder.EventName);
 }