public object CallOverride(Invocation invocation)
        {
            var args = implementationOverride.Method.GetParameters().Length > 0 && invocation.Args != null ? invocation.Args : Empty;

            var paramsCount = invocation.Method.GetParameters().Length;
            var implementationParamsCount = implementationOverride.Method.GetParameters().Length;

            if (invocation.Method.IsExtensionMethod() && paramsCount - 1 == implementationParamsCount)
            {
                args = args.Skip(1).ToArray();
            }

            int extraParamCount = 1 + (implementationOverride.Target != null && implementationOverride.Method.IsStatic ? 1 : 0);

            if (!invocation.Method.IsStatic && extraParamCount + paramsCount == implementationParamsCount)
            {
                args = new[] { invocation.Instance }.Concat(args).ToArray();
            }

            try
            {
                var returnValue = ProfilerInterceptor.GuardExternal(() => overrideInvoker(args, this.implementationOverride));
                return(returnValue);
            }
            catch (InvalidCastException ex)
            {
                throw new MockException("The implementation callback has an incorrect signature", ex);
            }
        }
Esempio n. 2
0
        protected override bool MatchesCore(IMatcher other)
        {
            var otherRange = other as RangeMatcher <T>;

            if (otherRange != null)
            {
                return((this.kind == otherRange.kind || otherRange.kind == RangeKind.Exclusive)
                                        ? ProfilerInterceptor.GuardExternal(() => this.from.CompareTo(otherRange.from) <= 0 && this.to.CompareTo(otherRange.to) >= 0)
                                        : ProfilerInterceptor.GuardExternal(() => this.from.CompareTo(otherRange.from) < 0 && this.to.CompareTo(otherRange.to) > 0));
            }

            var matcher = (IValueMatcher)other;

            if (matcher.Value == null)
            {
                return(false);
            }
            if (!typeof(T).IsAssignableFrom(matcher.Type))
            {
                return(false);
            }

            T val = (T)matcher.Value;

            if (kind == Telerik.JustMock.RangeKind.Inclusive)
            {
                return(ProfilerInterceptor.GuardExternal(() => val.CompareTo(from) >= 0 && val.CompareTo(to) <= 0));
            }
            else
            {
                return(ProfilerInterceptor.GuardExternal(() => val.CompareTo(from) > 0 && val.CompareTo(to) < 0));
            }
        }
        public object Create(Type type, MocksRepository repository, IMockMixin mockMixinImpl, MockCreationSettings settings, bool createTransparentProxy)
        {
            var baseType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
            RuntimeTypeHandle proxyTypeHandle;
            var key = new ProxySourceRegistry.ProxyKey(
                baseType.TypeHandle, GetAdditionalInterfaceHandles(type, settings.AdditionalMockedInterfaces));

            if (!ProxySourceRegistry.ProxyTypes.TryGetValue(key, out proxyTypeHandle))
            {
                ThrowNoProxyException(baseType, settings.AdditionalMockedInterfaces);
            }

            var interceptor = new DynamicProxyInterceptor(repository);

            var proxyType = Type.GetTypeFromHandle(proxyTypeHandle);

            if (proxyType.IsGenericTypeDefinition)
            {
                proxyType = proxyType.MakeGenericType(type.GetGenericArguments());
            }

            var mockConstructorCall = settings.MockConstructorCall &&
                                      proxyType.BaseType != typeof(object) &&
                                      UninitializedObjectFactory.IsSupported;

            ConstructorInfo proxyCtor = null;

            if (!mockConstructorCall && settings.Args == null)
            {
                proxyCtor = proxyType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                            .First(ctor => ctor.IsPublic || ctor.IsFamily || ctor.IsFamilyOrAssembly);
                settings.Args = proxyCtor.GetParameters()
                                .TakeWhile(p => p.ParameterType != typeof(IInterceptor))
                                .Select(p => (p.Attributes & ParameterAttributes.HasDefault) != 0 ? p.DefaultValue : p.ParameterType.GetDefaultValue())
                                .ToArray();
            }

            var ctorArgs =
                (settings.Args ?? Enumerable.Empty <object>())
                .Concat(new object[] { interceptor, mockMixinImpl })
                .Concat(settings.Mixins).ToArray();

            if (!mockConstructorCall)
            {
                if (proxyCtor != null)
                {
                    return(ProfilerInterceptor.GuardExternal(() => proxyCtor.Invoke(ctorArgs)));
                }
                else
                {
                    return(ProfilerInterceptor.GuardExternal(() => Activator.CreateInstance(proxyType, ctorArgs)));
                }
            }
            else
            {
                var result = UninitializedObjectFactory.Create(proxyType);
                proxyType.GetMethod(".init").Invoke(result, ctorArgs);
                return(result);
            }
        }
        /// <summary>
        /// Creates an instance within the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>The created instance.</returns>
        public virtual object Create(IContext context)
        {
            Ensure.ArgumentNotNull(context, "context");

            if (context.Plan == null)
            {
                context.Plan = this.Planner.GetPlan(this.GetImplementationType(context.Request.Service));
            }

            if (!context.Plan.Has <ConstructorInjectionDirective>())
            {
                throw new ActivationException(ExceptionFormatter.NoConstructorsAvailable(context));
            }

            var directives     = context.Plan.GetAll <ConstructorInjectionDirective>();
            var bestDirectives = directives
                                 .GroupBy(option => this.ConstructorScorer.Score(context, option))
                                 .OrderByDescending(g => g.Key)
                                 .First();

            if (bestDirectives.Skip(1).Any())
            {
                throw new ActivationException(ExceptionFormatter.ConstructorsAmbiguous(context, bestDirectives));
            }

            var directive = bestDirectives.Single();
            var arguments = directive.Targets.Select(target => this.GetValue(context, target)).ToArray();
            var injector  = directive.Injector;

            return(ProfilerInterceptor.GuardExternal(() => injector(arguments)));
        }
Esempio n. 5
0
 /// <summary>
 /// Sets the value of a property by name.
 /// </summary>
 /// <param name="name">The name of the property.</param>
 /// <param name="value">The value to set to the property.</param>
 /// <param name="indexArgs">Optional index arguments if the property has any.</param>
 public void SetProperty(string name, object value, params object[] indexArgs)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var prop = ResolveProperty(this.type, name, false, indexArgs, this.instance != null, value, getter: false);
         ProfilerInterceptor.GuardExternal(() => SecuredReflectionMethods.SetProperty(prop, this.instance, value, indexArgs));
     });
 }
Esempio n. 6
0
 /// <summary>
 /// Gets the value of a property by name.
 /// </summary>
 /// <param name="name">The name of the property.</param>
 /// <param name="indexArgs">Optional index arguments if the property has any.</param>
 /// <returns>The value of the property.</returns>
 public object GetProperty(string name, params object[] indexArgs)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         var prop = ResolveProperty(this.type, name, false, indexArgs, this.instance != null);
         return ProfilerInterceptor.GuardExternal(() => SecuredReflectionMethods.GetProperty(prop, this.instance, indexArgs));
     }));
 }
Esempio n. 7
0
        protected override bool MatchesCore(IMatcher other)
        {
            var matcher = (IValueMatcher)other;
            var value   = matcher.Value;

            if (value == null && typeof(T).IsValueType)
            {
                return(false);
            }
            if (value != null && !typeof(T).IsAssignableFrom(matcher.Type))
            {
                return(false);
            }

            return(ProfilerInterceptor.GuardExternal(() => predicate((T)value)));
        }
        public void Process(object[] invocationArgs, Type declaringType)
        {
            object[] args = null;

            var func = this.eventDelegateParametersFactory as Func <object[]>;

            if (func != null)
            {
                args = ProfilerInterceptor.GuardExternal(func);
            }
            else
            {
                var invoker = MockingUtil.MakeFuncCaller(this.eventDelegateParametersFactory);
                args = (object[])ProfilerInterceptor.GuardExternal(() => invoker(invocationArgs, this.eventDelegateParametersFactory));
            }

            RaiseEventImpl(this.instance, this.evt, args);
        }
Esempio n. 9
0
 private object CallInvoke(MethodBase method, object[] args)
 {
     try
     {
         return(ProfilerInterceptor.GuardExternal(() => SecuredReflectionMethods.Invoke(method, this.instance, args)));
     }
     catch (TargetInvocationException targetInvocationException)
     {
         if (this.RethrowOriginalOnCallMethod && targetInvocationException.InnerException != null)
         {
             throw targetInvocationException.InnerException;
         }
         else
         {
             throw;
         }
     }
 }
Esempio n. 10
0
        private static bool NodeMatchesFilter(CallPattern callPattern, IMatcherTreeNode node)
        {
            var filter = callPattern.Filter;

            if (filter == null)
            {
                return(true);
            }

            var args     = new List <object>();
            var nodeIter = node;

            while (nodeIter != null)
            {
                var valueMatcher = nodeIter.Matcher as IValueMatcher;
                if (valueMatcher != null)
                {
                    args.Add(valueMatcher.Value);
                }
                nodeIter = nodeIter.Parent;
            }

            if (!callPattern.Method.IsStatic && filter.Method.GetParameters().Length + 1 == args.Count)
            {
                args.RemoveAt(args.Count - 1);
            }

            args.Reverse();
            var argsArray = args.ToArray();

            object state;

            MockingUtil.BindToMethod(MockingUtil.Default, new[] { filter.Method }, ref argsArray, null, null, null, out state);

            var filterFunc = MockingUtil.MakeFuncCaller(filter);
            var isMatch    = (bool)ProfilerInterceptor.GuardExternal(() => filterFunc(argsArray, filter));

            DebugView.TraceEvent(IndentLevel.Matcher, () => String.Format("Matcher predicate {0} call to {2} with arguments ({1})",
                                                                          isMatch ? "passed" : "rejected", String.Join(", ", args.Select(x => x.ToString()).ToArray()),
                                                                          callPattern.Method));

            return(isMatch);
        }
Esempio n. 11
0
        public void RaiseEvent(EventInfo evt, object[] delegateArguments)
        {
            Delegate existing;

            eventHandlers.TryGetValue(evt, out existing);

            if (existing != null)
            {
                try
                {
                    object state;
                    MockingUtil.BindToMethod(MockingUtil.Default, new[] { existing.Method }, ref delegateArguments, null, null, null, out state);
                }
                catch (MissingMethodException ex)
                {
                    throw new MockException(String.Format("Event signature {0} is incompatible with argument types ({1})",
                                                          existing.Method, String.Join(", ", delegateArguments.Select(x => x != null ? x.GetType().ToString() : "null").ToArray())
                                                          ), ex);
                }

                var invoker = MockingUtil.MakeFuncCaller(existing);
                ProfilerInterceptor.GuardExternal(() => invoker(delegateArguments, existing));
            }
        }
Esempio n. 12
0
 private object CallInvoke(MethodBase method, object[] args)
 {
     return(ProfilerInterceptor.GuardExternal(() => SecuredReflectionMethods.Invoke(method, this.instance, args)));
 }