public Maybe<ITransactionOptions> AsTransactional(MethodInfo target)
		{
			Contract.Requires(target != null);
			Contract.Ensures(Contract.Result<Maybe<TransactionAttribute>>() != null);
			return _TxMethodsHackMap.ContainsKey(target.ToString())
					? Maybe.Some<ITransactionOptions>(_TxMethodsHackMap[target.ToString()])
			       	: Maybe.None<ITransactionOptions>();
		}
Esempio n. 2
0
		private static IntPtr MethodInfoToFtnptr (MethodInfo method) {
			if (module_builder.Assembly.GetType ("BridgeHelpers" + method.ToString ()) != null)
				return (IntPtr) module_builder.Assembly.GetType ("BridgeHelpers" + method.ToString ()).InvokeMember ("InternalMethodInfoToFtnPtr", BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public, null, null, new object[] { });

			TypeBuilder ftn_converter_builder = module_builder.DefineType ("BridgeHelpers" + method.ToString (), TypeAttributes.Public);
			MethodBuilder ftn_method = ftn_converter_builder.DefineMethod ("InternalMethodInfoToFtnPtr", MethodAttributes.Public | MethodAttributes.Static, typeof (IntPtr), new Type[] { }); 
			ILGenerator il_generator = ftn_method.GetILGenerator ();
			
			il_generator.Emit (OpCodes.Ldftn, method);
			il_generator.Emit (OpCodes.Ret);
			
			Type ftn_converter = ftn_converter_builder.CreateType ();
			return (IntPtr) ftn_converter.InvokeMember ("InternalMethodInfoToFtnPtr", BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public, null, null, new object[] { });
		}
 internal static WebMethodAttribute GetAttribute(MethodInfo implementation, MethodInfo declaration)
 {
     WebMethodAttribute attribute = null;
     WebMethodAttribute attribute2 = null;
     object[] customAttributes;
     if (declaration != null)
     {
         customAttributes = declaration.GetCustomAttributes(typeof(WebMethodAttribute), false);
         if (customAttributes.Length > 0)
         {
             attribute = (WebMethodAttribute) customAttributes[0];
         }
     }
     customAttributes = implementation.GetCustomAttributes(typeof(WebMethodAttribute), false);
     if (customAttributes.Length > 0)
     {
         attribute2 = (WebMethodAttribute) customAttributes[0];
     }
     if (attribute == null)
     {
         return attribute2;
     }
     if (attribute2 == null)
     {
         return attribute;
     }
     if (attribute2.MessageNameSpecified)
     {
         throw new InvalidOperationException(Res.GetString("ContractOverride", new object[] { implementation.Name, implementation.DeclaringType.FullName, declaration.DeclaringType.FullName, declaration.ToString(), "WebMethod.MessageName" }));
     }
     return new WebMethodAttribute(attribute2.EnableSessionSpecified ? attribute2.EnableSession : attribute.EnableSession) { TransactionOption = attribute2.TransactionOptionSpecified ? attribute2.TransactionOption : attribute.TransactionOption, CacheDuration = attribute2.CacheDurationSpecified ? attribute2.CacheDuration : attribute.CacheDuration, BufferResponse = attribute2.BufferResponseSpecified ? attribute2.BufferResponse : attribute.BufferResponse, Description = attribute2.DescriptionSpecified ? attribute2.Description : attribute.Description };
 }
Esempio n. 4
0
        public IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method)
        {
            IHqlGeneratorForMethod methodGenerator;

            if (method.IsGenericMethod)
            {
                method = method.GetGenericMethodDefinition();
            }

            if (_registeredMethods.TryGetValue(method, out methodGenerator))
            {
                return methodGenerator;
            }

            // No method generator registered.  Look to see if it's a standard LinqExtensionMethod
            var attr = method.GetCustomAttributes(typeof (LinqExtensionMethodAttribute), false);
            if (attr.Length == 1)
            {
                // It is
                // TODO - cache this?  Is it worth it?
                return new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute) attr[0], method);
            }

            // Not that either.  Let's query each type generator to see if it can handle it
            foreach (var typeGenerator in _typeGenerators)
            {
                if (typeGenerator.SupportsMethod(method))
                {
                    return typeGenerator.GetMethodGenerator(method);
                }
            }

            throw new NotSupportedException(method.ToString());
        }
Esempio n. 5
0
 public MethodNode(object parentObj, MethodInfo m)
     : base(null, NodeTypes.Method, m.ToString())
 {
     parentObject = parentObj;
     method = m;
     CanInvoke = true;
 }
		protected Command(object target, MethodInfo mi)
			: base(target, mi)
		{
			ParameterInfo[] paramList = mi.GetParameters();

			_names = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
			List<Argument> tempList = new List<Argument>();

			foreach (ParameterInfo pi in paramList)
			{
				Argument arg = new Argument(target, pi);
				foreach(string name in arg.AllNames)
					_names.Add(name, tempList.Count);
				tempList.Add(arg);
			}
			_arguments = tempList.ToArray();

			if (base.Description == mi.ToString())
            {//if no description provided, let's build a better one
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("{0} ", base.DisplayName);
                foreach(Argument a in tempList)
					if(a.Visible)
						sb.AppendFormat("{0} ", a.FormatSyntax(a.DisplayName));
                _description = sb.ToString(0, sb.Length - 1);
            }
		}
        public MethodInfo(System.Reflection.MethodInfo mi)
        {
            name = mi.Name;

            // get acces modifires
            modificators = GetModificators(mi.GetType()) + mi.ToString();
            if (mi.IsAbstract && !mi.DeclaringType.IsInterface)
            {
                modificators += "abstract ";
            }
            if (mi.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null)
            {
                modificators += "async ";
            }
            if ((mi.MethodImplementationFlags & MethodImplAttributes.InternalCall) != 0)
            {
                modificators += "extern ";
            }
            if (!mi.Equals(mi.GetBaseDefinition()))
            {
                modificators += "overriden ";
            }
            if (mi.IsVirtual && mi.IsFinal)
            {
                modificators += "sealed ";
            }
            if (mi.IsStatic)
            {
                modificators += "static ";
            }
            if (mi.IsVirtual && !mi.IsFinal && mi.Equals(mi.GetBaseDefinition()) && !mi.DeclaringType.IsInterface)
            {
                modificators += "virtual ";
            }
        }
 public static void executeXRuleMethod(MethodInfo methodToExecute, Action<bool,object> executionResult)
 {            
     if (methodToExecute == null)
     {                
         executionResult(false,null);
     }
     else
         try
         {
             DI.log.info("executing method: {0}", methodToExecute.Name);
             // create method's type using default constructor
             var liveObject = DI.reflection.createObjectUsingDefaultConstructor(methodToExecute.DeclaringType);
             // and execute the method
             var returnData = methodToExecute.Invoke(liveObject, new object[] { });            // don't use the DI.reflection methods since we want the exceptions to be thrown
             //DI.reflection.invoke(liveObject, methodInfo, new object[] {});
             executionResult(true, returnData);
         }
         catch (Exception ex)
         {
             DI.log.error("in UnitTestSupport.executeXRuleMethod: {0} threw error: {1} ", methodToExecute.ToString(),
                          ex.Message);
             if (ex.InnerException != null)
             {
                 var innerExceptionMessage = ex.InnerException.Message;
                 DI.log.error("   InnerException value: {0}", innerExceptionMessage);
                 executionResult(false, innerExceptionMessage);
             }
             else
                 executionResult(false, null);
         }
 }
Esempio n. 9
0
 public void WriteMethod(System.Type type, bool isStatic, System.Reflection.MethodInfo method)
 {
     WriteTypeName(type);
     Console.WriteLine("," + method.Name +
                       ",Public Method" +
                       "," + // property scope column
                       ",\"" + (isStatic?"static ":"") + method.ToString() + "\"");
 }
        public void EmitCall(OpCode opCode, MethodInfo mi)
        {
            ProcessCommand(
                opCode, 
                (mi.GetParameters().Length + 1) * -1 + (mi.ReturnType == typeof(void) ? 0 : 1), 
                mi.ToString()
                );

            ilGenerator.EmitCall(opCode, mi, null);
        }
Esempio n. 11
0
        public void WriteOperator(System.Type type, System.Reflection.MethodInfo method)
        {
            string value;
            bool   found = _operators.TryGetValue(method.Name, out value);

            WriteTypeName(type);
            Console.WriteLine("," + (found?value:method.Name) +
                              ",Operator" +
                              "," + // property scope column
                              ",\"" + method.ToString() + "\"");
        }
Esempio n. 12
0
        public IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method)
        {
            IHqlGeneratorForMethod methodGenerator;

            if (!TryGetMethodGenerator(method, out methodGenerator))
            {
                throw new NotSupportedException(method.ToString());
            }

            return methodGenerator;
        }
Esempio n. 13
0
        private MethodInfo GetParallelMethod(MethodInfo forkMethod)
        {
            MethodInfo result = null;
            MethodInfo[] methods =
                source.GetMethods(BindingFlags.Instance | BindingFlags.Static |
                                  BindingFlags.Public | BindingFlags.NonPublic);
            foreach (MethodInfo method in methods)
                if (IsParallel(method)
                    && SignatureMatch(forkMethod, method))
                {
                    if (result == null)
                        result = method;
                    else
                        throw new InvalidMethodException(source.Name, forkMethod.ToString(),
                                                         "There is more than one parallel method which has a nonchannel parameter signature that matches this [Fork] method.");

                }

            if (result == null)
                throw new InvalidMethodException(source.Name, forkMethod.ToString(),
                                                 "There is no parallel method which has a nonchannel parameter signature that matches this [Fork] method.");

            return result;
        }
 public static MethodDefinition getMethodDefinitionFromMethodInfo(MethodInfo methodInfo, Mono.Cecil.AssemblyDefinition assemblyDefinition)
 {
     foreach (var methodDefinition in CecilUtils.getMethods(assemblyDefinition))
     {
         var functionSignature1 = new FilteredSignature(methodInfo);
         var functionSignature2 = new FilteredSignature(methodDefinition.ToString());
         if (functionSignature1.sSignature == functionSignature2.sSignature)                
             return methodDefinition;
         if (functionSignature1.sFunctionName == functionSignature2.sFunctionName)
         { 
         }
     }
     PublicDI.log.error("in getMethodDefinitionFromMethodInfo, could not map MethodInfo: {0}", methodInfo.ToString());
     return null;
 }
Esempio n. 15
0
        public static void Calculate(ShowResult showResult, int a, int b)
        {
            if (a < 0 || b < 0)
            {
                Console.WriteLine("参数有误");
            }
            else
            {
                System.Reflection.MethodInfo methodInfo = RuntimeReflectionExtensions.GetMethodInfo(showResult);
                Console.WriteLine("在这里写入一条日志" + methodInfo.ToString());

                Console.WriteLine(showResult?.Invoke(a, b));
                //Console.WriteLine(showResult(a, b));
            }
        }
Esempio n. 16
0
        public object GetRealObject(StreamingContext context)
        {
            switch (_memberType)
            {
            case MemberTypes.Constructor:
                ConstructorInfo [] ctors;

                ctors = _reflectedType.GetConstructors(DefaultBinding);
                for (int i = 0; i < ctors.Length; i++)
                {
                    if (ctors[i].ToString().Equals(_memberSignature))
                    {
                        return(ctors[i]);
                    }
                }

                throw new SerializationException(String.Format("Could not find constructor '{0}' in type '{1}'", _memberSignature, _reflectedType));

            case MemberTypes.Method:
                MethodInfo [] methods;

                methods = _reflectedType.GetMethods(DefaultBinding);
                for (int i = 0; i < methods.Length; i++)
                {
                    if ((methods[i]).ToString().Equals(_memberSignature))
                    {
                        return(methods[i]);
                    }
                }
#if NET_2_0
                else if (_genericArguments != null &&
                         methods[i].IsGenericMethod &&
                         methods[i].GetGenericArguments().Length == _genericArguments.Length)
                {
                    MethodInfo mi = methods[i].MakeGenericMethod(_genericArguments);

                    if (mi.ToString() == _memberSignature)
                    {
                        return(mi);
                    }
                }
#endif

                throw new SerializationException(String.Format("Could not find method '{0}' in type '{1}'", _memberSignature, _reflectedType));
Esempio n. 17
0
        // Methods
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            #region Contracts

            if (controllerContext == null) throw new ArgumentNullException();
            if (methodInfo == null) throw new ArgumentNullException();

            #endregion

            // ParameterInfoArray
            var parameterInfoArray = ParameterInfoFactory.Current.GetAll(controllerContext.Controller.GetType(), methodInfo);
            if (parameterInfoArray == null) throw new InvalidOperationException();

            // Current Overload Action Matching
            if (this.IsOverloadMatched(controllerContext, parameterInfoArray) == false)
            {
                return false;
            }

            // Other MethodInfoArray
            var otherMethodInfoArray = MethodInfoFactory.Current.GetAll(controllerContext.Controller.GetType());
            if (otherMethodInfoArray == null) throw new InvalidOperationException();
            
            // Other Overload Action Matching
            foreach (var otherMethodInfo in otherMethodInfoArray)
            {
                // MethodInfo
                if (otherMethodInfo.Name != methodInfo.Name) continue;
                if (otherMethodInfo.ToString() == methodInfo.ToString()) continue;
                if (otherMethodInfo.GetCustomAttribute<OverloadAttribute>() == null) continue;

                // ParameterInfoArray
                var otherParameterInfoArray = ParameterInfoFactory.Current.GetAll(controllerContext.Controller.GetType(), otherMethodInfo);
                if (otherParameterInfoArray == null) throw new InvalidOperationException();
                if (otherParameterInfoArray.Length < parameterInfoArray.Length) continue;

                // IsOverloadMatched
                if (this.IsOverloadMatched(controllerContext, otherParameterInfoArray) == true) return false;
            }

            // Return
            return true;
        }
Esempio n. 18
0
        public override DynamicMethodProxyHandler GetMethodDelegate(
            Module targetModule, 
            MethodInfo genericMethodInfo, 
            params Type[] genericParameterTypes)
        {
            #region  Construct cache key

            if (targetModule == null)
            {
                throw new ArgumentNullException("targetModule");
            }

            string key = targetModule.FullyQualifiedName + "|" + genericMethodInfo.DeclaringType.ToString() + "|" + genericMethodInfo.ToString();
            if (genericParameterTypes != null)
            {
                for (int i = 0; i < genericParameterTypes.Length; ++i)
                {
                    key += "|" + genericParameterTypes[i].ToString();
                }
            }

            #endregion

            DynamicMethodProxyHandler dmd;

            lock (cache2)
            {
                if (cache2.ContainsKey(key))
                {
                    dmd = cache2[key];
                }
                else
                {
                    dmd = DoGetMethodDelegate(targetModule, genericMethodInfo, genericParameterTypes);
                    cache2.Add(key, dmd);
                }
            }

            return dmd;
        }
Esempio n. 19
0
        public static MethodInvokerBase GetMethodInvoker(object targetObject, MethodInfo mi)
        {
            var typeName = "EmitMapper.MethodCaller_" + mi.ToString();

            Type callerType = _typesCache.Get<Type>(
                typeName,
                () =>
                {
                    if (mi.ReturnType == typeof(void))
                    {
                        return BuildActionCallerType(typeName, mi);
                    }
                    else
                    {
                        return BuildFuncCallerType(typeName, mi);
                    }
                }
            );

            MethodInvokerBase result = (MethodInvokerBase)Activator.CreateInstance(callerType);
            result.targetObject = targetObject;
            return result;
        }
        public static ProductionRule GenerateRule(MethodInfo method)
        {
            ProductionAttribute production =
                (ProductionAttribute)Attribute.GetCustomAttribute(method, typeof(ProductionAttribute), false);

            if (production == null)
            {
                return null;
            }

            Type[] newLeft, left, strict, right, newRight;
            production.GetTypes(method, out newLeft, out left, out strict, out right, out newRight);

            var ignoreList = IgnoreAttribute.GetIgnoredTypes(method);
            foreach(var p in method.GetParameters())
            {
                if (ignoreList.Contains(p.ParameterType))
                {
                    throw new InvalidOperationException(string.Format(
                        "ProductionRule: Ignored type is production function parameters list (class: {0}, method: {1}).", method.DeclaringType.Name, method.ToString()));
                }
            }

            Array.Reverse(newLeft);
            Array.Reverse(left);

            return new ProductionRule()
            {
                Method = method,
                NewLeft = newLeft,
                Left = left,
                Strict = strict,
                Right = right,
                NewRight = newRight,
                IgnoreList = ignoreList
            };
        }
Esempio n. 21
0
 public bool OkToUse(MethodInfo m, out string message)
 {
     if (m == null) throw new ArgumentNullException("m");
     string toCheckStr = m.DeclaringType.ToString() + "." + m.ToString(); //[email protected]
     return OkToUseInternal(toCheckStr + "/" + m.ReturnType.ToString(), this.require_members, this.forbid_members, out message); //[email protected]
     //return OkToUseInternal(m.ToString() + "/" + m.ReturnType.ToString(), this.require_members, this.forbid_members, out message); //[email protected]
 }
Esempio n. 22
0
        /// <summary>
        /// Invokes the event handler identified by the given method on the given instance.
        /// </summary>
        /// <param name="instance">The instance to invoke the event handler on.</param>
        /// <param name="method">The method identifying the event handler to invoke.</param>
        private void InvokeEventHandler(object instance, MethodInfo method)
        {
            ParameterInfo[] args = method.GetParameters();

            switch (args.Length)
            {
                case 2:
                    method.Invoke(instance, new object[] { this, new EventArgs() });
                    break;
                case 1:
                    method.Invoke(instance, new object[] { this });
                    break;
                case 0:
                    method.Invoke(instance, null);
                    break;
                default:
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "The specified method was expected to have 0, 1, or 2 parameters: {0}", method.ToString()));
            }
        }
Esempio n. 23
0
        public virtual object GetRealObject(StreamingContext context)
        {
            if (this.m_memberName == null || this.m_reflectedType == null || this.m_memberType == (MemberTypes)0)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
            }
            BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.OptionalParamBinding;
            MemberTypes  memberType  = this.m_memberType;

            switch (memberType)
            {
            case MemberTypes.Constructor:
            {
                if (this.m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_NullSignature"));
                }
                ConstructorInfo[] array = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Constructor, bindingAttr) as ConstructorInfo[];
                if (array.Length == 1)
                {
                    return(array[0]);
                }
                if (array.Length > 1)
                {
                    for (int i = 0; i < array.Length; i++)
                    {
                        if (this.m_signature2 != null)
                        {
                            if (((RuntimeConstructorInfo)array[i]).SerializationToString().Equals(this.m_signature2))
                            {
                                return(array[i]);
                            }
                        }
                        else if (array[i].ToString().Equals(this.m_signature))
                        {
                            return(array[i]);
                        }
                    }
                }
                throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[]
                    {
                        this.m_memberName
                    }));
            }

            case MemberTypes.Event:
            {
                EventInfo[] array2 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Event, bindingAttr) as EventInfo[];
                if (array2.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[]
                        {
                            this.m_memberName
                        }));
                }
                return(array2[0]);
            }

            case MemberTypes.Constructor | MemberTypes.Event:
                break;

            case MemberTypes.Field:
            {
                FieldInfo[] array3 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Field, bindingAttr) as FieldInfo[];
                if (array3.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[]
                        {
                            this.m_memberName
                        }));
                }
                return(array3[0]);
            }

            default:
                if (memberType != MemberTypes.Method)
                {
                    if (memberType == MemberTypes.Property)
                    {
                        PropertyInfo[] array4 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Property, bindingAttr) as PropertyInfo[];
                        if (array4.Length == 0)
                        {
                            throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[]
                            {
                                this.m_memberName
                            }));
                        }
                        if (array4.Length == 1)
                        {
                            return(array4[0]);
                        }
                        if (array4.Length > 1)
                        {
                            for (int j = 0; j < array4.Length; j++)
                            {
                                if (this.m_signature2 != null)
                                {
                                    if (((RuntimePropertyInfo)array4[j]).SerializationToString().Equals(this.m_signature2))
                                    {
                                        return(array4[j]);
                                    }
                                }
                                else if (array4[j].ToString().Equals(this.m_signature))
                                {
                                    return(array4[j]);
                                }
                            }
                        }
                        throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[]
                        {
                            this.m_memberName
                        }));
                    }
                }
                else
                {
                    MethodInfo methodInfo = null;
                    if (this.m_signature == null)
                    {
                        throw new SerializationException(Environment.GetResourceString("Serialization_NullSignature"));
                    }
                    Type[]       array5 = this.m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
                    MethodInfo[] array6 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Method, bindingAttr) as MethodInfo[];
                    if (array6.Length == 1)
                    {
                        methodInfo = array6[0];
                    }
                    else if (array6.Length > 1)
                    {
                        for (int k = 0; k < array6.Length; k++)
                        {
                            if (this.m_signature2 != null)
                            {
                                if (((RuntimeMethodInfo)array6[k]).SerializationToString().Equals(this.m_signature2))
                                {
                                    methodInfo = array6[k];
                                    break;
                                }
                            }
                            else if (array6[k].ToString().Equals(this.m_signature))
                            {
                                methodInfo = array6[k];
                                break;
                            }
                            if (array5 != null && array6[k].IsGenericMethod && array6[k].GetGenericArguments().Length == array5.Length)
                            {
                                MethodInfo methodInfo2 = array6[k].MakeGenericMethod(array5);
                                if (this.m_signature2 != null)
                                {
                                    if (((RuntimeMethodInfo)methodInfo2).SerializationToString().Equals(this.m_signature2))
                                    {
                                        methodInfo = methodInfo2;
                                        break;
                                    }
                                }
                                else if (methodInfo2.ToString().Equals(this.m_signature))
                                {
                                    methodInfo = methodInfo2;
                                    break;
                                }
                            }
                        }
                    }
                    if (methodInfo == null)
                    {
                        throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[]
                        {
                            this.m_memberName
                        }));
                    }
                    if (!methodInfo.IsGenericMethodDefinition)
                    {
                        return(methodInfo);
                    }
                    if (array5 == null)
                    {
                        return(methodInfo);
                    }
                    if (array5[0] == null)
                    {
                        return(null);
                    }
                    return(methodInfo.MakeGenericMethod(array5));
                }
                break;
            }
            throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
        }
Esempio n. 24
0
        public virtual object GetRealObject(StreamingContext context)
        {
            MethodInfo info;

            Type[] valueNoThrow;
            if (((this.m_memberName == null) || (this.m_reflectedType == null)) || (this.m_memberType == 0))
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
            }
            BindingFlags bindingAttr = BindingFlags.OptionalParamBinding | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;

            switch (this.m_memberType)
            {
            case MemberTypes.Constructor:
            {
                if (this.m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_NullSignature"));
                }
                ConstructorInfo[] infoArray4 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Constructor, bindingAttr) as ConstructorInfo[];
                if (infoArray4.Length == 1)
                {
                    return(infoArray4[0]);
                }
                if (infoArray4.Length > 1)
                {
                    for (int i = 0; i < infoArray4.Length; i++)
                    {
                        if (infoArray4[i].ToString().Equals(this.m_signature))
                        {
                            return(infoArray4[i]);
                        }
                    }
                }
                throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[] { this.m_memberName }));
            }

            case MemberTypes.Event:
            {
                EventInfo[] infoArray2 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Event, bindingAttr) as EventInfo[];
                if (infoArray2.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[] { this.m_memberName }));
                }
                return(infoArray2[0]);
            }

            case MemberTypes.Field:
            {
                FieldInfo[] infoArray = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Field, bindingAttr) as FieldInfo[];
                if (infoArray.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[] { this.m_memberName }));
                }
                return(infoArray[0]);
            }

            case MemberTypes.Method:
            {
                info = null;
                if (this.m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_NullSignature"));
                }
                valueNoThrow = this.m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
                MethodInfo[] infoArray5 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Method, bindingAttr) as MethodInfo[];
                if (infoArray5.Length == 1)
                {
                    info = infoArray5[0];
                }
                else if (infoArray5.Length > 1)
                {
                    for (int j = 0; j < infoArray5.Length; j++)
                    {
                        if (infoArray5[j].ToString().Equals(this.m_signature))
                        {
                            info = infoArray5[j];
                            break;
                        }
                        if (((valueNoThrow != null) && infoArray5[j].IsGenericMethod) && (infoArray5[j].GetGenericArguments().Length == valueNoThrow.Length))
                        {
                            MethodInfo info2 = infoArray5[j].MakeGenericMethod(valueNoThrow);
                            if (info2.ToString().Equals(this.m_signature))
                            {
                                info = info2;
                                break;
                            }
                        }
                    }
                }
                break;
            }

            case MemberTypes.Property:
            {
                PropertyInfo[] infoArray3 = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Property, bindingAttr) as PropertyInfo[];
                if (infoArray3.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[] { this.m_memberName }));
                }
                if (infoArray3.Length == 1)
                {
                    return(infoArray3[0]);
                }
                if (infoArray3.Length > 1)
                {
                    for (int k = 0; k < infoArray3.Length; k++)
                    {
                        if (infoArray3[k].ToString().Equals(this.m_signature))
                        {
                            return(infoArray3[k]);
                        }
                    }
                }
                throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[] { this.m_memberName }));
            }

            default:
                throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
            }
            if (info == null)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", new object[] { this.m_memberName }));
            }
            if (!info.IsGenericMethodDefinition)
            {
                return(info);
            }
            if (valueNoThrow == null)
            {
                return(info);
            }
            if (valueNoThrow[0] == null)
            {
                return(null);
            }
            return(info.MakeGenericMethod(valueNoThrow));
        }
Esempio n. 25
0
 public bool VerifyMatchedAction(MethodInfo method)
 {
     return _actionMappings.Any(item => ((ReflectedHttpActionDescriptor)item).MethodInfo.ToString() == method.ToString());
 }
Esempio n. 26
0
 internal void Call(MethodInfo methodInfo)
 {
     if (methodInfo.IsVirtual && !methodInfo.DeclaringType.GetTypeInfo().IsValueType)
     {
         if (_codeGenTrace != CodeGenTrace.None)
             EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
         _ilGen.Emit(OpCodes.Callvirt, methodInfo);
     }
     else if (methodInfo.IsStatic)
     {
         if (_codeGenTrace != CodeGenTrace.None)
             EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
         _ilGen.Emit(OpCodes.Call, methodInfo);
     }
     else
     {
         if (_codeGenTrace != CodeGenTrace.None)
             EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
         _ilGen.Emit(OpCodes.Call, methodInfo);
     }
 }
Esempio n. 27
0
        public Form2(Assembly asm, MethodInfo meth, List<Memory> mem)
        {
            InitializeComponent();

            assembly = asm;
            method = meth;
            memory = mem;

            label6.Text = "Method: " + meth.ToString();

            // Param combo box
            int count = 0;

            foreach (ParameterInfo param in method.GetParameters())
            {
                comboBox1.Items.Add("#" + (count + 1).ToString() + " " + param.ParameterType.ToString().Replace("System.", ""));

                ListViewItem item = new ListViewItem("#" + (count + 1).ToString());
                item.SubItems.Add(param.ParameterType.ToString().Replace("System.", ""));
                item.SubItems.Add("");

                listView1.Items.Add (item);

                count++;

                parameters.Add(new Parameter());
                parameters[parameters.Count - 1].parameterType = param.ParameterType;
            }

            if (count == 0)
            {
                comboBox1.Items.Add("None");
                comboBox1.SelectedIndex = 0;
                comboBox1.Enabled = false;

                comboBox3.Enabled = false;

                button5.Enabled = false;
                button6.Enabled = false;
            }
            else
            {
                comboBox1.SelectedIndex = 0;
            }

            // Fill store box
            for (int i = 0; i < memory.Count; i++)
            {
                // No result storing on void
                if (method.ReturnType != typeof(void))
                {
                    comboBox2.Items.Add("Memory #" + (i + 1));

                    if ((memory[i].full == false) && (comboBox2.SelectedIndex < 0))
                    {
                        comboBox2.SelectedIndex = i;
                        storeTo = i;
                    }
                }
            }

            if (method.ReturnType != typeof(void))
            {
                comboBox2.Items.Add("None");
            }
        }
Esempio n. 28
0
        public static bool IsSupportedOnCurrentRuntime(MethodInfo mi)
        {
            SupportedRuntimeAttribute[] supportedRuntimes = 
                (SupportedRuntimeAttribute[])mi.GetCustomAttributes(typeof(SupportedRuntimeAttribute), true);

            NotSupportedRuntimeAttribute[] notSupportedRuntimes = 
                (NotSupportedRuntimeAttribute[])mi.GetCustomAttributes(typeof(NotSupportedRuntimeAttribute), true);

            // no attributes defined - we default to Yes.
            if (supportedRuntimes.Length + notSupportedRuntimes.Length == 0)
                return true;

            bool supported = false;
            if (supportedRuntimes.Length == 0)
                supported = true;

            foreach (SupportedRuntimeAttribute sr in supportedRuntimes)
            {
                if (RuntimeMatches(sr))
                {
                    supported = true;
                    break;
                }
            }



            if (supported)
            {
                foreach (NotSupportedRuntimeAttribute nsr in notSupportedRuntimes)
                {
                    if (RuntimeMatches(nsr))
                    {
                        supported = false;
                        break;
                    }
                }
            }

            if (!supported)
                InternalLogger.Debug("{0} is not supported on current runtime.", mi.ToString());

            return supported;
        }
Esempio n. 29
0
        public static DynamicMethodDelegate GetDynamicMethodDelegate(MethodInfo genericMethodInfo,
            params Type[] genericParameterTypes)
        {
            #region 检查参数的有效性

            if (genericMethodInfo == null)
            {
                throw new ArgumentNullException("需要被调用的方法的genericMethodInfo不能为空!");
            }

            if (genericParameterTypes != null)
            {
                if (genericParameterTypes.Length != genericMethodInfo.GetGenericArguments().Length)
                {
                    throw new ArgumentException("genericMethodInfo和泛型参数类型的数量不一致!");
                }
            }
            else
            {
                if (genericMethodInfo.GetGenericArguments().Length > 0)
                {
                    throw new ArgumentException("没有为genericMethodInfo指定泛型参数类型!");
                }
            }

            #endregion

            #region  构造用于缓存的key

            string key = genericMethodInfo.DeclaringType.ToString() + "|" + genericMethodInfo.ToString();
            if (genericParameterTypes != null)
            {
                for (int i = 0; i < genericParameterTypes.Length; ++i)
                {
                    key += "|" + genericParameterTypes[i].ToString();
                }
            }

            #endregion

            DynamicMethodDelegate dmd;

            lock (cache)
            {
                if (cache.ContainsKey(key))
                {
                    dmd = cache[key];
                }
                else
                {
                    //动态创建一个封装了泛型方法调用的非泛型方法,并返回绑定到他的DynamicMethodDelegate的实例
                    //返回的动态方法的实现在编译期就是以显式方法调用泛型方法的,因此,最大程度上避免了反射的性能损失
                    DynamicMethod dm = new DynamicMethod(Guid.NewGuid().ToString("N"),
                        typeof(object),
                        new Type[] { typeof(object[]) },
                        typeof(string).Module);

                    ILGenerator il = dm.GetILGenerator();

                    #region 创建所有方法的参数的本地变量

                    //首先获得目标方法的MethodInfo
                    MethodInfo makeGenericMethodInfo;
                    if (genericParameterTypes != null && genericParameterTypes.Length > 0)
                    {
                        makeGenericMethodInfo = genericMethodInfo.MakeGenericMethod(genericParameterTypes);
                    }
                    else
                    {
                        makeGenericMethodInfo = genericMethodInfo;
                    }

                    //声明本地变量
                    ParameterInfo[] pis = makeGenericMethodInfo.GetParameters();
                    for (int i = 0; i < pis.Length; ++i)
                    {
                        il.DeclareLocal(pis[i].ParameterType);
                    }

                    #endregion

                    #region 从paramObjs参数中解析所有参数值到本地变量中

                    for (int i = 0; i < pis.Length; ++i)
                    {
                        il.Emit(OpCodes.Ldarg_0);
                        LoadIndex(il, i);
                        il.Emit(OpCodes.Ldelem_Ref);
                        if (pis[i].ParameterType.IsValueType)
                        {
                            il.Emit(OpCodes.Unbox_Any, pis[i].ParameterType);
                        }
                        else if (pis[i].ParameterType != typeof(object))
                        {
                            il.Emit(OpCodes.Castclass, pis[i].ParameterType);
                        }
                        StoreLocal(il, i);
                    }

                    #endregion

                    #region 执行目标方法

                    for (int i = 0; i < pis.Length; ++i)
                    {
                        LoadLocal(il, i);
                    }
                    if (makeGenericMethodInfo.IsStatic)
                    {
                        il.Emit(OpCodes.Call, makeGenericMethodInfo);
                    }
                    else
                    {
                        throw new NotImplementedException("暂时还没有实现该功能!");
                    }

                    if (makeGenericMethodInfo.ReturnType == typeof(void))
                    {
                        il.Emit(OpCodes.Ldnull);
                    }

                    #endregion

                    il.Emit(OpCodes.Ret);

                    dmd = (DynamicMethodDelegate)dm.CreateDelegate(typeof(DynamicMethodDelegate));
                    cache.Add(key, dmd);
                }
            }

            return dmd;
        }
 /// <summary>
 /// Initialzes a new instance of <see cref="InvalidSignatureException"/>
 /// </summary>
 /// <param name="expectedSignature"><see cref="MethodInfo"/> that represents the expected signature</param>
 public InvalidSignatureException(MethodInfo expectedSignature) : base(string.Format("Method '{0}' was invoked with the wrong signature, expected: {1}", expectedSignature.Name, expectedSignature.ToString()))
 {
 }
Esempio n. 31
0
        public object GetRealObject(StreamingContext context)
        {
            MemberTypes memberType = this._memberType;

            switch (memberType)
            {
            case MemberTypes.Constructor:
            {
                ConstructorInfo[] constructors = this._reflectedType.GetConstructors(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                for (int i = 0; i < constructors.Length; i++)
                {
                    if (constructors[i].ToString().Equals(this._memberSignature))
                    {
                        return(constructors[i]);
                    }
                }
                throw new SerializationException(string.Format("Could not find constructor '{0}' in type '{1}'", this._memberSignature, this._reflectedType));
            }

            case MemberTypes.Event:
            {
                EventInfo @event = this._reflectedType.GetEvent(this._memberName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                if (@event != null)
                {
                    return(@event);
                }
                throw new SerializationException(string.Format("Could not find event '{0}' in type '{1}'", this._memberName, this._reflectedType));
            }

            default:
            {
                if (memberType != MemberTypes.Property)
                {
                    throw new SerializationException(string.Format("Unhandled MemberType {0}", this._memberType));
                }
                PropertyInfo property = this._reflectedType.GetProperty(this._memberName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                if (property != null)
                {
                    return(property);
                }
                throw new SerializationException(string.Format("Could not find property '{0}' in type '{1}'", this._memberName, this._reflectedType));
            }

            case MemberTypes.Field:
            {
                FieldInfo field = this._reflectedType.GetField(this._memberName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                if (field != null)
                {
                    return(field);
                }
                throw new SerializationException(string.Format("Could not find field '{0}' in type '{1}'", this._memberName, this._reflectedType));
            }

            case MemberTypes.Method:
            {
                MethodInfo[] methods = this._reflectedType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                for (int j = 0; j < methods.Length; j++)
                {
                    if (methods[j].ToString().Equals(this._memberSignature))
                    {
                        return(methods[j]);
                    }
                    if (this._genericArguments != null && methods[j].IsGenericMethod && methods[j].GetGenericArguments().Length == this._genericArguments.Length)
                    {
                        MethodInfo methodInfo = methods[j].MakeGenericMethod(this._genericArguments);
                        if (methodInfo.ToString() == this._memberSignature)
                        {
                            return(methodInfo);
                        }
                    }
                }
                throw new SerializationException(string.Format("Could not find method '{0}' in type '{1}'", this._memberSignature, this._reflectedType));
            }
            }
        }
Esempio n. 32
0
 public void Register(object id, MethodInfo method)
 {
     bool context = false;
     XQueryFunctionRecord rec = new XQueryFunctionRecord();
     rec.id = id;
     object[] attrs = method.GetCustomAttributes(typeof(XQuerySignatureAttribute), false);
     XQuerySignatureAttribute sig = null;
     if (attrs.Length > 0)
         sig = (XQuerySignatureAttribute)attrs[0];
     ParameterInfo[] parameter_info = method.GetParameters();
     List<XQuerySequenceType> type_list = new List<XQuerySequenceType>();
     int implict = -1;
     foreach (ParameterInfo pi in parameter_info)
     {
         if (pi.ParameterType == typeof(IContextProvider))
         {
             if (context)
                 throw new ArgumentException(pi.Name);
             context = true;
             continue;
         }
         bool customized = false;
         bool variableParam = false;                
         object[] pi_attrs = pi.GetCustomAttributes(false);
         foreach (object pi_atr in pi_attrs)
         {
             if (pi_atr is System.ParamArrayAttribute)
                 variableParam = true;
             else if (pi_atr is ImplictAttribute)
             {
                 customized = true;
                 if (implict != -1)
                     throw new ArgumentException(pi.Name);
                 implict = pi.Position;
             }
             else
             {
                 XQueryParameterAttribute xattr = pi_atr as XQueryParameterAttribute;
                 if (xattr != null)
                 {
                     type_list.Add(new XQuerySequenceType(xattr.TypeCode, xattr.Cardinality, variableParam ?
                         pi.ParameterType.GetElementType() : pi.ParameterType));                            
                     customized = true;
                     break;
                 }
             }
         }
         if (!customized)
         {
             if (pi.ParameterType == typeof(XQueryNodeIterator))
                 type_list.Add(new XQuerySequenceType(XmlTypeCode.Item, XmlTypeCardinality.ZeroOrMore, pi.ParameterType));
             else
                 type_list.Add(new XQuerySequenceType(pi.ParameterType, XmlTypeCardinality.One));
         }
     }
     if (sig != null && sig.Return != XmlTypeCode.None)
         rec.returnType = new XQuerySequenceType(sig.Return, sig.Cardinality, method.ReturnType);
     else
     {
         if (method.ReturnType == typeof(XQueryNodeIterator))
             rec.returnType = new XQuerySequenceType(XmlTypeCode.Item, XmlTypeCardinality.ZeroOrMore, method.ReturnType);
         else
             rec.returnType = new XQuerySequenceType(method.ReturnType, XmlTypeCardinality.One);
     }
     if (sig != null)
     {
         rec.variableParams = sig.VariableParams;
         rec.validationReader = sig.ValidationReaderDemanded;
     }
     rec.parameters = type_list.ToArray();
     FunctionSocket sock = new FunctionSocket(rec);
     FunctionSocket next;
     if (m_table.TryGetValue(rec.id, out next))
     {
         FunctionSocket curr = next;
         while (curr != null)
         {
             if (curr.rec.parameters.Length == rec.parameters.Length &&
                 curr.rec.variableParams == rec.variableParams)
                 throw new InvalidOperationException(method.ToString());
             curr = curr.next;
         }
         sock.next = next;
     }
     m_table[rec.id] = sock;
     GlobalSymbols.DefineStaticOperator(rec.id, method);
     if (context)
     {
         object[] body;                 
         Executive.Parameter[] parameters;
         if (implict == -1)
         {
             parameters = new Executive.Parameter[parameter_info.Length - 1];
             body = new object[parameter_info.Length + 2];
         }
         else
         {
             parameters = new Executive.Parameter[parameter_info.Length - 2];
             body = new object[parameter_info.Length + 1];
         }
         int k = 0;
         int i = 2;
         body[0] = Funcs.List;
         body[1] = Lisp.List(Lisp.QUOTE, rec.id);
         foreach (ParameterInfo pi in parameter_info)
         {
             if (pi.Position != implict)
             {
                 if (pi.ParameterType != typeof(IContextProvider))
                 {
                     parameters[k] = new Executive.Parameter();
                     parameters[k].ID = ATOM.Create(String.Format("p{0}", k + 1));
                     parameters[k].Type = typeof(System.Object);
                     parameters[k].VariableParam = false;
                     body[i++] = parameters[k].ID;
                     k++;
                 }
                 else
                     body[i++] = Lisp.List(Lisp.QUOTE, ID.Context);
             }
         }
         GlobalSymbols.Defmacro(rec.id, parameters, Lisp.List(body));
     }
 }
Esempio n. 33
0
 public object GetMethoParam(MethodInfo info, object param)
 {
     if (param is string)
     {
         object paraObject = null;
         try
         {
             paraObject = GetStringObject(info, param.ToString());
         }
         catch (Exception ex)
         {
             var friendlyEx = new UserFriendlyException("{0} 方法的请求参数出错".Fill(info.ToString()));
             friendlyEx.InnerException = ex;
             throw friendlyEx;
         }
         return paraObject;
     }
     else if (param is List<HttpPostedFile>)
     {
         return GetFileObject(info, param);
     }           
     throw new UserFriendlyException("请求的参数类型错误, 目前只支持文件和数据类型");
 }
Esempio n. 34
0
 private string getFunc(MethodInfo meth)
 {
     List<string> listTemp = util.getListValueWithToken(meth.ToString(), '(');
     string func = listTemp[0] + "(";
     ParameterInfo[] pis = meth.GetParameters();
     int n = pis.Length;
     if (n > 0)
     {
         for (int j = 0; j < n - 1; j++)
         {
             ParameterInfo info = pis[j];
             func += info.ParameterType.Name + " " + info.Name + ",";
         }
         ParameterInfo lastinfo = pis[n - 1];
         func += lastinfo.ParameterType.Name + " " + lastinfo.Name;
     }
     func += ")";
     return func;
 }
Esempio n. 35
0
 public static void GetSerializationInfo(SerializationInfo info, MethodInfo m)
 {
     Type[] genericArguments = (m.IsGenericMethod & !m.IsGenericMethodDefinition) ? m.GetGenericArguments() : null;
     GetSerializationInfo(info, m.Name, m.ReflectedType, m.ToString(), m.SerializationToString(), MemberTypes.Method, genericArguments);
 }
Esempio n. 36
0
		private static Boolean MethodsEqual(MethodInfo aMethod, MethodInfo bMethod)
		{
			//TODO: Compare all arguments, custom attributes, etc.
			return aMethod.ToString() == bMethod.ToString();
		}
 internal void Call(MethodInfo methodInfo)
 {
     if (methodInfo.IsVirtual)
     {
         if (this.codeGenTrace != CodeGenTrace.None)
         {
             this.EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
         }
         this.ilGen.Emit(OpCodes.Callvirt, methodInfo);
     }
     else if (methodInfo.IsStatic)
     {
         if (this.codeGenTrace != CodeGenTrace.None)
         {
             this.EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
         }
         this.ilGen.Emit(OpCodes.Call, methodInfo);
     }
     else
     {
         if (this.codeGenTrace != CodeGenTrace.None)
         {
             this.EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
         }
         this.ilGen.Emit(OpCodes.Call, methodInfo);
     }
 }
Esempio n. 38
0
 /// <summary>
 /// Checks if the method has the same signature as a method that was marked as
 /// one that should generate a new vtable slot.
 /// </summary>
 public bool ShouldCreateNewSlot(MethodInfo method)
 {
     string methodStr = method.ToString();
     foreach (MethodInfo candidate in _generateNewSlot)
     {
         if (candidate.ToString() == methodStr)
             return true;
     }
     return false;
 }
Esempio n. 39
0
        [System.Security.SecurityCritical]  // auto-generated
        public virtual Object GetRealObject(StreamingContext context)
        {
            if (m_memberName == null || m_reflectedType == null || m_memberType == 0)
            {
                throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState));
            }

            BindingFlags bindingFlags =
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Static | BindingFlags.OptionalParamBinding;

            switch (m_memberType)
            {
                #region case MemberTypes.Field:
            case MemberTypes.Field:
            {
                FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[];

                if (fields.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
                }

                return(fields[0]);
            }
                #endregion

                #region case MemberTypes.Event:
            case MemberTypes.Event:
            {
                EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[];

                if (events.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
                }

                return(events[0]);
            }
                #endregion

                #region case MemberTypes.Property:
            case MemberTypes.Property:
            {
                PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[];

                if (properties.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
                }

                if (properties.Length == 1)
                {
                    return(properties[0]);
                }

                if (properties.Length > 1)
                {
                    for (int i = 0; i < properties.Length; i++)
                    {
                        if (m_signature2 != null)
                        {
                            if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2))
                            {
                                return(properties[i]);
                            }
                        }
                        else
                        {
                            if ((properties[i]).ToString().Equals(m_signature))
                            {
                                return(properties[i]);
                            }
                        }
                    }
                }

                throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
            }
                #endregion

                #region case MemberTypes.Constructor:
            case MemberTypes.Constructor:
            {
                if (m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
                }

                ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[];

                if (constructors.Length == 1)
                {
                    return(constructors[0]);
                }

                if (constructors.Length > 1)
                {
                    for (int i = 0; i < constructors.Length; i++)
                    {
                        if (m_signature2 != null)
                        {
                            if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2))
                            {
                                return(constructors[i]);
                            }
                        }
                        else
                        {
                            if (constructors[i].ToString().Equals(m_signature))
                            {
                                return(constructors[i]);
                            }
                        }
                    }
                }

                throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
            }
                #endregion

                #region case MemberTypes.Method:
            case MemberTypes.Method:
            {
                MethodInfo methodInfo = null;

                if (m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
                }

                Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];

                MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[];

                if (methods.Length == 1)
                {
                    methodInfo = methods[0];
                }

                else if (methods.Length > 1)
                {
                    for (int i = 0; i < methods.Length; i++)
                    {
                        if (m_signature2 != null)
                        {
                            if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2))
                            {
                                methodInfo = methods[i];
                                break;
                            }
                        }
                        else
                        {
                            if (methods[i].ToString().Equals(m_signature))
                            {
                                methodInfo = methods[i];
                                break;
                            }
                        }

                        // Handle generic methods specially since the signature match above probably won't work (the candidate
                        // method info hasn't been instantiated). If our target method is generic as well we can skip this.
                        if (genericArguments != null && methods[i].IsGenericMethod)
                        {
                            if (methods[i].GetGenericArguments().Length == genericArguments.Length)
                            {
                                MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments);

                                if (m_signature2 != null)
                                {
                                    if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2))
                                    {
                                        methodInfo = candidateMethod;
                                        break;
                                    }
                                }
                                else
                                {
                                    if (candidateMethod.ToString().Equals(m_signature))
                                    {
                                        methodInfo = candidateMethod;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                if (methodInfo == null)
                {
                    throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
                }

                if (!methodInfo.IsGenericMethodDefinition)
                {
                    return(methodInfo);
                }

                if (genericArguments == null)
                {
                    return(methodInfo);
                }

                if (genericArguments[0] == null)
                {
                    return(null);
                }

                return(methodInfo.MakeGenericMethod(genericArguments));
            }
                #endregion

            default:
                throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
            }
        }
Esempio n. 40
0
		/// <summary>Writes XML documenting a method.</summary>
		/// <param name="writer">XmlWriter to write on.</param>
		/// <param name="method">Method to document.</param>
		/// <param name="inherited">true if a declaringType attribute should be included.</param>
		/// <param name="overload">If &gt; 0, indicates this it the nth overloaded method with the same name.</param>
		/// <param name="hiding">true if this method hides methods of the base class with the same signature.</param>
		private void WriteMethod(XmlWriter writer, MethodInfo method, bool inherited, int overload, bool hiding)
		{
			if (method != null)
			{
				string memberName = MemberID.GetMemberID(method);

				string name = method.Name;
				string interfaceName = null;

				name = name.Replace('+', '.');
				int lastIndexOfDot = name.LastIndexOf('.');
				if (lastIndexOfDot != -1)
				{
					//this is an explicit interface implementation. if we don't want
					//to document them, get out of here quick...
					if (!this.rep.DocumentExplicitInterfaceImplementations) return;

					interfaceName = name.Substring(0, lastIndexOfDot);
					lastIndexOfDot = interfaceName.LastIndexOf('.');
					if (lastIndexOfDot != -1)
						name = name.Substring(lastIndexOfDot + 1);

					//check if we want to document this interface.
					ImplementsInfo implements = implementations[method.ToString()];
					if (implements == null) return;
				}

				writer.WriteStartElement("method");
				writer.WriteAttributeString("name", name);
				writer.WriteAttributeString("id", memberName);
				writer.WriteAttributeString("access", GetMethodAccessValue(method));
				writer.WriteAttributeString("contract", GetMethodContractValue(method));
				Type t = method.ReturnType;
				writer.WriteAttributeString("returnType", MemberID.GetTypeName(t));
				writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());

				if (inherited)
				{
					writer.WriteAttributeString("declaringType", MemberID.GetDeclaringTypeName(method));
				}

				if (overload > 0)
				{
					writer.WriteAttributeString("overload", overload.ToString());
				}

				if (!IsMemberSafe(method))
					writer.WriteAttributeString("unsafe", "true");

				if (hiding)
				{
					writer.WriteAttributeString("hiding", "true");
				}

				if (interfaceName != null)
				{
					writer.WriteAttributeString("interface", interfaceName);
				}

				if (inherited)
				{
					WriteInheritedDocumentation(writer, memberName, method.DeclaringType);
				}
				else
				{
					WriteMethodDocumentation(writer, memberName, method, true);
				}

				WriteCustomAttributes(writer, method);

				foreach (ParameterInfo parameter in method.GetParameters())
				{
					WriteParameter(writer, MemberID.GetMemberID(method), parameter);
				}

				if (implementations != null)
				{
					ImplementsInfo implements = implementations[method.ToString()];
					if (implements != null)
					{
						writer.WriteStartElement("implements");
						writer.WriteAttributeString("name", implements.InterfaceMethod.Name);
						writer.WriteAttributeString("id", MemberID.GetMemberID((MethodBase)implements.InterfaceMethod));
						writer.WriteAttributeString("interface", MemberDisplayName.GetMemberDisplayName(implements.InterfaceType));
						writer.WriteAttributeString("interfaceId", MemberID.GetMemberID(implements.InterfaceType));
						writer.WriteAttributeString("declaringType", implements.InterfaceType.FullName.Replace('+', '.'));
						writer.WriteEndElement();
					}
				}

				writer.WriteEndElement();
			}
		}
        public object GetRealObject(StreamingContext context)
        {
            switch (_memberType)
            {
            case MemberTypes.Constructor:
                ConstructorInfo [] ctors;

                ctors = _reflectedType.GetConstructors(DefaultBinding);
                for (int i = 0; i < ctors.Length; i++)
                {
                    if (ctors[i].ToString().Equals(_memberSignature))
                    {
                        return(ctors[i]);
                    }
                }

                throw new SerializationException(String.Format("Could not find constructor '{0}' in type '{1}'", _memberSignature, _reflectedType));

            case MemberTypes.Method:
                MethodInfo [] methods;

                methods = _reflectedType.GetMethods(DefaultBinding);
                for (int i = 0; i < methods.Length; i++)
                {
                    if ((methods[i]).ToString().Equals(_memberSignature))
                    {
                        return(methods[i]);
                    }
                    else if (_genericArguments != null &&
                             methods[i].IsGenericMethod &&
                             methods[i].GetGenericArguments().Length == _genericArguments.Length)
                    {
                        MethodInfo mi = methods[i].MakeGenericMethod(_genericArguments);

                        if (mi.ToString() == _memberSignature)
                        {
                            return(mi);
                        }
                    }
                }

                throw new SerializationException(String.Format("Could not find method '{0}' in type '{1}'", _memberSignature, _reflectedType));

            case MemberTypes.Field:
                FieldInfo fi = _reflectedType.GetField(_memberName, DefaultBinding);

                if (fi != null)
                {
                    return(fi);
                }

                throw new SerializationException(String.Format("Could not find field '{0}' in type '{1}'", _memberName, _reflectedType));

            case MemberTypes.Property:
                PropertyInfo pi = _reflectedType.GetProperty(_memberName, DefaultBinding);

                if (pi != null)
                {
                    return(pi);
                }

                throw new SerializationException(String.Format("Could not find property '{0}' in type '{1}'", _memberName, _reflectedType));

            case MemberTypes.Event:
                EventInfo ei = _reflectedType.GetEvent(_memberName, DefaultBinding);

                if (ei != null)
                {
                    return(ei);
                }

                throw new SerializationException(String.Format("Could not find event '{0}' in type '{1}'", _memberName, _reflectedType));

            default:
                throw new SerializationException(String.Format("Unhandled MemberType {0}", _memberType));
            }
        }
Esempio n. 42
0
        public virtual object GetRealObject(StreamingContext context)
        {
            if (this.m_memberName == null || this.m_reflectedType == (RuntimeType)null || this.m_memberType == (MemberTypes)0)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
            }
            BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.OptionalParamBinding;

            switch (this.m_memberType)
            {
            case MemberTypes.Constructor:
                if (this.m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_NullSignature"));
                }
                ConstructorInfo[] constructorInfoArray = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Constructor, bindingAttr) as ConstructorInfo[];
                if (constructorInfoArray.Length == 1)
                {
                    return((object)constructorInfoArray[0]);
                }
                if (constructorInfoArray.Length > 1)
                {
                    for (int index = 0; index < constructorInfoArray.Length; ++index)
                    {
                        if (this.m_signature2 != null)
                        {
                            if (((RuntimeConstructorInfo)constructorInfoArray[index]).SerializationToString().Equals(this.m_signature2))
                            {
                                return((object)constructorInfoArray[index]);
                            }
                        }
                        else if (constructorInfoArray[index].ToString().Equals(this.m_signature))
                        {
                            return((object)constructorInfoArray[index]);
                        }
                    }
                }
                throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", (object)this.m_memberName));

            case MemberTypes.Event:
                EventInfo[] eventInfoArray = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Event, bindingAttr) as EventInfo[];
                if (eventInfoArray.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", (object)this.m_memberName));
                }
                return((object)eventInfoArray[0]);

            case MemberTypes.Field:
                FieldInfo[] fieldInfoArray = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Field, bindingAttr) as FieldInfo[];
                if (fieldInfoArray.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", (object)this.m_memberName));
                }
                return((object)fieldInfoArray[0]);

            case MemberTypes.Method:
                MethodInfo methodInfo1 = (MethodInfo)null;
                if (this.m_signature == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_NullSignature"));
                }
                Type[]       typeArray       = this.m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
                MethodInfo[] methodInfoArray = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Method, bindingAttr) as MethodInfo[];
                if (methodInfoArray.Length == 1)
                {
                    methodInfo1 = methodInfoArray[0];
                }
                else if (methodInfoArray.Length > 1)
                {
                    for (int index = 0; index < methodInfoArray.Length; ++index)
                    {
                        if (this.m_signature2 != null)
                        {
                            if (((RuntimeMethodInfo)methodInfoArray[index]).SerializationToString().Equals(this.m_signature2))
                            {
                                methodInfo1 = methodInfoArray[index];
                                break;
                            }
                        }
                        else if (methodInfoArray[index].ToString().Equals(this.m_signature))
                        {
                            methodInfo1 = methodInfoArray[index];
                            break;
                        }
                        if (typeArray != null && methodInfoArray[index].IsGenericMethod && methodInfoArray[index].GetGenericArguments().Length == typeArray.Length)
                        {
                            MethodInfo methodInfo2 = methodInfoArray[index].MakeGenericMethod(typeArray);
                            if (this.m_signature2 != null)
                            {
                                if (((RuntimeMethodInfo)methodInfo2).SerializationToString().Equals(this.m_signature2))
                                {
                                    methodInfo1 = methodInfo2;
                                    break;
                                }
                            }
                            else if (methodInfo2.ToString().Equals(this.m_signature))
                            {
                                methodInfo1 = methodInfo2;
                                break;
                            }
                        }
                    }
                }
                if (methodInfo1 == (MethodInfo)null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", (object)this.m_memberName));
                }
                if (!methodInfo1.IsGenericMethodDefinition)
                {
                    return((object)methodInfo1);
                }
                if (typeArray == null)
                {
                    return((object)methodInfo1);
                }
                if (typeArray[0] == (Type)null)
                {
                    return((object)null);
                }
                return((object)methodInfo1.MakeGenericMethod(typeArray));

            case MemberTypes.Property:
                PropertyInfo[] propertyInfoArray = this.m_reflectedType.GetMember(this.m_memberName, MemberTypes.Property, bindingAttr) as PropertyInfo[];
                if (propertyInfoArray.Length == 0)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", (object)this.m_memberName));
                }
                if (propertyInfoArray.Length == 1)
                {
                    return((object)propertyInfoArray[0]);
                }
                if (propertyInfoArray.Length > 1)
                {
                    for (int index = 0; index < propertyInfoArray.Length; ++index)
                    {
                        if (this.m_signature2 != null)
                        {
                            if (((RuntimePropertyInfo)propertyInfoArray[index]).SerializationToString().Equals(this.m_signature2))
                            {
                                return((object)propertyInfoArray[index]);
                            }
                        }
                        else if (propertyInfoArray[index].ToString().Equals(this.m_signature))
                        {
                            return((object)propertyInfoArray[index]);
                        }
                    }
                }
                throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", (object)this.m_memberName));

            default:
                throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
            }
        }
Esempio n. 43
0
 void ProcessMethod(System.Reflection.MethodInfo methodInfo)
 {
     Debug.WriteLine("Add method " + methodInfo.ToString());
 }