/// <summary>
 /// Modifies the current <paramref name="target"/> to support third-party method call interception for all method calls made inside the target.
 /// </summary>
 /// <param name="target">The target object.</param>
 /// <param name="methodCallFilter">The <see cref="IMethodCallFilter"/> instance that determines the method calls that will be intercepted.</param>
 /// <param name="hostMethodFilter">The <see cref="IMethodFilter"/> instance that determines the host method calls that will be modified</param>
 public static void InterceptMethodCalls(this IReflectionVisitable target, IMethodCallFilter methodCallFilter,
     IMethodFilter hostMethodFilter)
 {
     var rewriter = new InterceptMethodCalls(methodCallFilter);
     target.Accept(new ImplementModifiableType(GetDefaultTypeFilter()));
     target.WeaveWith(rewriter, hostMethodFilter.ShouldWeave);
 }
Example #2
0
        /// <summary>
        /// Executes the <paramref name="filter"/> on the <paramref name="method"/>, logging information if it was
        /// excluded.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="type">The type.</param>
        /// <param name="filter">The <see cref="Type"/> filter.</param>
        /// <returns>The result of <see cref="IMethodFilter.ExcludeMethod"/>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="method"/>, <paramref name="type"/> or
        /// <paramref name="filter"/> parameters are <see langword="null"/>.</exception>
        private static bool ApplyFilter(this MethodBase method, Type type, IMethodFilter filter)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            bool excludeMethod = filter.ExcludeMethod(type, method);

            if (excludeMethod)
            {
                ////TODO: Look into Tracing.
                ////Trace.TraceInformation(
                ////    "The method '{0}.{1}' was excluded by the filter '{2}'.",
                ////    type.Name,
                ////    method.Name,
                ////    filter.Name);
            }

            return(excludeMethod);
        }
        /// <summary>
        /// Modifies the <paramref name="target"/> to support intercepting calls to the 'new' operator.
        /// </summary>
        /// <param name="target">The item to be modified.</param>
        /// <param name="newInstanceFilter">The filter that will determine which constructor calls should be intercepted.</param>
        /// <param name="methodFilter">The filter that will determine which host methods should be modified to support new instance interception.</param>
        public static void InterceptNewInstances(this IReflectionVisitable target, INewInstanceFilter newInstanceFilter,
                                                 IMethodFilter methodFilter)
        {
            var redirector = new RedirectNewInstancesToActivator(newInstanceFilter);

            target.InterceptNewInstancesWith(redirector, methodFilter.ShouldWeave);
        }
Example #4
0
	public FileCache(LogManager log, IMethodFilter methodFilter, FileCacheManager manager, IFileObject file, int blockSize) {
		_log = log;
		_dirty = false;
		_manager = manager;
		_file = file;
		_blockSize = blockSize;
		_methodFilter = methodFilter;
	}
        /// <summary>
        ///     Modifies the current <paramref name="target" /> to support third-party method call interception for all method
        ///     calls made inside the target.
        /// </summary>
        /// <param name="target">The target object.</param>
        /// <param name="methodCallFilter">
        ///     The <see cref="IMethodCallFilter" /> instance that determines the method calls that will
        ///     be intercepted.
        /// </param>
        /// <param name="hostMethodFilter">
        ///     The <see cref="IMethodFilter" /> instance that determines the host method calls that
        ///     will be modified
        /// </param>
        public static void InterceptMethodCalls(this TypeDefinition target, IMethodCallFilter methodCallFilter,
                                                IMethodFilter hostMethodFilter)
        {
            var rewriter = new InterceptMethodCalls(methodCallFilter);

            target.Accept(new ImplementModifiableType(GetDefaultTypeFilter()));
            target.WeaveWith(rewriter);
        }
Example #6
0
            public TypeProxyKey(Type type, IProxyHandler handler, IMethodFilter filter)
            {
                Type    = type;
                Handler = handler;
                Filter  = filter;

                //ConcurrentDictionary<TypeProxy,Type> di=new ConcurrentDictionary<TypeProxy, Type>(IEqualityComparer)
            }
        /// <summary>
        /// Modifies the current <paramref name="target"/> to support third-party method call interception for all method calls made inside the target.
        /// </summary>
        /// <param name="target">The target object.</param>
        /// <param name="methodCallFilter">The <see cref="IMethodCallFilter"/> instance that determines the method calls that will be intercepted.</param>
        /// <param name="hostMethodFilter">The <see cref="IMethodFilter"/> instance that determines the host method calls that will be modified</param>
        public static void InterceptMethodCalls(this IReflectionVisitable target, IMethodCallFilter methodCallFilter,
                                                IMethodFilter hostMethodFilter)
        {
            var rewriter = new InterceptMethodCalls(methodCallFilter);

            target.Accept(new ImplementModifiableType(GetDefaultTypeFilter()));
            target.WeaveWith(rewriter, hostMethodFilter.ShouldWeave);
        }
 IEnumerable<Func<IEnumerable<IMethod>, IEnumerable<IMethod>>> FilterMethods(IMethodFilter[] filters)
 {
     if (filters == null)
     {
         yield return inMethods => inMethods;
         yield break;
     }
     foreach (var filter in filters)
         yield return filter.Filter;
 }
 public CreateInterfaceType(IMethodFilter methodFilter, 
                            IMethodBuilder methodBuilder, 
                            IDependencyScope scope, 
                            TypeDefinition targetDependency,
                            ModuleDefinition module)
 {
     _methodFilter = methodFilter;
     _methodBuilder = methodBuilder;
     _scope = scope;
     _targetDependency = targetDependency;
     _module = module;
 }
 public CreateInterfaceType(IMethodFilter methodFilter,
                            IMethodBuilder methodBuilder,
                            IDependencyScope scope,
                            TypeDefinition targetDependency,
                            ModuleDefinition module)
 {
     _methodFilter     = methodFilter;
     _methodBuilder    = methodBuilder;
     _scope            = scope;
     _targetDependency = targetDependency;
     _module           = module;
 }
        /// <summary>
        ///     Modifies the current <paramref name="target" /> to support third-party method call interception for all method
        ///     calls made inside the target.
        /// </summary>
        /// <param name="target">The target object.</param>
        /// <param name="methodCallFilter">
        ///     The <see cref="IMethodCallFilter" /> instance that determines the method calls that will
        ///     be intercepted.
        /// </param>
        /// <param name="hostMethodFilter">
        ///     The <see cref="IMethodFilter" /> instance that determines the host method calls that
        ///     will be modified
        /// </param>
        public static void InterceptMethodCalls(this AssemblyDefinition target,
                                                IMethodCallFilter methodCallFilter,
                                                IMethodFilter hostMethodFilter)
        {
            var module  = target.MainModule;
            var methods = module.Types.Where(t => GetDefaultTypeFilter()(t)).SelectMany(t => t.Methods)
                          .Where(hostMethodFilter.ShouldWeave).ToArray();

            var rewriter = new InterceptMethodCalls(methodCallFilter);

            target.Accept(new ImplementModifiableType(GetDefaultTypeFilter()));
            target.WeaveWith(rewriter);
        }
Example #12
0
        public virtual void RegisterMethodFilter(Type type, IMethodFilter filter)
        {
            if (_filters == null)
            {
                _filters = new Dictionary <Type, IMethodFilter>();
            }

            if (filter != null)
            {
                _filters[type] = filter;
            }
            else
            {
                _filters.Remove(type);
            }
        }
Example #13
0
        public ProxyBuilder(Type type, IProxyHandler handler, IMethodFilter methodFilter)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            if (methodFilter == null)
            {
                throw new ArgumentNullException("methodFilter");
            }

            if (type.IsAbstract)
            {
                throw new TypeProxyException("ProxyBuilder不支持对抽象类与接口的代理");
            }

            if (type.IsSealed)
            {
                throw new TypeProxyException("ProxyBuilder不支持有sealed修饰的类");
            }


            if (type.IsGenericType)
            {
                throw new TypeProxyException("ProxyBuilder不支持泛型类");
            }

            this.type         = type;
            this.handler      = handler;
            this.methodFilter = methodFilter;
            TypeProxyKey key = new TypeProxyKey(type, handler, methodFilter);
            Type         t;

            if (PROXY_TYPES.TryGetValue(key, out t))
            {
                className = t.FullName;
            }
            else
            {
                int id = Interlocked.Increment(ref classid);
                className = GetTypeName(type).Replace('.', '_') + "_Proxy" + "_" + id.ToString().Replace('-', '_');
            }
        }
        /// <summary>
        /// Executes the <paramref name="filter"/> on the <paramref name="method"/>, logging information if it was
        /// excluded.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="type">The type.</param>
        /// <param name="filter">The <see cref="Type"/> filter.</param>
        /// <returns>The result of <see cref="IMethodFilter.ExcludeMethod"/>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="method"/>, <paramref name="type"/> or
        /// <paramref name="filter"/> parameters are <see langword="null"/>.</exception>
        private static bool ApplyFilter(this MethodBase method, Type type, IMethodFilter filter)
        {
            if (method == null)
                throw new ArgumentNullException("method");
            if (type == null)
                throw new ArgumentNullException("type");
            if (filter == null)
                throw new ArgumentNullException("filter");

            bool excludeMethod = filter.ExcludeMethod(type, method);
            if (excludeMethod)
            {
                Trace.TraceInformation(
                    "The method '{0}.{1}' was excluded by the filter '{2}'.",
                    type.Name,
                    method.Name,
                    filter.Name);
            }

            return excludeMethod;
        }
Example #15
0
        /// <summary>
        /// Creates a proxy type of the specified source type.
        /// </summary>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        protected virtual Type InternalCreateProxyType(Type sourceType)
        {
            // load virtual methods
            MethodInfo[] methods = sourceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where((item) =>
                                                                                                                                     // not constrcutor methods
                                                                                                                                     !item.IsConstructor &&

                                                                                                                                     // only overridable methods
                                                                                                                                     this.IsMethodOverridable(item) &&

                                                                                                                                     // ignore property methods and operator override method
                                                                                                                                     !item.IsSpecialName &&

                                                                                                                                     // ignore marked methods
                                                                                                                                     item.GetCustomAttributes(typeof(FilterIgnoreAttribute), true).Length == 0 &&

                                                                                                                                     // ignore common methods defined in System.Object class
                                                                                                                                     !item.DeclaringType.Equals(typeof(object))).ToArray();

            // load virtual properties
            PropertyInfo[] properties = sourceType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where((item) =>
                                                                                                                                             // ignore index properties
                                                                                                                                             item.GetIndexParameters().Length == 0 &&

                                                                                                                                             // can read or write
                                                                                                                                             (item.CanRead || item.CanWrite) &&

                                                                                                                                             // ignore special properties
                                                                                                                                             !item.IsSpecialName &&

                                                                                                                                             // ignore marked methods
                                                                                                                                             Attribute.GetCustomAttributes(item, typeof(FilterIgnoreAttribute), true).Length == 0 &&

                                                                                                                                             // ignore common properties defined in System.Object class
                                                                                                                                             !item.DeclaringType.Equals(typeof(object))).ToArray();

            // find class filters
            MethodFilterAttribute[] classFilters = sourceType.GetCustomAttributes(typeof(MethodFilterAttribute), true).Cast <MethodFilterAttribute>().OrderBy((item) => item.Order).ToArray();

            // find methods filters
            MethodFilterAttribute[][] methodFilters = new MethodFilterAttribute[methods.Length][];
            for (int i = 0; i < methods.Length; i++)
            {
                methodFilters[i] = methods[i].GetCustomAttributes(typeof(MethodFilterAttribute), true).Cast <MethodFilterAttribute>().OrderBy((item) => item.Order).ToArray();
            }

            // find properties filters
            MethodFilterAttribute[][] propertyFilters = new MethodFilterAttribute[properties.Length][];
            for (int i = 0; i < properties.Length; i++)
            {
                propertyFilters[i] = Attribute.GetCustomAttributes(properties[i], typeof(MethodFilterAttribute), true).Cast <MethodFilterAttribute>().OrderBy((item) => item.Order).ToArray();
            }

            if (methods.Length == 0 && properties.Length == 0 || classFilters.Length == 0 && methodFilters.All((item) => item.Length == 0) && propertyFilters.All((item) => item.Length == 0))
            {
                return(sourceType);
            }

            ILGenerator generator = null;

            #region Create Proxy Type

            TypeAttributes typeAttributes = sourceType.Attributes;
            typeAttributes &= ~(TypeAttributes.NestedPrivate | TypeAttributes.NestedPublic | TypeAttributes.NestedFamily | TypeAttributes.NestedAssembly | TypeAttributes.NestedFamANDAssem | TypeAttributes.NestedFamORAssem);
            typeAttributes |= TypeAttributes.Public;

            Type   typeParameter  = null;
            Type[] typeParameters = null;
            GenericTypeParameterBuilder   typeParameterBuilder  = null;
            GenericTypeParameterBuilder[] typeParameterBuilders = null;
            TypeBuilder typeBuilder = this.m_moduleBuilder.DefineType(this.GetProxyTypeName(sourceType), typeAttributes, sourceType);
            this.InjectCustomAttributes(sourceType, typeBuilder);

            // create type arguments
            if (sourceType.IsGenericTypeDefinition || sourceType.IsGenericType && sourceType.ContainsGenericParameters)
            {
                typeParameters = sourceType.GetGenericArguments().Where((item) => item.IsGenericParameter).ToArray();
                if (typeParameters.Length > 0)
                {
                    typeParameterBuilders = typeBuilder.DefineGenericParameters(typeParameters.Select((item) => item.Name).ToArray());

                    for (int j = 0; j < typeParameters.Length; j++)
                    {
                        typeParameter        = typeParameters[j];
                        typeParameterBuilder = typeParameterBuilders[j];

                        typeParameterBuilder.SetGenericParameterAttributes(typeParameter.GenericParameterAttributes);
                        foreach (Type constraint in typeParameter.GetGenericParameterConstraints())
                        {
                            if (constraint.IsClass)
                            {
                                typeParameterBuilder.SetBaseTypeConstraint(constraint);
                            }
                            else
                            {
                                typeParameterBuilder.SetInterfaceConstraints(constraint);
                            }
                        }
                    }
                }
            }

            #endregion

            #region Create Static Fields

            int            filterIndex  = 0;
            FieldBuilder[] staticFields = new FieldBuilder[classFilters.Length + methodFilters.Sum((item) => item.Length) + propertyFilters.Sum((item) => item.Length)];

            for (int i = 0; i < classFilters.Length; i++, filterIndex++)
            {
                staticFields[filterIndex] = typeBuilder.DefineField(this.GetStaticFieldName(filterIndex), typeof(IMethodFilter), FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly);
            }
            for (int i = 0; i < methods.Length; i++)
            {
                if (methodFilters[i].Length == 0)
                {
                    continue;
                }

                for (int j = 0; j < methodFilters[i].Length; j++, filterIndex++)
                {
                    staticFields[filterIndex] = typeBuilder.DefineField(this.GetStaticFieldName(filterIndex), typeof(IMethodFilter), FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly);
                }
            }
            for (int i = 0; i < properties.Length; i++)
            {
                if (propertyFilters[i].Length == 0)
                {
                    continue;
                }

                for (int j = 0; j < propertyFilters[i].Length; j++, filterIndex++)
                {
                    staticFields[filterIndex] = typeBuilder.DefineField(this.GetStaticFieldName(filterIndex), typeof(IMethodFilter), FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly);
                }
            }

            #endregion

            #region Create Static Constructor

            string          classKey = this.GetClassKey(sourceType, typeBuilder);
            IMethodFilter[] filters  = g_classFilters[classKey] = new IMethodFilter[staticFields.Length];

            ConstructorBuilder constructorBuilder = typeBuilder.DefineTypeInitializer();
            generator = constructorBuilder.GetILGenerator();

            for (int i = 0; i < classFilters.Length; i++)
            {
                filters[i] = classFilters[i];

                generator.Emit(OpCodes.Ldstr, classKey);
                generator.Emit(OpCodes.Ldc_I4, i);
                generator.Emit(OpCodes.Call, g_getClassFilterMethod);
                generator.Emit(OpCodes.Stsfld, staticFields[i]);
            }

            filterIndex = classFilters.Length;

            for (int i = 0; i < methods.Length; i++)
            {
                if (methodFilters[i].Length == 0)
                {
                    continue;
                }

                for (int j = 0; j < methodFilters[i].Length; j++, filterIndex++)
                {
                    filters[filterIndex] = methodFilters[i][j];

                    generator.Emit(OpCodes.Ldstr, classKey);
                    generator.Emit(OpCodes.Ldc_I4, filterIndex);
                    generator.Emit(OpCodes.Call, g_getClassFilterMethod);
                    generator.Emit(OpCodes.Stsfld, staticFields[filterIndex]);
                }
            }
            for (int i = 0; i < properties.Length; i++)
            {
                if (propertyFilters[i].Length == 0)
                {
                    continue;
                }

                for (int j = 0; j < propertyFilters[i].Length; j++, filterIndex++)
                {
                    filters[filterIndex] = propertyFilters[i][j];

                    generator.Emit(OpCodes.Ldstr, classKey);
                    generator.Emit(OpCodes.Ldc_I4, filterIndex);
                    generator.Emit(OpCodes.Call, g_getClassFilterMethod);
                    generator.Emit(OpCodes.Stsfld, staticFields[filterIndex]);
                }
            }

            generator.Emit(OpCodes.Ret);

            #endregion

            #region Create Instance Constructors

            ParameterInfo[] constructorParameters = null;
            foreach (ConstructorInfo constructor in sourceType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                constructorParameters = constructor.GetParameters();
                constructorBuilder    = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorParameters.Select((item) => item.ParameterType).ToArray());
                for (int i = 0; i < constructorParameters.Length; i++)
                {
                    this.InjectCustomAttributes(
                        constructorParameters[i],
                        constructorBuilder.DefineParameter(i + 1, constructorParameters[i].Attributes, constructorParameters[i].Name));
                }

                generator = constructorBuilder.GetILGenerator();

                // call base constructor
                generator.Emit(OpCodes.Ldarg_0);
                for (int i = 1; i <= constructorParameters.Length; i++)
                {
                    generator.Emit(OpCodes.Ldarg, i);
                }
                generator.Emit(OpCodes.Call, constructor);

                generator.Emit(OpCodes.Ret);
            }

            #endregion

            #region Create Methods

            filterIndex = classFilters.Length;

            for (int i = 0; i < methods.Length; i++)
            {
                if (methodFilters[i].Length + classFilters.Length == 0)
                {
                    continue;
                }

                this.CreateProxyMethod(typeBuilder, methods[i], classFilters, methodFilters[i], staticFields, filterIndex, (item) => true);

                filterIndex += methodFilters[i].Length;
            }

            PropertyInfo    property = null;
            PropertyBuilder propertyBuilder = null;
            MethodInfo      getMethod = null, setMethod = null;
            bool            isGetMethodOverridable = false, isSetMethodOverridable = false;
            bool            isPropertyFilterGetMethod = false, isPropertyFilterSetMethod = false;
            bool            isClassFilterGetMethod = classFilters.Any((item) => item.PropertyMethods.HasFlag(MethodFilterActOnPropertyMethods.GetMethod));
            bool            isClassFilterSetMethod = classFilters.Any((item) => item.PropertyMethods.HasFlag(MethodFilterActOnPropertyMethods.SetMethod));

            for (int i = 0; i < properties.Length; i++)
            {
                if (propertyFilters[i].Length + classFilters.Length == 0)
                {
                    continue;
                }

                property = properties[i];
                isPropertyFilterGetMethod = propertyFilters[i].Any((item) => item.PropertyMethods.HasFlag(MethodFilterActOnPropertyMethods.GetMethod));
                isPropertyFilterSetMethod = propertyFilters[i].Any((item) => item.PropertyMethods.HasFlag(MethodFilterActOnPropertyMethods.SetMethod));

                isGetMethodOverridable = this.IsMethodOverridable(getMethod = property.GetGetMethod(true)) && (isClassFilterGetMethod || isPropertyFilterGetMethod);
                isSetMethodOverridable = this.IsMethodOverridable(setMethod = property.GetSetMethod(true)) && (isClassFilterSetMethod || isPropertyFilterSetMethod);
                if (!isGetMethodOverridable && !isSetMethodOverridable)
                {
                    continue;
                }

                propertyBuilder = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, null);
                if (isGetMethodOverridable)
                {
                    propertyBuilder.SetGetMethod(this.CreateProxyMethod(typeBuilder, getMethod, classFilters, propertyFilters[i], staticFields, filterIndex, (item) => item.PropertyMethods.HasFlag(MethodFilterActOnPropertyMethods.GetMethod)));
                }
                if (isSetMethodOverridable)
                {
                    propertyBuilder.SetSetMethod(this.CreateProxyMethod(typeBuilder, setMethod, classFilters, propertyFilters[i], staticFields, filterIndex, (item) => item.PropertyMethods.HasFlag(MethodFilterActOnPropertyMethods.SetMethod)));
                }

                filterIndex += propertyFilters[i].Length;
            }

            #endregion

            return(typeBuilder.CreateType());
        }
 public MethodBasedOperationCreator(IMethodFilter[] filters, IDependencyResolver resolver, IObjectBinderLocator binderLocator)
 {
     _resolver = resolver;
     _binderLocator = binderLocator;
     _filterMethod = FilterMethods(filters).Chain();
 }
 /// <summary>
 ///     Intercepts all method bodies on the target item.
 /// </summary>
 /// <param name="target">The target to be modified.</param>
 /// <param name="methodFilter">The method filter that will determine the methods that will be modified.</param>
 public static void InterceptMethodBody(this TypeDefinition target, IMethodFilter methodFilter)
 {
     target.InterceptMethodBody(methodFilter.ShouldWeave);
 }
 public static void InterceptMethodBody(this IReflectionStructureVisitable target, IMethodFilter methodFilter)
 {
     target.InterceptMethodBody(methodFilter.ShouldWeave);
 }
 /// <summary>
 /// Enables exception interception on the given type.
 /// </summary>
 /// <param name="visitable">The target type.</param>
 /// <param name="methodFilter">The <see cref="IMethodFilter"/> instance that will determine which methods should support exception interception.</param>
 public static void InterceptExceptions(this IReflectionStructureVisitable visitable, IMethodFilter methodFilter)
 {
     visitable.InterceptExceptions(methodFilter.ShouldWeave);
 }
 /// <summary>
 /// Modifies the <paramref name="target"/> to support intercepting calls to the 'new' operator.
 /// </summary>
 /// <param name="target">The item to be modified.</param>
 /// <param name="newInstanceFilter">The filter that will determine which constructor calls should be intercepted.</param>
 /// <param name="methodFilter">The filter that will determine which host methods should be modified to support new instance interception.</param>
 public static void InterceptNewInstances(this IReflectionVisitable target, INewInstanceFilter newInstanceFilter,
                                          IMethodFilter methodFilter)
 {
     var redirector = new RedirectNewInstancesToActivator(newInstanceFilter);
     target.InterceptNewInstancesWith(redirector, methodFilter.ShouldWeave);
 }
 public static void InterceptMethodBody(this IReflectionVisitable target, IMethodFilter methodFilter, ITypeFilter typeFilter)
 {
     target.InterceptMethodBody(methodFilter.ShouldWeave, typeFilter.ShouldWeave);
 }
        /// <summary>
        ///     Modifies the <paramref name="target" /> to support intercepting calls to the 'new' operator.
        /// </summary>
        /// <param name="target">The item to be modified.</param>
        /// <param name="newInstanceFilter">The filter that will determine which constructor calls should be intercepted.</param>
        /// <param name="methodFilter">
        ///     The filter that will determine which host methods should be modified to support new instance
        ///     interception.
        /// </param>
        public static void InterceptNewInstances(this AssemblyDefinition target,
                                                 INewInstanceFilter newInstanceFilter, IMethodFilter methodFilter)
        {
            var redirector = new RedirectNewInstancesToActivator(newInstanceFilter);

            target.InterceptNewInstancesWith(redirector, methodFilter.ShouldWeave);
        }
 public void SetUp()
 {
     _classFilter = MockRepository.GenerateMock<IClassFilter>();
     _classFilter
         .Stub(arg => arg.Matches(Arg<Type>.Is.Anything))
         .WhenCalled(arg => arg.ReturnValue = (Type)arg.Arguments.First() == typeof(Endpoint))
         .Return(false);
     _methodFilter = MockRepository.GenerateMock<IMethodFilter>();
     _methodFilter
         .Stub(arg => arg.Matches(Arg<MethodInfo>.Is.Anything))
         .WhenCalled(arg => arg.ReturnValue = ((MethodInfo)arg.Arguments.First()).Name == "IncludedMethod")
         .Return(false);
     _idMapper = MockRepository.GenerateMock<IIdMapper>();
     _idMapper.Stub(arg => arg.Map(Arg<Type>.Is.Anything, Arg<MethodInfo>.Is.Anything)).Return(IdResult.IdMapped(Guid.NewGuid()));
     _nameMapper = MockRepository.GenerateMock<INameMapper>();
     _nameMapper.Stub(arg => arg.Map(Arg<Type>.Is.Anything, Arg<MethodInfo>.Is.Anything)).Return(NameResult.NameMapped("name"));
     _resolvedRelativeUrlMapper = MockRepository.GenerateMock<IResolvedRelativeUrlMapper>();
     _resolvedRelativeUrlMapper.Stub(arg => arg.Map(Arg<Type>.Is.Anything, Arg<MethodInfo>.Is.Anything)).Return(ResolvedRelativeUrlResult.ResolvedRelativeUrlMapped("relative"));
     _responseMapper = MockRepository.GenerateMock<IResponseMapper>();
     _autoRouteCollection = new AutoRouteCollection()
         .Assemblies(Assembly.GetExecutingAssembly())
         .ClassFilters(_classFilter)
         .MethodFilters(_methodFilter)
         .NameMappers(_nameMapper)
         .IdMappers(_idMapper)
         .ResolvedRelativeUrlMappers(_resolvedRelativeUrlMapper)
         .ResponseMapper(_responseMapper);
     _routes = _autoRouteCollection.GenerateRouteCollection().ToArray();
 }
Example #24
0
 public static void InterceptMethodBody(this IReflectionVisitable target, IMethodFilter methodFilter, ITypeFilter typeFilter)
 {
     target.InterceptMethodBody(methodFilter.ShouldWeave, typeFilter.ShouldWeave);
 }
Example #25
0
        public virtual IMethodExecutor Resolve(IEvaluationContext context, object targetObject, string name, List <Type> argumentTypes)
        {
            try
            {
                var typeConverter = context.TypeConverter;
                var type          = targetObject is Type type1 ? type1 : targetObject.GetType();
                var methods       = new List <MethodInfo>(GetMethods(type, targetObject));

                // If a filter is registered for this type, call it
                IMethodFilter filter = null;
                _filters?.TryGetValue(type, out filter);
                if (filter != null)
                {
                    methods = filter.Filter(methods);
                }

                // Sort methods into a sensible order
                if (methods.Count > 1)
                {
                    methods.Sort((m1, m2) =>
                    {
                        var m1pl = m1.GetParameters().Length;
                        var m2pl = m2.GetParameters().Length;

                        // vararg methods go last
                        if (m1pl == m2pl)
                        {
                            if (!m1.IsVarArgs() && m2.IsVarArgs())
                            {
                                return(-1);
                            }
                            else if (m1.IsVarArgs() && !m2.IsVarArgs())
                            {
                                return(1);
                            }
                            else
                            {
                                return(0);
                            }
                        }

                        return(m1pl.CompareTo(m2pl));
                    });
                }

                // Remove duplicate methods (possible due to resolved bridge methods)
                var methodsToIterate = new HashSet <MethodInfo>(methods);

                MethodInfo closeMatch               = null;
                var        closeMatchDistance       = int.MaxValue;
                MethodInfo matchRequiringConversion = null;
                var        multipleOptions          = false;

                foreach (var method in methodsToIterate)
                {
                    if (method.Name.Equals(name))
                    {
                        var parameters = method.GetParameters();
                        var paramCount = parameters.Length;

                        var paramDescriptors = new List <Type>(paramCount);
                        for (var i = 0; i < paramCount; i++)
                        {
                            paramDescriptors.Add(parameters[i].ParameterType);
                        }

                        ArgumentsMatchInfo matchInfo = null;
                        if (method.IsVarArgs() && argumentTypes.Count >= (paramCount - 1))
                        {
                            // *sigh* complicated
                            matchInfo = ReflectionHelper.CompareArgumentsVarargs(paramDescriptors, argumentTypes, typeConverter);
                        }
                        else if (paramCount == argumentTypes.Count)
                        {
                            // Name and parameter number match, check the arguments
                            matchInfo = ReflectionHelper.CompareArguments(paramDescriptors, argumentTypes, typeConverter);
                        }

                        if (matchInfo != null)
                        {
                            if (matchInfo.IsExactMatch)
                            {
                                return(new ReflectiveMethodExecutor(method));
                            }
                            else if (matchInfo.IsCloseMatch)
                            {
                                if (_useDistance)
                                {
                                    var matchDistance = ReflectionHelper.GetTypeDifferenceWeight(paramDescriptors, argumentTypes);
                                    if (closeMatch == null || matchDistance < closeMatchDistance)
                                    {
                                        // This is a better match...
                                        closeMatch         = method;
                                        closeMatchDistance = matchDistance;
                                    }
                                }
                                else
                                {
                                    // Take this as a close match if there isn't one already
                                    if (closeMatch == null)
                                    {
                                        closeMatch = method;
                                    }
                                }
                            }
                            else if (matchInfo.IsMatchRequiringConversion)
                            {
                                if (matchRequiringConversion != null)
                                {
                                    multipleOptions = true;
                                }

                                matchRequiringConversion = method;
                            }
                        }
                    }
                }

                if (closeMatch != null)
                {
                    return(new ReflectiveMethodExecutor(closeMatch));
                }
                else if (matchRequiringConversion != null)
                {
                    if (multipleOptions)
                    {
                        throw new SpelEvaluationException(SpelMessage.MULTIPLE_POSSIBLE_METHODS, name);
                    }

                    return(new ReflectiveMethodExecutor(matchRequiringConversion));
                }
                else
                {
                    return(null);
                }
            }
            catch (EvaluationException ex)
            {
                throw new AccessException("Failed to resolve method", ex);
            }
        }
Example #26
0
 /// <summary>
 ///     Enables exception interception on the given type.
 /// </summary>
 /// <param name="visitable">The target type.</param>
 /// <param name="methodFilter">
 ///     The <see cref="IMethodFilter" /> instance that will determine which methods should support
 ///     exception interception.
 /// </param>
 public static void InterceptExceptions(this AssemblyDefinition visitable, IMethodFilter methodFilter)
 {
     visitable.InterceptExceptions(methodFilter.ShouldWeave);
 }
Example #27
0
 public static void InterceptMethodBody(this IReflectionStructureVisitable target, IMethodFilter methodFilter)
 {
     target.InterceptMethodBody(methodFilter.ShouldWeave);
 }
Example #28
0
 public static object GetProxyObject(Type type, IProxyHandler handler, IMethodFilter methodFilter)
 {
     return(new ProxyBuilder(type, handler, methodFilter).GetProxy());
 }
 protected void AddFilter(IMethodFilter filter)
 {
     FilterList.Add(filter);
 }
 /// <summary>
 /// Enables exception interception on the given type.
 /// </summary>
 /// <param name="visitable">The target type.</param>
 /// <param name="methodFilter">The <see cref="IMethodFilter"/> instance that will determine which methods should support exception interception.</param>
 public static void InterceptExceptions(this IReflectionStructureVisitable visitable, IMethodFilter methodFilter)
 {
     visitable.InterceptExceptions(methodFilter.ShouldWeave);
 }