Пример #1
0
        /// <summary>
        ///     Find methods of the supplied type which have WebGet or WebInvoke attributes.
        /// </summary>
        /// <param name="basePath">Base service basePath.</param>
        /// <param name="serviceType">The implementation type to search.</param>
        /// <param name="definitionsTypesList">Types to be documented in the models section.</param>
        internal IEnumerable<Path> FindMethods(string basePath, Type serviceType, IList<Type> definitionsTypesList)
        {
            var paths = new List<Path>();
            var pathActions = new List<Tuple<string, PathAction>>();

            if (!basePath.EndsWith("/"))
                basePath = basePath + "/";

            //search all interfaces for this type for potential DataContracts, and build a set of items
            Type[] interfaces = serviceType.GetInterfaces();
            foreach (Type i in interfaces)
            {
                Attribute dc = i.GetCustomAttribute(typeof(ServiceContractAttribute));
                if (dc == null)
                    continue;

                //found a DataContract, now get a service map and inspect the methods for WebGet/WebInvoke
                InterfaceMapping map = serviceType.GetInterfaceMap(i);
                pathActions.AddRange(GetActions(map, definitionsTypesList));
            }

            foreach (Tuple<string, PathAction> pathAction in pathActions)
            {
                GetPath(basePath, pathAction.Item1, paths).Actions.Add(pathAction.Item2);
            }

            return paths;
        }
Пример #2
0
        private static Action<object, object> GetHandlerAction(Type typeThatImplementsHandler, Type messageType)
        {
            Type interfaceGenericType = typeof (IHandleMessage<>);
            var interfaceType = interfaceGenericType.MakeGenericType(messageType);

            if (interfaceType.IsAssignableFrom(typeThatImplementsHandler))
            {
                var methodInfo = typeThatImplementsHandler.GetInterfaceMap(interfaceType).TargetMethods.FirstOrDefault();

                if (methodInfo != null)
                {
                    ParameterInfo firstParameter = methodInfo.GetParameters().First();

                    if (firstParameter.ParameterType != messageType)
                        return null;

                    var handler = Expression.Parameter(typeof (object));
                    var message = Expression.Parameter(typeof (object));

                    var castTarget = Expression.Convert(handler, typeThatImplementsHandler);
                    var castParam = Expression.Convert(message, methodInfo.GetParameters().First().ParameterType);
                    var execute = Expression.Call(castTarget, methodInfo, castParam);
                    return Expression.Lambda<Action<object, object>>(execute, handler, message).Compile();
                }
            }

            return null;
        }
Пример #3
0
        private static CloneHandler CreateCloneWrapper(Type type)
        {
            var cloneMethod = new DynamicMethod
            (
                "NativeClone",
                MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.NewSlot,
                CallingConventions.Standard,
                typeof(IntPtr), new Type[] { type },
                type, false
            );
            var ilGenerator = cloneMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Ldarg_0); // Step 1: Push the object to clone on the stack
            // Just to be clean, don't suppose ICloneable only has one member…
            var cloneableInterfaceMap = type.GetInterfaceMap(typeof(ICloneable));
            for (int i = 0; i < cloneableInterfaceMap.InterfaceMethods.Length; i++)
                if (cloneableInterfaceMap.InterfaceMethods[i].Name == "Clone")
                {
                    ilGenerator.Emit(OpCodes.Call, cloneableInterfaceMap.TargetMethods[i]); // Step 2: clone it
                    goto CloneMethodFound; // Finish the job once we found the Clone method (which should always be found)
                }
            throw new InvalidOperationException(); // This line should never be reached
            CloneMethodFound:
            ilGenerator.Emit(OpCodes.Isinst, type); // Step 3: Cast it to the correct type
            var nativePointerProperty = type.GetProperty
            (
                "NativePointer",
                BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder,
                typeof(IntPtr), Type.EmptyTypes, null
            );
            ilGenerator.Emit(OpCodes.Call, nativePointerProperty.GetGetMethod(true)); // Step 4: Get the native pointer
            ilGenerator.Emit(OpCodes.Ret); // Step 5: Return the value

            return cloneMethod.CreateDelegate(typeof(CloneHandler)) as CloneHandler;
        }
Пример #4
0
        static IDictionary<Type, MethodInfo> GetHandleMethods(Type targetType, Type messageType)
        {
            var result = new Dictionary<Type, MethodInfo>();

            foreach (var handlerInterface in handlerInterfaces)
            {
                MethodInfo method = null;

                var interfaceType = handlerInterface.MakeGenericType(messageType);

                if (interfaceType.IsAssignableFrom(targetType))
                {
                    method = targetType.GetInterfaceMap(interfaceType)
                        .TargetMethods
                        .FirstOrDefault();
                }

                if (method != null)
                {
                    result.Add(handlerInterface, method);
                }
            }

            return result;
        }
        static IDictionary<Type, MethodInfo> GetHandleMethods(Type targetType, Type messageType)
        {
            var result = new Dictionary<Type, MethodInfo>();
            foreach (var handlerInterface in handlerInterfaces)
            {
                MethodInfo method = null;
                try
                {
                    method = targetType.GetInterfaceMap(handlerInterface.MakeGenericType(messageType))
                        .TargetMethods
                        .FirstOrDefault();

                }
                catch
                {
                    //intentionally swallow
                }

                if (method != null)
                   result.Add(handlerInterface,method);

            }

            return result;
        }
        public static void DefineInterface(TypeBuilder typeBuilder, Type interfaceType, Type implementType,
            Action<ILGenerator, MethodInfo, MethodInfo> ilGenerator)
        {
            var proxyMethodBuilder = new ProxyMethodBuilder(typeBuilder);
            InterfaceMapping mapping = implementType.GetInterfaceMap(interfaceType);
            for (int i = 0; i < mapping.InterfaceMethods.Length; i++)
                mapping.TargetMethods[i] = proxyMethodBuilder.DefineMethod(mapping.InterfaceMethods[i],
                    il => ilGenerator(il, mapping.InterfaceMethods[i], mapping.TargetMethods[i]));

            foreach (PropertyInfo propertyInfo in interfaceType.GetProperties())
            {
                MethodBuilder getMethodBuilder = null;
                MethodInfo getMethodInfo = propertyInfo.GetGetMethod();
                if (getMethodInfo != null)
                    getMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, getMethodInfo);

                MethodBuilder setMethodBuilder = null;
                MethodInfo setMethodInfo = propertyInfo.GetSetMethod();
                if (setMethodInfo != null)
                    setMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, setMethodInfo);

                ProxyBuilderHelper.DefineProperty(typeBuilder, propertyInfo, getMethodBuilder, setMethodBuilder);
            }

            foreach (EventInfo eventInfo in interfaceType.GetEvents())
            {
                var addMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, eventInfo.GetAddMethod());
                var removeMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, eventInfo.GetRemoveMethod());
                ProxyBuilderHelper.DefineEvent(typeBuilder, eventInfo, addMethodBuilder, removeMethodBuilder);
            }
        }
        private IEnumerable<MethodImplementationInfo> DoGetInterceptableMethods(Type interceptedType, Type implementationType)
        {
            var interceptableMethodsToInterfaceMap = new Dictionary<MethodInfo, MethodInfo>();

            foreach (MethodInfo method in
                implementationType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (MethodOverride.MethodCanBeIntercepted(method))
                {
                    interceptableMethodsToInterfaceMap[method] = null;
                }
            }

            foreach(Type itf in implementationType.GetInterfaces())
            {
                var mapping = implementationType.GetInterfaceMap(itf);
                for(int i = 0; i < mapping.InterfaceMethods.Length; ++i)
                {
                    if(interceptableMethodsToInterfaceMap.ContainsKey(mapping.TargetMethods[i]))
                    {
                        interceptableMethodsToInterfaceMap[mapping.TargetMethods[i]] = mapping.InterfaceMethods[i];
                    }
                }
            }

            foreach(var kvp in interceptableMethodsToInterfaceMap)
            {
                yield return new MethodImplementationInfo(kvp.Value, kvp.Key);
            }
        }
        private bool IsDefinedOnType(MemberInfo member, Type type)
        {
            if (member.DeclaringType != type)
            {
                return false;
            }

            if (member.MemberType == MemberTypes.Property && !type.IsInterface)
            {
                var property = (PropertyInfo) member;

                IEnumerable<MethodInfo> interfaceMethods =
                    (from i in type.GetInterfaces()
                     from method in type.GetInterfaceMap(i).TargetMethods
                     select method);

                bool exists = (from method in interfaceMethods
                               where property.GetAccessors().Contains(method)
                               select 1).Count() > 0;

                if (exists) return false;
            }

            return true;
        }
Пример #9
0
    public static XmlRpcServiceInfo CreateServiceInfo(Type type)
    {
      XmlRpcServiceInfo svcInfo = new XmlRpcServiceInfo();
      // extract service info
      XmlRpcServiceAttribute svcAttr = (XmlRpcServiceAttribute)
        Attribute.GetCustomAttribute(type, typeof(XmlRpcServiceAttribute));
      if (svcAttr != null && svcAttr.Description != "")
        svcInfo.doc = svcAttr.Description;
      if (svcAttr != null && svcAttr.Name != "")
        svcInfo.Name = svcAttr.Name;
      else
        svcInfo.Name = type.Name;
      // extract method info
      var methods = new Dictionary<string, XmlRpcMethodInfo>();

      foreach (Type itf in type.GetInterfaces())
      {
        XmlRpcServiceAttribute itfAttr = (XmlRpcServiceAttribute)
          Attribute.GetCustomAttribute(itf, typeof(XmlRpcServiceAttribute));
        if (itfAttr != null)
          svcInfo.doc = itfAttr.Description;
#if (!COMPACT_FRAMEWORK)
        InterfaceMapping imap = type.GetInterfaceMap(itf);
        foreach (MethodInfo mi in imap.InterfaceMethods)
        {
          ExtractMethodInfo(methods, mi, itf);
        }
#else
        foreach (MethodInfo mi in itf.GetMethods())
        {
          ExtractMethodInfo(methods, mi, itf);
        }
#endif
      }

      foreach (MethodInfo mi in type.GetMethods())
      {
        var mthds = new List<MethodInfo>();
        mthds.Add(mi);
        MethodInfo curMi = mi;
        while (true)
        {
          MethodInfo baseMi = curMi.GetBaseDefinition();
          if (baseMi.DeclaringType == curMi.DeclaringType)
            break;
          mthds.Insert(0, baseMi);
          curMi = baseMi;
        }
        foreach (MethodInfo mthd in mthds)
        {
          ExtractMethodInfo(methods, mthd, type);
        }
      }
      svcInfo.methodInfos = new XmlRpcMethodInfo[methods.Count];
      methods.Values.CopyTo(svcInfo.methodInfos, 0);
      Array.Sort(svcInfo.methodInfos);
      return svcInfo;
    }
Пример #10
0
        private static CommandAttribute GetMethodAttribute(Type implementationType, Type commandType)
        {
            var method = implementationType
                .GetInterfaceMap(commandType)
                .TargetMethods
                .Single();

            return method.GetCustomAttribute<CommandAttribute>();
        }
        static MethodInfo GetHandleMethod(Type targetType, Type messageType)
        {
            var method = targetType.GetMethod("Handle", new[] { messageType });
            if (method != null) return method;

            var handlerType = typeof(IMessageHandler<>).MakeGenericType(messageType);
            return targetType.GetInterfaceMap(handlerType)
                .TargetMethods
                .FirstOrDefault();
        }
Пример #12
0
 public static void HasInterfaceMap(IDictionary<string, string> expectedMap, Type type, Type interfaceType)
 {
     var map = type.GetInterfaceMap(interfaceType);
       foreach (var entry in expectedMap) {
     int index = map.InterfaceMethods.ToList().FindIndex(method => method.Name == entry.Key);
     Assert.AreNotEqual(-1, index);
     var targetMethod = map.TargetMethods[index].Name;
     Assert.AreEqual(entry.Value, targetMethod);
       }
 }
Пример #13
0
 static IEnumerable<Type> GetInterfacesForMethod(Type type, MethodInfo method)
 {
     foreach (var itf in type.GetInterfaces())
     {
         var interfaceMap = type.GetInterfaceMap(itf);
         if (interfaceMap.TargetMethods.Any(m => m == method))
         {
             yield return itf;
         }
     }
 }
Пример #14
0
        static MethodInfo GetHandleMethod(Type targetType, Type messageType)
        {
            var method = targetType.GetMethods().FirstOrDefault(m => m.GetParameters().Any(p => p.ParameterType == messageType));

            if (method != null) return method;

            var handlerType = typeof(IMessageHandler<>).MakeGenericType(messageType);
            return targetType.GetInterfaceMap(handlerType)
                .TargetMethods
                .FirstOrDefault();
        }
Пример #15
0
        /// <summary>
        /// Maps the provided <paramref name="interfaceType"/> to the provided <paramref name="implementationType"/>.
        /// </summary>
        /// <param name="interfaceType">The interface type.</param>
        /// <param name="implementationType">The implementation type.</param>
        /// <returns>The mapped interface.</returns>
        private static IReadOnlyDictionary<int, MethodInfo> MapInterfaceToImplementation(
            Type interfaceType,
            Type implementationType)
        {
            var interfaceMapping = implementationType.GetInterfaceMap(interfaceType);

            // Map the interface methods to implementation methods.
            var interfaceMethods = GrainInterfaceData.GetMethods(interfaceType);
            return interfaceMethods.ToDictionary(
                GrainInterfaceData.ComputeMethodId,
                interfaceMethod => GetImplementingMethod(interfaceMethod, interfaceMapping));
        }
 private static IEnumerable<MethodImplementationInfo> GetImplementedInterfaceMethods(Type t)
 {
     foreach (Type itf in t.GetInterfaces())
     {
         InterfaceMapping mapping = t.GetInterfaceMap(itf);
         for (int i = 0; i < mapping.InterfaceMethods.Length; ++i)
         {
             yield return new MethodImplementationInfo(
                 mapping.InterfaceMethods[i], mapping.TargetMethods[i]);
         }
     }
 }
Пример #17
0
        /// <summary>
        /// Given a property or a field try to get the member from a given possible inherited type.
        /// </summary>
        /// <param name="member">The member to find.</param>
        /// <param name="reflectedType">The type where find the member.</param>
        /// <returns>The member from the reflected-type or the original <paramref name="member"/> where the <paramref name="member"/> is not accessible from <paramref name="reflectedType"/>.</returns>
        public static MemberInfo GetMemberFromReflectedType(this MemberInfo member, System.Type reflectedType)
        {
            if (member == null)
            {
                throw new ArgumentNullException("member");
            }
            if (reflectedType == null)
            {
                throw new ArgumentNullException("reflectedType");
            }
            var field = member as FieldInfo;

            if (field != null && field.IsPrivate)
            {
                return(member);
            }
            var property = member as PropertyInfo;

            if (property != null)
            {
                var propertyGetter = property.GetGetMethod(true);
                if (propertyGetter.IsPrivate)
                {
                    return(member);
                }
                if (property.DeclaringType.IsInterface)
                {
                    System.Type[] interfaces = reflectedType.GetInterfaces();
                    var           @interface = property.DeclaringType;
                    if (!interfaces.Contains(@interface))
                    {
                        return(member);
                    }
                    var reflectedCandidateProps = reflectedType.GetProperties(PropertiesOfClassHierarchy);
                    InterfaceMapping memberMap  = reflectedType.GetInterfaceMap(@interface);
                    for (int i = 0; i < memberMap.TargetMethods.Length; i++)
                    {
                        if (memberMap.InterfaceMethods[i] == propertyGetter)
                        {
                            return(reflectedCandidateProps.Single(pi => pi.GetGetMethod(true) == memberMap.TargetMethods[i]));
                        }
                    }
                    return(member);
                }
            }
            var reflectedTypeProperties = reflectedType.GetProperties(PropertiesOfClassHierarchy);
            var members = reflectedTypeProperties.Cast <MemberInfo>().Concat(reflectedType.GetFields(PropertiesOfClassHierarchy));
            var result  = members.FirstOrDefault(m => m.Name.Equals(member.Name) && m.GetPropertyOrFieldType().Equals(member.GetPropertyOrFieldType()));

            return(result ?? member);
        }
Пример #18
0
        /// <summary>
        /// Maps the provided <paramref name="interfaceId"/> to the provided <paramref name="implementationType"/>.
        /// </summary>
        /// <param name="interfaceType">The interface type.</param>
        /// <param name="implementationType">The implementation type.</param>
        /// <returns>The mapped interface.</returns>
        private static IReadOnlyDictionary<int, MethodInfo> GetInterfaceToImplementationMap(
            int interfaceId,
            Type implementationType)
        {
            // Get the interface mapping for the current implementation.
            var interfaceTypes = GrainInterfaceUtils.GetRemoteInterfaces(implementationType);
            var interfaceType = interfaceTypes[interfaceId];
            var interfaceMapping = implementationType.GetInterfaceMap(interfaceType);

            // Map the interface methods to implementation methods.
            var interfaceMethods = GrainInterfaceUtils.GetMethods(interfaceType);
            return interfaceMethods.ToDictionary(
                GrainInterfaceUtils.ComputeMethodId,
                interfaceMethod => GetImplementingMethod(interfaceMethod, interfaceMapping));
        }
 internal static MethodInfo FindInterfaceMethodInfo(Type type, string signature)
 {
     foreach (Type type2 in type.GetInterfaces())
     {
         InterfaceMapping interfaceMap = type.GetInterfaceMap(type2);
         MethodInfo[] targetMethods = interfaceMap.TargetMethods;
         for (int i = 0; i < targetMethods.Length; i++)
         {
             if (targetMethods[i].ToString() == signature)
             {
                 return interfaceMap.InterfaceMethods[i];
             }
         }
     }
     return null;
 }
        public bool AppliesTo(MethodInfo method, Type mixin, Type compositeType, Type fragmentClass)
        {
            InterfaceMapping map = fragmentClass.GetInterfaceMap(method.DeclaringType);

            for (int i = 0; i < map.InterfaceMethods.Length; i++)
            {
                if (map.InterfaceMethods[i] == method)
                {
                    MethodInfo targetMethod = map.TargetMethods[i];

                    return targetMethod.IsAbstract;
                }
            }

            return false;
        }
Пример #21
0
        public static MethodInfo MapInterfaceMethodToImplementationIfNecessary(MethodInfo methodInfo, System.Type implementingType)
        {
            AssertUtils.ArgumentNotNull(methodInfo, "methodInfo");
            AssertUtils.ArgumentNotNull(implementingType, "implementingType");
            AssertUtils.IsTrue(methodInfo.DeclaringType.IsAssignableFrom(implementingType), "methodInfo and implementingType are unrelated");

            MethodInfo concreteMethodInfo = methodInfo;

            if (methodInfo.DeclaringType.IsInterface)
            {
                InterfaceMapping interfaceMapping = implementingType.GetInterfaceMap(methodInfo.DeclaringType);
                int methodIndex = Array.IndexOf(interfaceMapping.InterfaceMethods, methodInfo);
                concreteMethodInfo = interfaceMapping.TargetMethods[methodIndex];
            }

            return(concreteMethodInfo);
        }
Пример #22
0
		private static MethodInfo ObtainMethod(MethodInfo proxiedMethod, Type type)
		{
			Type[] genericArguments = null;
			if (proxiedMethod.IsGenericMethod)
			{
				genericArguments = proxiedMethod.GetGenericArguments();
				proxiedMethod = proxiedMethod.GetGenericMethodDefinition();
			}
			Type declaringType = proxiedMethod.DeclaringType;
			MethodInfo methodOnTarget = null;
			if (declaringType.IsInterface)
			{
				var mapping = type.GetInterfaceMap(declaringType);
				int index = Array.IndexOf(mapping.InterfaceMethods, proxiedMethod);
				Debug.Assert(index != -1);
				methodOnTarget = mapping.TargetMethods[index];
			}
			else
			{
				// NOTE: this implementation sucks, feel free to improve it.
				var methods = MethodFinder.GetAllInstanceMethods(type, BindingFlags.Public | BindingFlags.NonPublic);
				foreach (var method in methods)
				{

					if (MethodSignatureComparer.Instance.Equals(method.GetBaseDefinition(), proxiedMethod))
					{
						methodOnTarget = method;
						break;
					}
				}	
			}
			if (methodOnTarget == null)
			{
				throw new ArgumentException(
					string.Format("Could not find method overriding {0} on type {1}. This is most likely a bug. Please report it.",
					              proxiedMethod, type));
			}

			if (genericArguments == null)
			{
				return methodOnTarget;
			}
			return methodOnTarget.MakeGenericMethod(genericArguments);
		}
        protected static PropagationDirections CalculateSkipPropagationFlags(Type handlerType)
        {
            bool skipOutbound = true;
            bool skipInbound = true;

            InterfaceMapping mapping = handlerType.GetInterfaceMap(typeof(IChannelHandler));
            for (int index = 0; index < mapping.InterfaceMethods.Length && (skipInbound || skipOutbound); index++)
            {
                MethodInfo method = mapping.InterfaceMethods[index];
                var propagationAttribute = method.GetCustomAttribute<PipelinePropagationAttribute>();
                if (propagationAttribute == null)
                {
                    continue;
                }

                MethodInfo implMethod = mapping.TargetMethods[index];
                if (implMethod.GetCustomAttribute<SkipAttribute>(false) == null)
                {
                    switch (propagationAttribute.Direction)
                    {
                        case PropagationDirections.Inbound:
                            skipInbound = false;
                            break;
                        case PropagationDirections.Outbound:
                            skipOutbound = false;
                            break;
                        default:
                            throw new NotSupportedException(string.Format("PropagationDirection value of {0} is not supported.", propagationAttribute.Direction));
                    }
                }
            }

            var result = PropagationDirections.None;
            if (skipInbound)
            {
                result |= PropagationDirections.Inbound;
            }
            if (skipOutbound)
            {
                result |= PropagationDirections.Outbound;
            }
            return result;
        }
Пример #24
0
        public static Action<object, object> BuildHandlerAction(Type handlerType, Type messageContract)
        {
            Type interfaceGenericType = typeof(IHandleMessage<>);
            var interfaceType = interfaceGenericType.MakeGenericType(messageContract);

            if (!interfaceType.IsAssignableFrom(handlerType))
                return null;

            var methodInfo = handlerType.GetInterfaceMap(interfaceType).TargetMethods.FirstOrDefault();

            if (methodInfo == null)
                return null;

            ParameterInfo firstParameter = methodInfo.GetParameters().First();

            if (firstParameter.ParameterType != messageContract)
                return null;

            Expression<Action<object, object>> handlerAction = BuildHandlerExpression(handlerType, methodInfo);
            return handlerAction.Compile();
        }
Пример #25
0
        // Get only public methods, or public/protected if type is not sealed
        public static MethodInfo[] GetMethods(System.Type monoType)
        {
            MethodInfo[] methodInfos = monoType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            List <MethodInfo> interfaceMethods = null;

            // Make sure we include non-public methods implementing interfaces
            if (!monoType.IsInterface && !monoType.IsGenericTypeDefinition)
            {
                System.Type[] interfaceTypes = monoType.GetInterfaces();
                if (interfaceTypes.Length > 0)
                {
                    for (int i = 0; i < interfaceTypes.Length; i++)
                    {
                        InterfaceMapping interfaceMapping = monoType.GetInterfaceMap(interfaceTypes[i]);
                        MethodInfo[]     targetMethods    = interfaceMapping.TargetMethods;
                        if (interfaceMethods == null)
                        {
                            interfaceMethods = new List <MethodInfo>();
                        }
                        interfaceMethods.AddRange(targetMethods);
                    }
                }
            }

            List <MethodInfo> finalInfos = new List <MethodInfo>();

            foreach (MethodInfo methodInfo in methodInfos)
            {
                if (methodInfo.IsPublic || (!monoType.IsSealed && methodInfo.IsFamily))
                {
                    finalInfos.Add(methodInfo);
                }
                else if (interfaceMethods != null && interfaceMethods.Contains(methodInfo))
                {
                    finalInfos.Add(methodInfo);
                }
            }
            return(finalInfos.ToArray());
        }
Пример #26
0
 private IEnumerable<MethodImplementationInfo> DoGetInterceptableMethods(
     Type interceptedType,
     Type implementationType)
 {
     if (interceptedType.IsInterface && implementationType.IsInterface
         && interceptedType.IsAssignableFrom(implementationType))
     {
         var methods = interceptedType.GetMethods();
         for (int i = 0; i < methods.Length; ++i)
         {
             yield return new MethodImplementationInfo(methods[i], methods[i]);
         }
     }
     else
     {
         InterfaceMapping mapping = implementationType.GetInterfaceMap(interceptedType);
         for (int i = 0; i < mapping.InterfaceMethods.Length; ++i)
         {
             yield return new MethodImplementationInfo(mapping.InterfaceMethods[i], mapping.TargetMethods[i]);
         }
     }
 }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="type"></param>
		/// <param name="method"></param>
		/// <param name="interceptors"></param>W
		/// <returns></returns>
		public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
		{
			if (!metaInfo.Contains(method))
			{
				if (IsInterfaceMappingCandidate(type, method))
				{
					var map = type.GetInterfaceMap(method.DeclaringType);
					var index = Array.IndexOf(map.InterfaceMethods, method);
					if (index >= 0 && metaInfo.Contains(map.TargetMethods[index]))
						return interceptors;
				}

				interceptors = interceptors.Where(i => i is SynchronizeInterceptor == false).ToArray();
			}

			if (existingSelector != null)
			{
				interceptors = existingSelector.SelectInterceptors(type, method, interceptors);
			}

			return interceptors;
		}
 public static MemberInfo ConvertToClassMI(Type t, MemberInfo mi)
 {
     Type reflectedType = mi.ReflectedType;
     if (!reflectedType.IsInterface)
     {
         return mi;
     }
     Cachetable cachetable = (Cachetable) Cache.Get(t);
     if (cachetable != null)
     {
         MemberInfo info = (MemberInfo) cachetable.Get(mi);
         if (info != null)
         {
             return info;
         }
     }
     MethodInfo info2 = (MethodInfo) mi;
     MethodInfo nv = null;
     InterfaceMapping interfaceMap = t.GetInterfaceMap(reflectedType);
     if (interfaceMap.TargetMethods == null)
     {
         throw new InvalidCastException();
     }
     for (int i = 0; i < interfaceMap.TargetMethods.Length; i++)
     {
         if (interfaceMap.InterfaceMethods[i] == info2)
         {
             nv = interfaceMap.TargetMethods[i];
             break;
         }
     }
     if (cachetable == null)
     {
         cachetable = (Cachetable) Cache.Set(t, new Cachetable());
     }
     cachetable.Reset(mi, nv);
     return nv;
 }
        public override void CompileTimeInitialize(Type type, AspectInfo aspectInfo)
        {
            base.CompileTimeInitialize(type, aspectInfo);

            if (!typeof(IEditableObject).IsAssignableFrom(type))
            {
                this.interfaceImplementationMap = new Dictionary<MethodBase, MethodBase>();
                return;
            }

            if (typeof(IEditableObject).IsAssignableFrom(type))
            {
                var targetIEditableMethodsInterfaceMap = type.GetInterfaceMap(typeof(IEditableObject));
                var aspectIEditableMethodsInterfaceMap = this.GetType().GetInterfaceMap(typeof(IEditableObject));

                var targetIEditableMethodsMap = targetIEditableMethodsInterfaceMap.InterfaceMethods.Zip(
                    targetIEditableMethodsInterfaceMap.TargetMethods, (im, tm) => new { InterfaceMethod = im, TargetMethod = tm })
                    .ToList();

                if (!targetIEditableMethodsMap.All(t => t.TargetMethod.IsToBeImplementedMethod()))
                {
                    DomainMessageSource.Instance.Write(type, SeverityType.Error, "DOM016", type.FullName);
                }

                var aspectIEditableMethodsMap = aspectIEditableMethodsInterfaceMap.InterfaceMethods.Zip(
                    aspectIEditableMethodsInterfaceMap.TargetMethods, (im, tm) => new { InterfaceMethod = im, TargetMethod = tm })
                    .ToList();

                this.interfaceImplementationMap =
                    targetIEditableMethodsMap
                    .Join(
                        aspectIEditableMethodsMap,
                        m => m.InterfaceMethod,
                        m => m.InterfaceMethod,
                        (tm, am) => new { TargetMethod = (MethodBase)tm.TargetMethod, AspectMethod = (MethodBase)am.TargetMethod })
                    .ToDictionary(r => r.TargetMethod, r => r.AspectMethod);
            }
        }
        static MethodInfo GetHandleMethod(Type targetType, Type messageType)
        {
            foreach (var handlerInterface in handlerInterfaces)
            {
                MethodInfo method = null;
                try
                {
                    method = targetType.GetInterfaceMap(handlerInterface.MakeGenericType(messageType))
                        .TargetMethods
                        .FirstOrDefault();

                }
                catch
                {
                    //intentionally swallow
                }

                if (method != null)
                    return method;

            }

            return null;
        }
Пример #31
0
        private static MethodInfo GetMethodOnTypeThatImplementsInterfaceMethod(Type type, MethodInfo method)
        {
            var baseDefinition = method.GetBaseDefinition();

            if (!baseDefinition.DeclaringType.IsInterface || !TypeImplementsInterface(type, baseDefinition.DeclaringType))
            {
                return null;
            }

            var interfaceMap = type.GetInterfaceMap(baseDefinition.DeclaringType);

            return
                (from methodTargetPair in interfaceMap.InterfaceMethods
                     .Zip(interfaceMap.TargetMethods, (interfaceMethod, targetMethod) => new { InterfaceMethod = interfaceMethod, TargetMethod = targetMethod })
                 where HasSameBaseMethod(EnsureNonGeneric(methodTargetPair.InterfaceMethod), EnsureNonGeneric(method))
                 select MakeGeneric(methodTargetPair.TargetMethod, method)).First();
        }
Пример #32
0
        //[Test]
        //public void TestThis()
        //{
        //    PrintMethods(typeof(Impl1));
        //    PrintMethods(typeof(Impl2));
        //    PrintMethods(typeof(Impl3));
        //    PrintMethods(typeof(I1));
        //    PrintInterfaceMaps(typeof(Impl1));
        //    PrintInterfaceMaps(typeof(Impl2));
        //    PrintInterfaceMaps(typeof(Impl3));
        //    Expect(true);
        //}
        private void PrintInterfaceMaps(Type type)
        {
            Console.WriteLine("Interface map for {0}",
                type.FullName);

            Type[] interfaces = type.GetInterfaces();
            if (interfaces.Length == 0)
                Console.WriteLine("No interfaces");
            else
            {
                foreach (Type iftype in interfaces)
                {
                    InterfaceMapping im = type.GetInterfaceMap(iftype);
                    MethodInfo[] ifMeths = im.InterfaceMethods;
                    MethodInfo[] tgtMeths = im.TargetMethods;

                    for (int i = 0; i < ifMeths.Length; i++)
                    {
                        PrintMethod(ifMeths[i]);
                        PrintMethod(tgtMeths[i]);
                        Console.WriteLine("-");
                    }
                }
            }

            Console.WriteLine("------");
        }
        private static void EmitCallBaseIfLazyInitializerIsNull(
            ILGenerator IL,
            MethodInfo method,
            FieldInfo lazyInitializerField,
            System.Type parentType)
        {
            /*
             *      if (this.__lazyInitializer == null)
             *      <if (method.IsAbstract)
             *      {>
             *      return default;
             *      <} else {>
             *      return base.<method>(args..);
             *      <}>
             */

            // When deriving from the entity class, the entity class constructor may trigger
            // virtual calls accessing the proxy state before its own constructor has a chance
            // to initialize it. So although lazyInitializer is never supplied as null to the
            // proxy constructor, we must guard nonetheless against it being null during base
            // constructor call.

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldfld, lazyInitializerField);
            var skipBaseCall = IL.DefineLabel();

            IL.Emit(OpCodes.Ldnull);
            IL.Emit(OpCodes.Bne_Un, skipBaseCall);

            if (method.DeclaringType.IsInterface &&
                method.DeclaringType.IsAssignableFrom(parentType))
            {
                var interfaceMap = parentType.GetInterfaceMap(method.DeclaringType);
                var methodIndex  = Array.IndexOf(interfaceMap.InterfaceMethods, method);
                method = interfaceMap.TargetMethods[methodIndex];
            }

            if (method.IsAbstract)
            {
                /*
                 * return default(<ReturnType>);
                 */

                if (!method.ReturnType.IsValueType)
                {
                    IL.Emit(OpCodes.Ldnull);
                }
                else if (method.ReturnType != typeof(void))
                {
                    var local = IL.DeclareLocal(method.ReturnType);
                    IL.Emit(OpCodes.Ldloca, local);
                    IL.Emit(OpCodes.Initobj, method.ReturnType);
                    IL.Emit(OpCodes.Ldloc, local);
                }

                IL.Emit(OpCodes.Ret);
            }
            else if (method.IsPrivate)
            {
                /*
                 * var mi = (MethodInfo)MethodBase.GetMethodFromHandle(<method>, <parentType>);
                 * var delegate = (<delegateType>)mi.CreateDelegate(typeof(<delegateType>), this);
                 * delegate.Invoke(args...);
                 */

                var parameters = method.GetParameters();

                var delegateType = Expression.GetDelegateType(
                    parameters.Select(p => p.ParameterType).Concat(new[] { method.ReturnType }).ToArray());

                var invokeDelegate = delegateType.GetMethod("Invoke");

                IL.Emit(OpCodes.Ldtoken, method);
                IL.Emit(OpCodes.Ldtoken, parentType);
                IL.Emit(OpCodes.Call, ReflectionCache.MethodBaseMethods.GetMethodFromHandleWithDeclaringType);
                IL.Emit(OpCodes.Castclass, typeof(MethodInfo));
                IL.Emit(OpCodes.Ldtoken, delegateType);
                IL.Emit(OpCodes.Call, ReflectionCache.TypeMethods.GetTypeFromHandle);
                IL.Emit(OpCodes.Ldarg_0);
                IL.Emit(
                    OpCodes.Callvirt,
                    typeof(MethodInfo).GetMethod(
                        nameof(MethodInfo.CreateDelegate),
                        new[] { typeof(System.Type), typeof(object) }));
                IL.Emit(OpCodes.Castclass, delegateType);

                EmitCallMethod(IL, OpCodes.Callvirt, invokeDelegate);
                IL.Emit(OpCodes.Ret);
            }
            else
            {
                /*
                 * base.<method>(args...);
                 */

                IL.Emit(OpCodes.Ldarg_0);
                EmitCallMethod(IL, OpCodes.Call, method);
                IL.Emit(OpCodes.Ret);
            }

            IL.MarkLabel(skipBaseCall);
        }
Пример #34
0
            public override IList<Type/*!*/>/*!*/ GetInterfaces(Type/*!*/ t) {
                if (t.IsInterface) {
                    return t.GetInterfaces();
                }

                Type[] allInterfaces = t.GetInterfaces();
                List<Type> res = new List<Type>();
                foreach (Type intf in allInterfaces) {
                    try {
                        InterfaceMapping imap = t.GetInterfaceMap(intf);
                        foreach (MethodInfo mi in imap.TargetMethods) {
                            if (mi.DeclaringType == t) {
                                res.Add(intf);
                                break;
                            }
                        }
                    } catch (ArgumentException) {
                        // this fails when the CLR is manufacturing an interface
                        // type for a built in type.  For example IList<string>
                        // for Array[str].  This can be reproed by doing:
                        //
                        // import System
                        // System.Array[str].__dict__['__contains__']

                        // __contains__ is actually inherited from Array's IList
                        // implementation but IList<str> interferes here.
                    }
                }

                return res;
            }
Пример #35
0
 public static InterfaceMapping GetRuntimeInterfaceMap(this Type type, Type iface)
 {
     return(type.GetInterfaceMap(iface));
 }
Пример #36
0
 private static Dictionary <System.Type, Dictionary <MethodInfo, MethodInfo> > BuildInterfacesMap(System.Type type)
 {
     return(type.GetInterfaces()
            .Distinct()
            .ToDictionary(i => i, i => ToDictionary(type.GetInterfaceMap(i))));
 }