Discovers the attributes of a method and provides access to method metadata.
Inheritance: MethodBase
Ejemplo n.º 1
5
 /// <summary>
 /// Создает на основе типа фильтр
 /// </summary>
 /// <param name="lib"></param>
 /// <param name="type"></param>
 public Filter(string lib, Type type)
 {
     libname = lib;
     if (type.BaseType == typeof(AbstractFilter))
     {
         Exception fullex = new Exception("");
         ConstructorInfo ci = type.GetConstructor(System.Type.EmptyTypes);
         filter = ci.Invoke(null);
         PropertyInfo everyprop;
         everyprop = type.GetProperty("Name");
         name = (string)everyprop.GetValue(filter, null);
         everyprop = type.GetProperty("Author");
         author = (string)everyprop.GetValue(filter, null);
         everyprop = type.GetProperty("Ver");
         version = (Version)everyprop.GetValue(filter, null);
         help = type.GetMethod("Help");
         MethodInfo[] methods = type.GetMethods();
         filtrations = new List<Filtration>();
         foreach (MethodInfo mi in methods)
             if (mi.Name == "Filter")
             {
                 try
                 {
                     filtrations.Add(new Filtration(mi));
                 }
                 catch (TypeLoadException)
                 {
                     //Не добавляем фильтрацию.
                 }
             }
         if (filtrations == null) throw new TypeIncorrectException("Класс " + name + " не содержит ни одной фильтрации");
     }
     else
         throw new TypeLoadException("Класс " + type.Name + " не наследует AbstractFilter");
 }
Ejemplo n.º 2
1
 internal UnaryExpression(ExpressionType nodeType, Expression expression, Type type, MethodInfo method)
 {
     _operand = expression;
     _method = method;
     _nodeType = nodeType;
     _type = type;
 }
Ejemplo n.º 3
1
        internal ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethods) {
            if (asyncMethodInfo == null) {
                throw new ArgumentNullException("asyncMethodInfo");
            }
            if (completedMethodInfo == null) {
                throw new ArgumentNullException("completedMethodInfo");
            }
            if (String.IsNullOrEmpty(actionName)) {
                throw Error.ParameterCannotBeNullOrEmpty("actionName");
            }
            if (controllerDescriptor == null) {
                throw new ArgumentNullException("controllerDescriptor");
            }

            if (validateMethods) {
                string asyncFailedMessage = VerifyActionMethodIsCallable(asyncMethodInfo);
                if (asyncFailedMessage != null) {
                    throw new ArgumentException(asyncFailedMessage, "asyncMethodInfo");
                }

                string completedFailedMessage = VerifyActionMethodIsCallable(completedMethodInfo);
                if (completedFailedMessage != null) {
                    throw new ArgumentException(completedFailedMessage, "completedMethodInfo");
                }
            }

            AsyncMethodInfo = asyncMethodInfo;
            CompletedMethodInfo = completedMethodInfo;
            _actionName = actionName;
            _controllerDescriptor = controllerDescriptor;
            _uniqueId = new Lazy<string>(CreateUniqueId);
        }
 /// <summary>
 /// Redirects all calls from method 'from' to method 'to'.
 /// </summary>
 /// <param name="from"></param>
 /// <param name="to"></param>
 public static RedirectCallsState RedirectCalls(MethodInfo from, MethodInfo to)
 {
     // GetFunctionPointer enforces compilation of the method.
     var fptr1 = from.MethodHandle.GetFunctionPointer();
     var fptr2 = to.MethodHandle.GetFunctionPointer();
     return PatchJumpTo(fptr1, fptr2);
 }
        public static SqlCommand GenerateCommand(SqlConnection Connection, MethodInfo Method, object[] Values, CommandType SQLCommandType, string SQLCommandText)
        {
            if (Method == null)
            {
                Method = (MethodInfo)new StackTrace().GetFrame(1).GetMethod();
            }

            SqlCommand command = new SqlCommand();
            command.Connection = Connection;
            command.CommandType = SQLCommandType;

            if (SQLCommandText.Length == 0)
            {
                command.CommandText = Method.Name;
            }
            else
            {
                command.CommandText = SQLCommandText;
            }

            if (command.CommandType == CommandType.StoredProcedure)
            {
                GenerateCommandParameters(command, Method, Values);

                command.Parameters.Add(ReturnValueParameterName, SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
            }

            return command;
        }
        /// <summary>
        /// Verifies that `x.Equals(y)` 3 times on an instance of the type returns same
        /// value, if the supplied method is an override of the 
        /// <see cref="object.Equals(object)"/>.
        /// </summary>
        /// <param name="methodInfo">The method to verify</param>
        public override void Verify(MethodInfo methodInfo)
        {
            if (methodInfo == null)
                throw new ArgumentNullException("methodInfo");

            if (methodInfo.ReflectedType == null ||
                !methodInfo.IsObjectEqualsOverrideMethod())
            {
                // The method is not an override of the Object.Equals(object) method
                return;
            }

            var instance = this.builder.CreateAnonymous(methodInfo.ReflectedType);
            var other = this.builder.CreateAnonymous(methodInfo.ReflectedType);

            var results = Enumerable.Range(1, 3)
                .Select(i => instance.Equals(other))
                .ToArray();

            if (results.Any(result => result != results[0]))
            {
                throw new EqualsOverrideException(string.Format(CultureInfo.CurrentCulture,
                    "The type '{0}' overrides the object.Equals(object) method incorrectly, " +
                    "calling x.Equals(y) multiple times should return the same value.",
                    methodInfo.ReflectedType.FullName));
            }
        }
Ejemplo n.º 7
1
 private static BaseInvokableCall GetObjectCall(UnityEngine.Object target, MethodInfo method, ArgumentCache arguments)
 {
     System.Type type = typeof(UnityEngine.Object);
     if (!string.IsNullOrEmpty(arguments.unityObjectArgumentAssemblyTypeName))
     {
         System.Type type1 = System.Type.GetType(arguments.unityObjectArgumentAssemblyTypeName, false);
         if (type1 != null)
         {
             type = type1;
         }
         else
         {
             type = typeof(UnityEngine.Object);
         }
     }
     System.Type type2 = typeof(CachedInvokableCall<>);
     System.Type[] typeArguments = new System.Type[] { type };
     System.Type[] types = new System.Type[] { typeof(UnityEngine.Object), typeof(MethodInfo), type };
     ConstructorInfo constructor = type2.MakeGenericType(typeArguments).GetConstructor(types);
     UnityEngine.Object unityObjectArgument = arguments.unityObjectArgument;
     if ((unityObjectArgument != null) && !type.IsAssignableFrom(unityObjectArgument.GetType()))
     {
         unityObjectArgument = null;
     }
     object[] parameters = new object[] { target, method, unityObjectArgument };
     return (constructor.Invoke(parameters) as BaseInvokableCall);
 }
Ejemplo n.º 8
1
 protected IList<IInterceptor> GetMethodInterceptors(MethodInfo Method)
 {
     if (this.MethodInterceptorRegistrations.ContainsKey(Method))
         return this.MethodInterceptorRegistrations[Method];
     else
         return null;
 }
Ejemplo n.º 9
1
		public MethodTokenExpression(MethodInfo method)
		{
			this.method = method;
#if !MONO
			declaringType = method.DeclaringType;
#endif
		}
Ejemplo n.º 10
1
        public static MethodBuilder DefineMethod(this TypeBuilder typeBuilder, MethodInfo method, MethodAttributes? attributes = null, ParameterInfo[] parameters = null)
        {
            Type[] parametersTypes = null;
            MethodBuilder methodBuilder = null;

            parameters = parameters ?? method.GetParameters();
            parametersTypes = parameters.ToArray(parameter => parameter.ParameterType);
            attributes = attributes ?? method.Attributes & ~MethodAttributes.Abstract;
            methodBuilder = typeBuilder.DefineMethod(method.Name, attributes.Value, method.ReturnType, parametersTypes);

            parameters.ForEach(1, (parameter, i) => {
                var parameterBuilder = methodBuilder.DefineParameter(i, parameter.Attributes, parameter.Name);

                if (parameter.IsDefined<ParamArrayAttribute>()) {
                    parameterBuilder.SetCustomAttribute<ParamArrayAttribute>();
                }
                else if (parameter.IsOut) {
                    parameterBuilder.SetCustomAttribute<OutAttribute>();
                }
                else if (parameter.IsOptional) {
                    parameterBuilder.SetCustomAttribute<OptionalAttribute>()
                                    .SetConstant(parameter.DefaultValue);
                }
            });

            return methodBuilder;
        }
Ejemplo n.º 11
1
 protected Delegate CreateMethodDelegate(MethodInfo method)
 {
     if (method.ReturnType == typeof (void))
         return CreateActionDelegate(method);
     else
         return CreateFuncDelegate(method);
 }
Ejemplo n.º 12
1
 internal ProjectionBuilder()
 {
     if (miGetValue == null) {
         miGetValue = typeof(DocumentProjection).GetMethod("GetValue");
         miExecuteSubQuery = typeof(DocumentProjection).GetMethod("ExecuteSubQuery");
     }
 }
 public SqlCallProcedureInfo(MethodInfo method, ISerializationTypeInfoProvider typeInfoProvider)
 {
     if (method == null) {
         throw new ArgumentNullException("method");
     }
     if (typeInfoProvider == null) {
         throw new ArgumentNullException("typeInfoProvider");
     }
     SqlProcAttribute procedure = GetSqlProcAttribute(method);
     schemaName = procedure.SchemaName;
     name = procedure.Name;
     timeout = procedure.Timeout;
     deserializeReturnNullOnEmptyReader = procedure.DeserializeReturnNullOnEmptyReader;
     deserializeRowLimit = procedure.DeserializeRowLimit;
     deserializeCallConstructor = procedure.DeserializeCallConstructor;
     SortedDictionary<int, SqlCallParameterInfo> sortedParams = new SortedDictionary<int, SqlCallParameterInfo>();
     outArgCount = 0;
     foreach (ParameterInfo parameterInfo in method.GetParameters()) {
         if ((parameterInfo.GetCustomAttributes(typeof(SqlNameTableAttribute), true).Length > 0) || (typeof(XmlNameTable).IsAssignableFrom(parameterInfo.ParameterType))) {
             if (xmlNameTableParameter == null) {
                 xmlNameTableParameter = parameterInfo;
             }
         } else {
             SqlCallParameterInfo sqlParameterInfo = new SqlCallParameterInfo(parameterInfo, typeInfoProvider, ref outArgCount);
             sortedParams.Add(parameterInfo.Position, sqlParameterInfo);
         }
     }
     parameters = sortedParams.Select(p => p.Value).ToArray();
     returnTypeInfo = typeInfoProvider.GetSerializationTypeInfo(method.ReturnType);
     if ((procedure.UseReturnValue != SqlReturnValue.Auto) || (method.ReturnType != typeof(void))) {
         useReturnValue = (procedure.UseReturnValue == SqlReturnValue.ReturnValue) || ((procedure.UseReturnValue == SqlReturnValue.Auto) && (typeInfoProvider.TypeMappingProvider.GetMapping(method.ReturnType).DbType == SqlDbType.Int));
     }
 }
Ejemplo n.º 14
1
        private ActionMethodInfo BuildActionMethodInfo(ActionStepAttribute actionStep, MethodInfo method)
        {
            if (actionStep.ActionMatch == null)
                actionStep.BuildActionMatchFromMethodInfo(method);

            return new ActionMethodInfo(actionStep.ActionMatch, null, method, actionStep.Type);
        }
        private static MethodInfo GetInterceptedMethod(MethodInfo interceptionMethod)
        {
            var parameterTypes = from parameter in interceptionMethod.GetParameters()
                                 select parameter.ParameterType;

            return interceptionMethod.DeclaringType.GetMethod(interceptionMethod.GetMethodNameWithoutTilde(), parameterTypes.ToArray());
        }
 /// <summary>
 /// Construct from a MethodInfo
 /// </summary>
 /// <param name="method"></param>
 public ParameterizedMethodSuite(MethodInfo method)
     : base(method.ReflectedType.FullName, method.Name)
 {
     this.maintainTestOrder = true;
     this.isTheory = Reflect.HasAttribute(method, NUnitFramework.TheoryAttribute, true);
     this.method = method;
 }
Ejemplo n.º 17
1
 /// <summary>
 /// Creates a new <see cref="MethodInvocationValidator"/> instance.
 /// </summary>
 /// <param name="method">Method to be validated</param>
 /// <param name="parameterValues">List of arguments those are used to call the <paramref name="method"/>.</param>
 public MethodInvocationValidator(MethodInfo method, object[] parameterValues)
 {
     _method = method;
     _parameterValues = parameterValues;
     _parameters = method.GetParameters();
     _validationErrors = new List<ValidationResult>();
 }
Ejemplo n.º 18
1
 public static void CallMethod(this ILGenerator generator, MethodInfo methodInfo)
 {
     if (methodInfo.IsFinal || !methodInfo.IsVirtual)
         generator.Emit(OpCodes.Call, methodInfo);
     else
         generator.Emit(OpCodes.Callvirt, methodInfo);
 }
Ejemplo n.º 19
1
 private static bool IsSameMethod(MethodInfo first, MethodInfo second)
 {
     return first.DeclaringType == second.DeclaringType
            && first.MetadataToken == second.MetadataToken
            && first.Module == second.Module
            && first.GetGenericArguments().SequenceEqual(second.GetGenericArguments());
 }
 private static void CheckMethod(MethodInfo mainMethod, MethodInfo observableMethod)
 {
     Assert.Equal(mainMethod.MemberType, observableMethod.MemberType);
     Assert.Equal(mainMethod.Name, observableMethod.Name);
     CheckParameters(mainMethod, observableMethod);
     CheckReturnValue(mainMethod, observableMethod);
 }
Ejemplo n.º 21
1
        private static bool HasSameBaseMethod(MethodInfo first, MethodInfo second)
        {
            var baseOfFirst = GetBaseDefinition(first);
            var baseOfSecond = GetBaseDefinition(second);

            return IsSameMethod(baseOfFirst, baseOfSecond);
        }
Ejemplo n.º 22
1
        private string GetTypeJavaScript(MethodInfo[] ajaxMethodInfos)
        {
            StringBuilder javascriptBuilder = new StringBuilder();
            javascriptBuilder.Append("// author: lcomplete,\n\n");
            javascriptBuilder.AppendFormat("if(typeof {0} ==\"undefined\") {0}={{}};\n", _type.Namespace);
            javascriptBuilder.AppendFormat("if(typeof {0}_class ==\"undefined\") {0}_class={{}};\n", _type.FullName);
            javascriptBuilder.AppendFormat("{0}_class=function(){{}};\n", _type.FullName);
            javascriptBuilder.AppendFormat(
                "Object.extend({0}_class.prototype,Object.extend(new Iridescent.AjaxClass(), {{\n", _type.FullName);
            foreach (var ajaxMethodInfo in ajaxMethodInfos)
            {
                var parameters = ajaxMethodInfo.GetParameters();
                var joinParameters = (from parameterInfo in parameters
                                      select parameterInfo.Name).ToArray();
                javascriptBuilder.AppendFormat("\t{0}:function({1}) {{\n", ajaxMethodInfo.Name,
                                               string.Join(",", joinParameters));
                javascriptBuilder.AppendFormat("\t\treturn this.invoke(\"{0}\",{{{1}}},this.{0}.getArguments().slice({2}));\n",
                    ajaxMethodInfo.Name,
                    string.Join(",",(from joinParameter in joinParameters
                         select "\""+joinParameter+"\":"+joinParameter).ToArray()),
                     parameters.Length);
                javascriptBuilder.Append("\t},\n");
            }
            javascriptBuilder.AppendFormat(
                "\turl:\"/Iridescent/Ajax/{0}.ashx\"\n}}));\n", _type.FullName + "," + _type.Assembly.GetName().Name);
            javascriptBuilder.AppendFormat("{0}=new {0}_class();", _type.FullName);

            return javascriptBuilder.ToString();
        }
Ejemplo n.º 23
1
 public bool AttachView(EditorWindow parent, ScriptableObject webView, bool initialize = false)
 {
     this.parentWin = parent;
     this.internalWebView = webView;
     if (this.internalWebView != null)
     {
         this.hostView = Tools.GetReflectionField<object>(parent, "m_Parent");
         this.dockedGetterMethod = this.parentWin.GetType().GetProperty("docked", Tools.FullBinding).GetGetMethod(true);
         if (this.hostView != null && dockedGetterMethod != null)
         {
             if (initialize)
             {
                 Rect initViewRect = new Rect(0, 20, this.parentWin.position.width, this.parentWin.position.height - ((this.IsDocked()) ? 20 : 40));
                 this.InitWebView(this.hostView, (int)initViewRect.x, (int)initViewRect.y, (int)initViewRect.width, (int)initViewRect.height, false);
                 this.SetHideFlags(HideFlags.HideAndDontSave);
                 this.AllowRightClickMenu(true);
             }
         }
         else
         {
             throw new Exception("Failed to get parent window or docked property");
         }
     }
     return (this.internalWebView != null);
 }
 private void checkTransactionProperties( ITransactionAttributeSource tas, MethodInfo method, TransactionPropagation transactionPropagation )
 {
     ITransactionAttribute ta = tas.ReturnTransactionAttribute( method, null );
     Assert.IsTrue( ta != null );
     Assert.IsTrue( ta.TransactionIsolationLevel == IsolationLevel.Unspecified );
     Assert.IsTrue( ta.PropagationBehavior == transactionPropagation);
 }
Ejemplo n.º 25
1
 public WebBrowser()
 {
     this.hostView = null;
     this.parentWin = null;
     this.internalWebView = null;
     this.dockedGetterMethod = null;
 }
Ejemplo n.º 26
1
 public TestUnit(MethodInfo methodInfo, string description = "")
     : this()
 {
     this.MethodInfo = methodInfo.Name;
     this.Name = methodInfo.Name;
     this.Description = description;
 }
        private void AddParameterDescriptionsToModel(ActionApiDescriptionModel actionModel, MethodInfo method, ApiDescription apiDescription)
        {
            if (!apiDescription.ParameterDescriptions.Any())
            {
                return;
            }

            var matchedMethodParamNames = ArrayMatcher.Match(
                apiDescription.ParameterDescriptions.Select(p => p.Name).ToArray(),
                method.GetParameters().Select(GetMethodParamName).ToArray()
            );

            for (var i = 0; i < apiDescription.ParameterDescriptions.Count; i++)
            {
                var parameterDescription = apiDescription.ParameterDescriptions[i];
                var matchedMethodParamName = matchedMethodParamNames.Length > i
                                                 ? matchedMethodParamNames[i]
                                                 : parameterDescription.Name;

                actionModel.AddParameter(new ParameterApiDescriptionModel(
                        parameterDescription.Name,
                        matchedMethodParamName,
                        parameterDescription.Type,
                        parameterDescription.RouteInfo?.IsOptional ?? false,
                        parameterDescription.RouteInfo?.DefaultValue,
                        parameterDescription.RouteInfo?.Constraints?.Select(c => c.GetType().Name).ToArray(),
                        parameterDescription.Source.Id
                    )
                );
            }
        }
 /// <summary>
 /// Initializes dispatcher-stack attaching method container work item.
 /// </summary>
 /// <param name="testHarness">Test harness.</param>
 /// <param name="instance">Test instance.</param>
 /// <param name="method">Method reflection object.</param>
 /// <param name="testMethod">Test method metadata.</param>
 /// <param name="granularity">Granularity of test.</param>
 public UnitTestMethodContainer(UnitTestHarness testHarness, object instance, MethodInfo method, ITestMethod testMethod, TestGranularity granularity)
     : base(instance, method, testMethod)
 {
     _granularity = granularity;
     _harness = testHarness as UnitTestHarness;
     _testMethod = testMethod;
 }
        private static void InitializeTypes(Action<string> errorHandler)
        {
            if (_typesInitialized)
            {
                return;
            }

            try
            {
                Assembly extensionManagerAssembly = AppDomain.CurrentDomain.GetAssemblies()
                    .First(a => a.FullName.StartsWith("Microsoft.VisualStudio.ExtensionManager,"));
                _sVsExtensionManagerType =
                    extensionManagerAssembly.GetType("Microsoft.VisualStudio.ExtensionManager.SVsExtensionManager");
                _iVsExtensionManagerType =
                    extensionManagerAssembly.GetType("Microsoft.VisualStudio.ExtensionManager.IVsExtensionManager");
                _iInstalledExtensionType =
                    extensionManagerAssembly.GetType("Microsoft.VisualStudio.ExtensionManager.IInstalledExtension");
                _tryGetInstalledExtensionMethod = _iVsExtensionManagerType.GetMethod("TryGetInstalledExtension",
                    new[] { typeof(string), _iInstalledExtensionType.MakeByRefType() });
                _installPathProperty = _iInstalledExtensionType.GetProperty("InstallPath", typeof(string));
                if (_installPathProperty == null || _tryGetInstalledExtensionMethod == null ||
                    _sVsExtensionManagerType == null)
                {
                    throw new Exception();
                }

                _typesInitialized = true;
            }
            catch
            {
                // if any of the types or methods cannot be loaded throw an error. this indicates that some API in
                // Microsoft.VisualStudio.ExtensionManager got changed.
                errorHandler(VsResources.PreinstalledPackages_ExtensionManagerError);
            }
        }
        private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, IList<string> arguments)
        {
            var invokeParameters = new List<object>();
            var args = new List<string>(arguments);
            var methodParameters = methodInfo.GetParameters();
            bool methodHasParams = false;

            if (methodParameters.Length == 0) {
                if (args.Count == 0)
                    return invokeParameters.ToArray();
                return null;
            }

            if (methodParameters[methodParameters.Length - 1].ParameterType.IsAssignableFrom(typeof(string[]))) {
                methodHasParams = true;
            }

            if (!methodHasParams && args.Count != methodParameters.Length) return null;
            if (methodHasParams && (methodParameters.Length - args.Count >= 2)) return null;

            for (int i = 0; i < args.Count; i++) {
                if (methodParameters[i].ParameterType.IsAssignableFrom(typeof(string[]))) {
                    invokeParameters.Add(args.GetRange(i, args.Count - i).ToArray());
                    break;
                }
                invokeParameters.Add(Convert.ChangeType(arguments[i], methodParameters[i].ParameterType));
            }

            if (methodHasParams && (methodParameters.Length - args.Count == 1)) invokeParameters.Add(new string[] { });

            return invokeParameters.ToArray();
        }
Ejemplo n.º 31
0
            /// <summary>
            /// Initialize this provider to be able to gets the intialization value.
            /// </summary>
            private void Initialize()
            {
                if (!_initialized)
                {
                    _initialized = true;
#if ACTIVEX_COMPONENTSERVER
                    if (_elementType.BaseType.Name == "ComponentClassHelper" ||
                        _elementType.BaseType.Name == "ComponentSingleUseClassHelper" ||
                        _elementType.BaseType.Name == "GlbComponentSingleUseClassHelper")
                    {
                        _initializeMethod = InitialValueMethod.CsFactory;
                    }
                    else
#endif
                    if (_elementType == typeof(Object))
                    {
                        _initializeMethod = InitialValueMethod.Null;
                    }
                    else if (!(_elementType == typeof(String)))
                    {
                        //try for a constructor method
                        if (_constructorParams == null)
                        {
                            _constructorParams = new object[] { }
                        }
                        ;
#if PORTABLE
                        Type[] typeArray = new Type[_constructorParams.Length];
                        for (int i = 0; i < _constructorParams.Length; i++)
                        {
                            typeArray[i] = _constructorParams[i].GetType();
                        }
#else
                        Type[] typeArray = Type.GetTypeArray(_constructorParams);
#endif



                        if ((_constructor = _elementType.GetConstructor(typeArray)) == null)
                        {
                            if (_elementType.IsValueType && (_constructorParams == null || _constructorParams.Length == 0))
                            {
                                _initializeMethod = (_method = _elementType.GetMethod("CreateInstance")) == null ? InitialValueMethod.ValueType : InitialValueMethod.CreateInstanceValueType;
                            }
                        }
                        else
                        {
                            _initializeMethod = InitialValueMethod.Constructor;
                        }
                    }
                }
            }
        }
Ejemplo n.º 32
0
        public static string ToString(this Object obj, string format)
        {
            Type t = obj.GetType();

            Reflection.MethodInfo tostringMethod = t.GetMethod("ToString", Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance, null, new Type[] { typeof(string) }, null);
            if (tostringMethod == null)
            {
                return(obj.ToString());
            }
            else
            {
                //Reflection.ParameterInfo[] paramsInfo = tostringMethod.GetParameters();//得到指定方法的参数列表
                return(tostringMethod.Invoke(obj, new object[] { format }).ToString());
            }
        }
Ejemplo n.º 33
0
        static StackObject *set_Item_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.MethodInfo @value = (System.Reflection.MethodInfo) typeof(System.Reflection.MethodInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Int32 @key = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Collections.Generic.Dictionary <System.Int32, System.Reflection.MethodInfo> instance_of_this_method = (System.Collections.Generic.Dictionary <System.Int32, System.Reflection.MethodInfo>) typeof(System.Collections.Generic.Dictionary <System.Int32, System.Reflection.MethodInfo>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method[key] = value;

            return(__ret);
        }
Ejemplo n.º 34
0
        protected virtual async Task Interceptor_Evict_With_Task_Method_Should_Succeed()
        {
            System.Reflection.MethodInfo method = typeof(AspectCoreExampleService).GetMethod("EvictTest");

            var key = _keyGenerator.GetCacheKey(method, null, "CastleExample");

            var cachedValue = Guid.NewGuid().ToString();

            _cachingProvider.Set(key, cachedValue, TimeSpan.FromSeconds(30));

            var value = _cachingProvider.Get <string>(key);

            Assert.True(value.HasValue);
            Assert.Equal(cachedValue, value.Value);

            await _service.EvictTestAsync();

            var after = _cachingProvider.Get <string>(key);

            Assert.False(after.HasValue);
        }
Ejemplo n.º 35
0
 /// <summary>
 /// This is called from the compile/run appdomain to convert objects within an expression block to a string
 /// </summary>
 public string ToStringWithCulture(object objectToConvert)
 {
     if ((objectToConvert == null))
     {
         throw new global::System.ArgumentNullException("objectToConvert");
     }
     System.Type t = objectToConvert.GetType();
     System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
         typeof(System.IFormatProvider)
     });
     if ((method == null))
     {
         return(objectToConvert.ToString());
     }
     else
     {
         return((string)(method.Invoke(objectToConvert, new object[] {
             this.formatProviderField
         })));
     }
 }
Ejemplo n.º 36
0
 public static bool CallFunction(object p_instance, System.Type p_type, string p_functionName, params object[] p_param)
 {
     if (p_instance != null)
     {
         System.Type v_type = p_type;
         if (v_type != null)
         {
             try
             {
                 System.Reflection.MethodInfo v_info = v_type.GetMethod(p_functionName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                 if (v_info != null)
                 {
                     v_info.Invoke(p_instance, p_param);
                     return(true);
                 }
             }
             catch { }
         }
     }
     return(false);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Returns information about the specified
        /// method, even if the parameter types are
        /// generic and are located in an abstract
        /// generic base class.
        /// </summary>
        /// <param name="objectType">
        /// Type of object containing method.
        /// </param>
        /// <param name="method">
        /// Name of the method.
        /// </param>
        /// <param name="types">
        /// Parameter types to pass to method.
        /// </param>
        public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, Type[] types)
        {
            System.Reflection.MethodInfo info = null;
            do
            {
                // find for a strongly typed match
                info = objectType.GetMethod(method, oneLevelFlags, null, types, null);
                if (info != null)
                {
                    break; // match found
                }

#if NETFX_CORE
                objectType = objectType.BaseType();
#else
                objectType = objectType.BaseType;
#endif
            } while (objectType != null);

            return(info);
        }
Ejemplo n.º 38
0
        public ActionHandler(object controller, System.Reflection.MethodInfo method, HttpApiServer httpApiServer)
        {
            ID             = System.Threading.Interlocked.Increment(ref mIdSeed);
            Remark         = "";
            Parameters     = new List <ParameterBinder>();
            mMethod        = method;
            mMethodHandler = new MethodHandler(mMethod);
            Controller     = controller;
            HttpApiServer  = httpApiServer;
            LoadParameter();
            Filters        = new List <FilterAttribute>();
            Method         = "GET";
            SingleInstance = true;
            ControllerType = Controller.GetType();
            NoConvert      = false;
            var aname = controller.GetType().Assembly.GetName();

            this.AssmblyName = aname.Name;
            this.Version     = aname.Version.ToString();
            Async            = false;
        }
Ejemplo n.º 39
0
        private static T GetStruct <T>(XmlElement etype)
        {
            Type        type = typeof(T);
            XmlNodeList list = etype.SelectNodes("./member");
            T           t    = Activator.CreateInstance <T>();

            foreach (XmlElement e in list)
            {
                XmlElement eName  = (XmlElement)e.SelectSingleNode("./name");
                XmlElement eValue = (XmlElement)e.SelectSingleNode("./value");
                FieldInfo  field  = type.GetField(eName.InnerText);
                Debug.Assert(field != null, "A field was not found", "The field " + eName.InnerText + " was not found in " + type.Name);
                System.Reflection.MethodInfo mi = typeof(XmlRpcClient).GetMethod("GetValue", BindingFlags.Static | BindingFlags.NonPublic);
                Type[] _params = { field.FieldType };
                mi = mi.MakeGenericMethod(_params);
                object[] @params = { eValue.ChildNodes[0] };
                object   value   = mi.Invoke(null, @params);
                field.SetValue(t, value);
            }
            return(t);
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Uses reflection to dynamically invoke a method
        /// if that method is implemented on the target object.
        /// </summary>
        /// <param name="obj">
        /// Object containing method.
        /// </param>
        /// <param name="method">
        /// Name of the method.
        /// </param>
        /// <param name="parameters">
        /// Parameters to pass to method.
        /// </param>
        public static object CallMethodIfImplemented(object obj, string method, params object[] parameters)
        {
#if WINDOWS_PHONE
            System.Reflection.MethodInfo info = GetMethod(obj.GetType(), method, parameters);
            if (info != null)
            {
                return(CallMethod(obj, info, parameters));
            }
            else
            {
                return(null);
            }
#else
            var mh = GetCachedMethod(obj, method, parameters);
            if (mh == null || mh.DynamicMethod == null)
            {
                return(null);
            }
            return(CallMethod(obj, mh, parameters));
#endif
        }
            private static ContextCallableDelegate <TInstance> CreateProcedure(System.Reflection.MethodInfo target)
            {
                var methodCall   = MethodCallExpression(target, out var instParam, out var argsParam);
                var returnLabel  = Expression.Label(typeof(IValue));
                var defaultValue = Expression.Constant(null, typeof(IValue));
                var returnExpr   = Expression.Return(
                    returnLabel,
                    defaultValue,
                    typeof(IValue)
                    );

                var body = Expression.Block(
                    methodCall,
                    returnExpr,
                    Expression.Label(returnLabel, defaultValue)
                    );

                var l = Expression.Lambda <ContextCallableDelegate <TInstance> >(body, instParam, argsParam);

                return(l.Compile());
            }
Ejemplo n.º 42
0
        static MethodDefinition CreateMethod(TypeDefinition type, SR.MethodInfo pattern)
        {
            var module = type.Module;

            var method = new MethodDefinition {
                Name     = "Run",
                IsPublic = true,
                IsStatic = true,
            };

            type.Methods.Add(method);

            method.MethodReturnType.ReturnType = module.ImportReference(pattern.ReturnType);

            foreach (var parameter_pattern in pattern.GetParameters())
            {
                method.Parameters.Add(new ParameterDefinition(module.ImportReference(parameter_pattern.ParameterType)));
            }

            return(method);
        }
Ejemplo n.º 43
0
        static StackObject *op_Equality_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.MethodInfo @right = (System.Reflection.MethodInfo) typeof(System.Reflection.MethodInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Reflection.MethodInfo @left = (System.Reflection.MethodInfo) typeof(System.Reflection.MethodInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);


            var result_of_this_method = left == right;

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method ? 1 : 0;
            return(__ret + 1);
        }
Ejemplo n.º 44
0
        private static void InitializePerTypeRules(AuthorizationRuleManager mgr, Type type)
        {
            if (!mgr.InitializedPerType)
            {
                lock (mgr)
                    if (!mgr.InitializedPerType && !mgr.InitializingPerType)
                    {
                        // Only call AddObjectAuthorizationRules when there are no rules for this type
                        if (RulesExistForType(type))
                        {
                            mgr.InitializedPerType = true;
                            return;
                        }

                        try
                        {
                            mgr.InitializingPerType = true;

                            // invoke method to add auth roles
                            const BindingFlags           flags  = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
                            System.Reflection.MethodInfo method = type.GetMethod("AddObjectAuthorizationRules", flags);
                            if (method != null)
                            {
                                method.Invoke(null, null);
                            }
                            mgr.InitializedPerType = true;
                        }
                        catch (Exception)
                        {
                            // remove all loaded rules for this type
                            CleanupRulesForType(type);
                            throw; // and rethrow the exception
                        }
                        finally
                        {
                            mgr.InitializingPerType = false;
                        }
                    }
            }
        }
Ejemplo n.º 45
0
        public static ReflectFun GetInternalFunction(Type type, string function, bool isStatic, bool isPrivate, bool isInstance, bool baseType, bool all = false)
        {
            System.Reflection.BindingFlags flag = System.Reflection.BindingFlags.Default;
            if (all)
            {
                flag = BindingFlags.NonPublic |
                       BindingFlags.Public |
                       BindingFlags.Instance |
                       BindingFlags.Static;
            }
            else
            {
                if (isStatic)
                {
                    flag |= System.Reflection.BindingFlags.Static;
                }
                if (isPrivate)
                {
                    flag |= System.Reflection.BindingFlags.NonPublic;
                }
                else
                {
                    flag |= System.Reflection.BindingFlags.Public;
                }
                if (isInstance)
                {
                    flag |= System.Reflection.BindingFlags.Instance;
                }
            }

            System.Reflection.MethodInfo mi = baseType ? type.BaseType.GetMethod(function, flag) : type.GetMethod(function, flag);
            if (mi != null)
            {
                return(new ReflectFun()
                {
                    fun = mi
                });
            }
            return(null);
        }
Ejemplo n.º 46
0
        public static object GetQueryForThenBy(object linqQuery, string stringOrder)
        {
            Type myType               = typeof(System.Linq.Queryable);
            Type dataType             = linqQuery.GetType().GetGenericArguments()[0];
            ParameterExpression param = System.Linq.Expressions.Expression.Parameter(dataType, "n");
            var methods               = myType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

            string[] orders = stringOrder.Split(',');
            foreach (string order in orders)
            {
                if (order.Trim().Length == 0)
                {
                    continue;
                }
                bool   desc         = order.Trim().ToLower().Contains(" desc");
                string methodName   = desc ? "ThenByDescending" : "ThenBy";
                string itemProperty = order.Trim().Split(' ')[0];
                if (itemProperty.StartsWith("[") && itemProperty.EndsWith("]"))
                {
                    itemProperty = itemProperty.Substring(1, itemProperty.Length - 2);
                }

                System.Reflection.PropertyInfo     pinfo;
                System.Linq.Expressions.Expression left       = GetPropertyExpression(param, dataType, itemProperty, out pinfo);
                System.Linq.Expressions.Expression expression = System.Linq.Expressions.Expression.Lambda(left, param);


                foreach (System.Reflection.MethodInfo method in methods)
                {
                    if (method.Name != methodName || method.IsGenericMethod == false)
                    {
                        continue;
                    }
                    System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType, pinfo.PropertyType);
                    linqQuery = mmm.Invoke(null, new object[] { linqQuery, expression });
                    break;
                }
            }
            return(linqQuery);
        }
Ejemplo n.º 47
0
        static Action <object> CreateExecute(object target
                                             , System.Reflection.MethodInfo method
                                             , Type parameterType)
        {
            var parameter = Expression.Parameter(typeof(object), "parameter");

            var instance = ConvertTarget(target, method);

            Expression body;

            if (parameterType == typeof(object))
            {
                body = Expression.Call(instance,
                                       method,
                                       parameter
                                       );
            }
            else
            {
                var arg0        = Expression.Variable(typeof(object), "argX");
                var convertCall = Expression.Call(tryConvert,
                                                  Expression.Constant(parameterType),
                                                  parameter,
                                                  Expression.Property(null, currentCulture),
                                                  arg0
                                                  );

                var call = Expression.Call(instance,
                                           method,
                                           Expression.Convert(arg0, parameterType)
                                           );
                body = Expression.Block(new[] { arg0 },
                                        convertCall,
                                        call
                                        );
            }
            return(Expression
                   .Lambda <Action <object> >(body, parameter)
                   .Compile());
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Gets a boolean value that indicates whether the specified value is a method or not.
        /// </summary>
        /// <param name="method">The value that may contain a method name (string) or an OrderedMap.
        /// If the value is an OrderedMap, then it should have to entries: a class instance and a method name.</param>
        /// <param name="callableName">The referenced string value used to return the method name.</param>
        /// <param name="declaringType">The method declaring type. This parameter is used when the first parameter is a string.</param>
        /// <returns>Returns a boolean value that indicates whther the specified value is a method or not.</returns>
        public static bool IsCallable(object method, ref string callableName, System.Type declaringType)
        {
            bool result = false;

            try
            {
                System.Reflection.MethodInfo methodInfo = null;

                if (method is System.String)
                {
                    callableName = method.ToString();
                    methodInfo   = declaringType.GetTypeInfo().GetMethod(method.ToString());
                    if (methodInfo != null)
                    {
                        callableName = methodInfo.Name;
                        result       = true;
                    }
                }
                else if (method is OrderedMap)
                {
                    OrderedMap typeMethod = (OrderedMap)method;
                    callableName = typeMethod.ToString();
                    methodInfo   = typeMethod.GetValueAt(0).GetType().GetTypeInfo().GetMethod(typeMethod.GetValueAt(1).ToString());
                    if (methodInfo != null)
                    {
                        callableName = typeMethod.GetValueAt(0).GetType().Name + ":" + methodInfo.Name;
                        result       = true;
                    }
                }
                else
                {
                    callableName = method.ToString();
                }
            }
            catch
            {
            }

            return(result);
        }
        public void InitializeMenuCommand()
        {
            // Create the package
            IVsPackage package = new VsOnBuildExtensionPackage() as IVsPackage;

            Assert.IsNotNull(package, "The object does not implement IVsPackage");

            // Create a basic service provider
            OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();

            // Site the package
            Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");

            //Verify that the menu command can be found
            CommandID menuCommandID = new CommandID(CleverMonkeys.VSOnBuildExtension.GuidList.guidVSOnBuildExtensionCmdSet, (int)CleverMonkeys.VSOnBuildExtension.PkgCmdIDList.cmdidIISReset);

            System.Reflection.MethodInfo info = typeof(Package).GetMethod("GetService", BindingFlags.Instance | BindingFlags.NonPublic);
            Assert.IsNotNull(info);
            OleMenuCommandService mcs = info.Invoke(package, new object[] { (typeof(IMenuCommandService)) }) as OleMenuCommandService;

            Assert.IsNotNull(mcs.FindCommand(menuCommandID));
        }
Ejemplo n.º 50
0
        public static MethodDefinition Wrap(ReflectionNET.MethodInfo methodInfo)
        {
            var methodName = new MethodName(methodInfo.Name);
            var builder    = new MethodBuilder(methodName);

            var generator = builder.GetGenerator();

            foreach (var local in methodInfo.GetMethodBody().LocalVariables)
            {
                generator.DeclareLocal(local.LocalType);
            }

            var instructions = new ILReader(methodInfo).Instructions;
            var modifyWriter = new StringModifyWriter(generator);

            foreach (var instr in instructions)
            {
                modifyWriter.Write(instr);
            }
            //ILInstructionWriter.WriteIL(instructions, generator);
            return(builder.CreateMethodDefinition());
        }
Ejemplo n.º 51
0
        // The method to call Game Objects methods
        //----------------------------------------
        public void sendMessageToGameObject(GameObject gameObject, string methodName, Dictionary <object, object> data)
        {
            int           size    = data.Count;
            List <object> keyList = new List <object>(data.Keys);

            System.Reflection.MethodInfo info = gameObject.GetComponent("PlayerController").GetType().GetMethod(methodName);
            ParameterInfo[] par = info.GetParameters();


            for (int j = 0; j < par.Length; j++)
            {
                System.Reflection.ParameterInfo par1 = par[j];

                Debug.Log("->>>>>>>>>>>>>>--> parametre Name >>=>>=>>=  " + par1.Name);
                Debug.Log("->>>>>>>>>>>>>>--> parametre Type >>=>>=>>=  " + par1.ParameterType);
            }

            switch (size)
            {
            case 0:
                gameObject.SendMessage(methodName);
                break;

            case 1:
                gameObject.SendMessage(methodName, convertParameter(data[keyList.ElementAt(0)], par[0]));
                break;

            default:
                object[] obj = new object[size + 1];
                int      i   = 0;
                foreach (KeyValuePair <object, object> pair in data)
                {
                    obj[i] = pair.Value;
                    i++;
                }
                gameObject.SendMessage(methodName, obj);
                break;
            }
        }
Ejemplo n.º 52
0
        protected virtual void AddMethod(MethodInfo methodInfo)
        {
            if (methodInfo.ContainsGenericParameters)
            {
                // Currently don't support generic parameters to keep it simple for now
                return;
            }

            MethodData data = new MethodData {
                method = methodInfo, parameters = methodInfo.GetParameters()
            };

            data.NeededParameterCount = data.parameters.Count(p => !p.IsOptional);

            int    i = 0;
            string name;

            do
            {
                name = $"{methodInfo.Name}{(i == 0 ? string.Empty : $"_{i}")}";
                i++;
            } while (Methods.ContainsKey(name));
Ejemplo n.º 53
0
        public void InitializeMenuCommand()
        {
            // Create the package
            IVsPackage package = new DapperFactoryPackage() as IVsPackage;

            Assert.IsNotNull(package, "The object does not implement IVsPackage");

            // Create a basic service provider
            OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();

            // Site the package
            Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");

            //Verify that the menu command can be found
            CommandID menuCommandID = new CommandID(Chambersoft.DapperFactory.GuidList.guidDapperFactoryCmdSet, (int)Chambersoft.DapperFactory.PkgCmdIDList.dfGenerateServiceInterfaces);

            System.Reflection.MethodInfo info = typeof(Package).GetMethod("GetService", BindingFlags.Instance | BindingFlags.NonPublic);
            Assert.IsNotNull(info);
            OleMenuCommandService mcs = info.Invoke(package, new object[] { (typeof(IMenuCommandService)) }) as OleMenuCommandService;

            Assert.IsNotNull(mcs.FindCommand(menuCommandID));
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Gets a method.
        /// </summary>
        /// <param name="t"></param>
        /// <param name="methodName"></param>
        /// <param name="flags"></param>
        /// <param name="p1"></param>
        /// <param name="parameterTypes"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        public static System.Reflection.MethodInfo GetMethod(this Type t, string methodName, BindingFlags flags, object p1, Type[] parameterTypes, object p2)
        {
            var ti = t.GetTypeInfo();

            System.Reflection.MethodInfo result = null;
            while (ti != null)
            {
                var potentials = ti.DeclaredMethods.
                                 Where(r => r.Name == methodName &&
                                       r.GetParameters().Count() == parameterTypes.Count());
                foreach (var item in potentials)
                {
                    result = item;
                    var resultParameters = result.GetParameters();
                    for (int i = 0; i < resultParameters.Count(); i++)
                    {
                        if (resultParameters[i].ParameterType != parameterTypes[i])
                        {
                            result = null;
                            break;
                        }
                    }
                    if (result != null)
                    {
                        break;
                    }
                }
                if (result != null)
                {
                    break;
                }
                if (ti.BaseType == null)
                {
                    break;
                }
                ti = ti.BaseType.GetTypeInfo();
            }
            return(result);
        }
Ejemplo n.º 55
0
        public static object InvokeWhereWithMethod(object linqQuery, MethodInfo fieldMethod, string propertyName, object value)
        {
            Type dataType             = linqQuery.GetType().GetGenericArguments()[0];
            ParameterExpression param = System.Linq.Expressions.Expression.Parameter(dataType, "n");

            System.Reflection.PropertyInfo     pinfo;
            System.Linq.Expressions.Expression left, right;

            left = GetPropertyExpression(param, dataType, propertyName, out pinfo);

            if (pinfo.PropertyType.GetTypeInfo().IsGenericType)
            {
                Type ptype = pinfo.PropertyType.GetGenericArguments()[0];
                left = System.Linq.Expressions.Expression.Convert(left, ptype);
                //等式右边的值
                right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(value, ptype));
            }
            else
            {
                //等式右边的值
                right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(value, pinfo.PropertyType));
            }

            System.Linq.Expressions.Expression expression = System.Linq.Expressions.Expression.Call(left, fieldMethod, right);
            expression = System.Linq.Expressions.Expression.Lambda(expression, param);

            Type queryableType = typeof(System.Linq.Queryable);
            var  methods       = queryableType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

            foreach (System.Reflection.MethodInfo method in methods)
            {
                if (method.Name == "Where" && method.IsGenericMethod)
                {
                    System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType);
                    return(mmm.Invoke(null, new object[] { linqQuery, expression }));
                }
            }
            return(null);
        }
Ejemplo n.º 56
0
        private bool IsAutoRegistration(string userid)
        {
            var result     = false;
            var Permission = User.permissions.Where(p => p.SelfRegistration != null && p.SelfRegistration.Value);

            foreach (var ent in Permission)
            {
                result = true;
                var    EntityName               = ent.EntityName;
                Type   controller               = Type.GetType("GeneratorBase.MVC.Controllers." + EntityName + "Controller");
                object objController            = Activator.CreateInstance(controller, null);
                System.Reflection.MethodInfo mc = controller.GetMethod("IsAlreadyRegistred");
                object[] MethodParams           = new object[] { userid, db };
                var      result1 = mc.Invoke(objController, MethodParams);
                if (Convert.ToBoolean(result1))
                {
                    return(false);
                }
            }

            return(result);
        }
Ejemplo n.º 57
0
    /// <summary>
    /// 调用类型的 实例/静态 方法。
    /// </summary>
    /// <param name="type">当前类型。</param>
    /// <param name="name">方法名称。</param>
    /// <param name="instance">当前实例。</param>
    /// <param name="args">参数列表。</param>
    /// <returns>返回方法调用的结果。</returns>
    public static object MethodInvoke(Type type, string name, object instance, object[] args)
    {
#if netcore
        System.Reflection.MethodInfo methodInfo = null;
        if (instance == null)
        {
            methodInfo = type.GetMethod(name, DefaultBindingFlags | BindingFlags.Static | BindingFlags.InvokeMethod);
        }
        else
        {
            methodInfo = type.GetMethod(name, DefaultBindingFlags | BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Static);
        }
        if (methodInfo == null)
        {
            Symbol.CommonException.ThrowNotSupported(string.Format("未找到方法 {0}.{1}", type.FullName2(), name));
        }

        return(methodInfo.Invoke(instance, args));
#else
        return(InvokeMember(type, name, instance, DefaultBindingFlags | BindingFlags.Static | BindingFlags.Instance | BindingFlags.InvokeMethod, args));
#endif
    }
Ejemplo n.º 58
0
        public void RunTest(MethodInfo testMethod, bool exe)
        {
            if (testMethod == null)
            {
                throw new ArgumentNullException(nameof(testMethod));
            }
            Generator gen;

            ParameterInfo[] pi = testMethod.GetParameters();

            if (pi.Length == 1 && pi[0].ParameterType == typeof(AssemblyGen))
            {
                gen = ((Generator)Delegate.CreateDelegate(typeof(Generator), testMethod, true));
            }
            else
            {
                throw new ArgumentException("Wrong test method signature", nameof(testMethod));
            }


            RunTest(gen, exe);
        }
Ejemplo n.º 59
0
        System.Reflection.MethodInfo GetPaneMethod(string methodName, object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            System.Type t = obj.GetType();

            System.Reflection.MethodInfo method = null;
            while (t != null)
            {
                method = t.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (method != null)
                {
                    return(method);
                }

                t = t.BaseType;
            }
            return(null);
        }
Ejemplo n.º 60
0
        // Generic bases work.
//		[Test]
        public void GenericBase()
        {
            SR.MethodInfo   mi  = typeof(Int16).GetMethod("CompareTo", new Type[] { typeof(Int16) });
            MethodReference mr1 = m_module.Import(mi);

            Type[] types = typeof(Int16).GetInterfaces();
            foreach (Type t in types)
            {
                if (t.IsGenericType)
                {
                    mi = t.GetMethod("CompareTo");
                    if (mi != null)
                    {
                        MethodReference mr2 = m_module.Import(mi);                              // this throws
                        Console.WriteLine(mr1);
                        Console.WriteLine(mr2);

                        Assert.IsTrue(MethodMatcher.Match(mr1, mr2));
                    }
                }
            }
        }