public bool HasTestCasesFor(System.Reflection.MethodInfo method)
        {
            if (method.GetParameters().Length == 0)
                return false;

            foreach (ParameterInfo parameter in method.GetParameters())
                if (!dataPointProvider.HasDataFor(parameter))
                    return false;

            return true;
        }
        public override object GetInstance(System.Reflection.ConstructorInfo constructor, object[] parameters = null)
        {
            if (cache.ContainsKey(constructor.DeclaringType))
            {
                return cache[constructor.DeclaringType];
            }

            var dependencies = constructor.GetParameters();
            if (dependencies.Count() == 0)
            {
                var instance = Activator.CreateInstance(constructor.DeclaringType);
                cache.Add(constructor.DeclaringType, instance);

                return instance;
            }
            else
            {
                if (parameters == null || parameters.Count() != dependencies.Count())
                {
                    throw new Exception("Incorrect number of parameters to invoke instance.");
                }

                var instance = constructor.Invoke(parameters);
                cache.Add(constructor.DeclaringType, instance);

                return instance;
            }
        }
 private LogicalMethodInfo(System.Reflection.MethodInfo beginMethodInfo, System.Reflection.MethodInfo endMethodInfo, WebMethod webMethod)
 {
     this.methodInfo = beginMethodInfo;
     this.endMethodInfo = endMethodInfo;
     this.methodName = beginMethodInfo.Name.Substring(5);
     if (webMethod != null)
     {
         this.binding = webMethod.binding;
         this.attribute = webMethod.attribute;
         this.declaration = webMethod.declaration;
     }
     ParameterInfo[] parameters = beginMethodInfo.GetParameters();
     if (((parameters.Length < 2) || (parameters[parameters.Length - 1].ParameterType != typeof(object))) || (parameters[parameters.Length - 2].ParameterType != typeof(AsyncCallback)))
     {
         throw new InvalidOperationException(Res.GetString("WebMethodMissingParams", new object[] { beginMethodInfo.DeclaringType.FullName, beginMethodInfo.Name, typeof(AsyncCallback).FullName, typeof(object).FullName }));
     }
     this.stateParam = parameters[parameters.Length - 1];
     this.callbackParam = parameters[parameters.Length - 2];
     this.inParams = GetInParameters(beginMethodInfo, parameters, 0, parameters.Length - 2, true);
     ParameterInfo[] paramInfos = endMethodInfo.GetParameters();
     this.resultParam = paramInfos[0];
     this.outParams = GetOutParameters(endMethodInfo, paramInfos, 1, paramInfos.Length - 1, true);
     this.parameters = new ParameterInfo[this.inParams.Length + this.outParams.Length];
     this.inParams.CopyTo(this.parameters, 0);
     this.outParams.CopyTo(this.parameters, this.inParams.Length);
     this.retType = endMethodInfo.ReturnType;
     this.isVoid = this.retType == typeof(void);
     this.attributes = new Hashtable();
 }
Example #4
0
        /// <summary>
        /// 创建一个ParameterCollection
        /// </summary>
        /// <param name="method"></param>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static ParameterCollection CreateParameters(System.Reflection.MethodInfo method, string jsonString)
        {
            if (!string.IsNullOrEmpty(jsonString))
            {
                JObject obj = JObject.Parse(jsonString);
                if (obj.Count > 0)
                {
                    var pis = method.GetParameters();
                    object[] parameters = new object[pis.Length];
                    var index = 0;
                    foreach (var p in pis)
                    {
                        var property = obj.Properties().SingleOrDefault(o => string.Compare(o.Name, p.Name, true) == 0);
                        if (property != null)
                        {
                            //获取Json值
                            string value = property.Value.ToString(Newtonsoft.Json.Formatting.None);
                            object jsonValue = CoreHelper.ConvertJsonValue(p.ParameterType, value);
                            parameters[index] = jsonValue;
                        }

                        index++;
                    }

                    //创建参数集合
                    return CreateParameters(method, parameters);
                }
            }

            //如果json检测不通过,返回空的参数集合
            return new ParameterCollection();
        }
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            var methodParams = methodInfo.GetParameters();

            foreach (var parameterInfo in methodParams)
            {
                if (parameterInfo.HasDefaultValue)
                {
                    continue;
                }

                var paramType = parameterInfo.ParameterType;
                if (!IsSimpleType(paramType))
                {
                    continue;
                }

                var value = controllerContext.Controller.ValueProvider.GetValue(parameterInfo.Name);
                if (value == null || value.AttemptedValue == null || !CanParse(value.AttemptedValue, paramType, value.Culture))
                {
                    return false;
                }
            }

            return true;
        }
 private StringBuilder GetArgsString(System.Reflection.MethodInfo method)
 {
     var sb = new StringBuilder();
     foreach (var arg in method.GetParameters())
         sb.Append(string.Format("{0} {1}, ", arg.ParameterType.Name, arg.Name));
     return sb;
 }
	public CompositionException(System.Reflection.MethodBase Method,string message, System.Exception innerException):this(String.Format("{0}\r\nAssembly:{1}\r\n{2}:{3}\r\nArgs:\r\n",message,Method.ReflectedType.AssemblyQualifiedName,Method.MemberType.ToString(),Method.Name),innerException)
	{
		System.Reflection.ParameterInfo[] parameters = Method.GetParameters();
		for(int i = 0; i<parameters.Length; i++)
		{
			_message = String.Format("{0}\t{1}({2})\r\n",_message,parameters[i].Name,parameters[i].ParameterType.ToString());
		}
	}
        protected override void GenerateMethodCall(StringBuilder js, System.Reflection.MethodInfo method, string Controller, bool documentate)
        {
            var jsattribute = method.DeclaringType.GetCustomAttributes(typeof(JsActionAttribute), false).First() as JsActionAttribute;

            if (groups.Count(str => string.IsNullOrEmpty(str) == false) > 0 && jsattribute.Groups.Split(',').Intersect(groups).Count() == 0)
                return;

            var pars = method.GetParameters();

            var parameters = string.Join(",", pars.Select(m => m.Name));
            if (parameters.Length > 0)
                parameters += ',';
            js.AppendFormat("{0}:function({1}options)", method.Name, parameters);

            pars.FirstOrDefault(m =>
            {
                if (m.ParameterType.IsGenericType)
                    ComplexTypeList.Value.Add(m.ParameterType.GetGenericArguments().First());
                else if (this.FindIEnumerable(m.ParameterType) == null && m.ParameterType != typeof(DateTime) && m.ParameterType != typeof(DateTimeOffset) && m.ParameterType.IsPrimitive == false)
                    ComplexTypeList.Value.Add(m.ParameterType);
                return false;
            });

            js.Append('{');
            if (documentate)
            {
                //Method can be empty.
                this.DocumentateTheFunction(js, method);
                js.Append("},");
                return;

            }
            string url = RouteTable.Routes.GetVirtualPath(this.requestContext, new RouteValueDictionary(new { httproute = "", controller = Controller })).VirtualPath;

            StringBuilder jsondata = new StringBuilder();

            foreach (var parameter in pars)
            {
                jsondata.AppendFormat("{0}:{0},", parameter.Name);
            }

            if (jsondata.Length > 0)
                jsondata.Remove(jsondata.Length - 1, 1);

            string requestmethod = string.Empty;

            if (method.Name.StartsWith("GET", StringComparison.InvariantCultureIgnoreCase))
                requestmethod = "GET";
            else if (method.Name.StartsWith("POST", StringComparison.InvariantCultureIgnoreCase))
                requestmethod = "POST";
            else if (method.Name.StartsWith("PUT", StringComparison.InvariantCultureIgnoreCase))
                requestmethod = "PUT";
            else if (method.Name.StartsWith("DELETE", StringComparison.InvariantCultureIgnoreCase))
                requestmethod = "DELETE";

            js.AppendFormat("var opts={{success:trd,url:\"{0}\",async:{4},cache:{3},type:\"{1}\",data:$.toDictionary({{{2}}})}};", url, requestmethod, jsondata, jsattribute.CacheRequest == true ? "true" : "false", jsattribute.Async == true ? "true" : "false");
            js.Append("jQuery.extend(opts,options);return jQuery.ajax(opts);},");
        }
 private static string MethodToString(System.Reflection.MethodInfo method)
 {
   return (method.ReturnType == null ? "void" : method.ReturnType.Name)
     + " "
     + method.Name
     + "("
     + method.GetParameters()
             .GroupConcat(", ", p => (p.IsOut ? "out " : "") + p.ParameterType.Name + " " + p.Name + (p.IsOptional ? " = " + (p.DefaultValue ?? "null").ToString() : ""))
     + ")";
 }
 public Method(System.Reflection.MethodInfo theMethod) {
     method = theMethod;
     var methodArguments = method.GetParameters();
     arguments = new Argument[methodArguments.Length];
     for (var i = 0; i < methodArguments.Length; ++i) {
         arguments[i] = new Argument();
         arguments[i].name = methodArguments[i].Name;
         arguments[i].type = methodArguments[i].ParameterType;
     }
 }
Example #11
0
        public Result Execute(ICommunicationObject client, string service, System.Reflection.MethodBase method, params object[] data)
        {


            RemoteInvokeArgs info = new RemoteInvokeArgs();
            info.Interface = service;
            int index = method.Name.LastIndexOf('.');
            index = index>0?(index+1):0;
            info.Method = method.Name.Substring(index, method.Name.Length - index);
            info.Parameters = data;
            info.CommunicationObject = client;
            info.ParameterInfos = method.GetParameters();
            foreach (System.Reflection.ParameterInfo pi in method.GetParameters())
            {
                info.ParameterTypes.Add(pi.ParameterType.Name);
            }
            return Handler.Execute(info);

        }
Example #12
0
        /// <summary>
        /// 设置ParameterCollection值
        /// </summary>
        /// <param name="method"></param>
        /// <param name="collection"></param>
        /// <param name="parameters"></param>
        public static void SetRefParameters(System.Reflection.MethodInfo method, ParameterCollection collection, object[] parameters)
        {
            int index = 0;
            foreach (var p in method.GetParameters())
            {
                if (p.ParameterType.IsByRef)
                    collection[p.Name] = parameters[index];

                index++;
            }
        }
Example #13
0
        /// <summary>
        /// 设置参数值
        /// </summary>
        /// <param name="method"></param>
        /// <param name="collection"></param>
        /// <param name="parameters"></param>
        public static void SetRefParameterValues(System.Reflection.MethodInfo method, ParameterCollection collection, object[] parameters)
        {
            var index = 0;
            foreach (var p in method.GetParameters())
            {
                //给参数赋值
                if (p.ParameterType.IsByRef)
                    parameters[index] = collection[p.Name];

                index++;
            }
        }
Example #14
0
        public override bool CompileTimeValidate(System.Reflection.MethodBase method)
        {
            var parameters = method.GetParameters().ToArray();
            for (var i = 0; i < parameters.Length; i++)
                if (this._arguments[i] != parameters[i].ParameterType)
                {
                    var msg = string.Format(ArgumentValidationAspect._INVALID_ARGUMENT, _paramNames);
                    throw new ArgumentException(msg, parameters[i].Name);
                }

            return true;
        }
Example #15
0
 private void BuilderMethod(System.Reflection.MethodInfo method)
 {
     List<string> ps = new List<string>();
     List<string> tps = new List<string>();
     ParameterInfo[] pis = method.GetParameters();
     foreach (ParameterInfo pi in method.GetParameters())
     {
         tps.Add(pi.Name);
         string pt = "";
        if (pi.IsRetval)
             pt = "ref";
         if (pi.IsOut)
             pt = "out";
         ps.Add(string.Format(" {0} {1} {2}", pt, GetTypeName(pi.ParameterType), pi.Name));
     }
     mCode.AppendFormat("public {0} {1}({2})\r\n", method.ReturnType.FullName == "System.Void" ? "void" :GetTypeName( method.ReturnType),
         method.Name, ps.Count == 0 ? "" : string.Join(",", ps.ToArray()));
     mCode.AppendLine("{");
     foreach (ParameterInfo pi in method.GetParameters())
     {
         if (pi.IsOut)
             mCode.AppendFormat("{0}=default({1});\r\n", pi.Name,  GetTypeName( pi.ParameterType));
     }
     mCode.AppendFormat("Result result = ProxyFactory.CursorFactory.Execute(this,\"{1}\",System.Reflection.MethodInfo.GetCurrentMethod(),{0});",
         tps.Count == 0 ? "new object[0]" : string.Join(",", tps.ToArray()),mInterfaceType.Name);
     for (int i = 0; i < ps.Count; i++)
     {
         if (ps[i].IndexOf("ref") >= 0 || ps[i].IndexOf("out")>=0)
         {
             mCode.AppendFormat("{0}=({1})result[\"{0}\"];", tps[i], GetTypeName( pis[i].ParameterType));
         }
     }
     if (method.ReturnType.FullName != "System.Void")
     {
         mCode.AppendFormat("return ({0})result.Data;\r\n",GetTypeName( method.ReturnType));
     }
     mCode.AppendLine("}");
 }
    public static DynamicMethodDelegate CreateMethod(System.Reflection.MethodInfo method)
    {
      if (method == null)
        throw new ArgumentNullException("method");

      ParameterInfo[] pi = method.GetParameters();
      var targetExpression = Expression.Parameter(typeof(object));
      var parametersExpression = Expression.Parameter(typeof(object[]));

      Expression[] callParametrs = new Expression[pi.Length];
      for (int x = 0; x < pi.Length; x++)
      {
        callParametrs[x] =
          Expression.Convert(
            Expression.ArrayIndex(
              parametersExpression,
              Expression.Constant(x)),
            pi[x].ParameterType);
      }

      Expression instance = Expression.Convert(targetExpression, method.DeclaringType);
      Expression body = pi.Length > 0
        ? Expression.Call(instance, method, callParametrs)
        : Expression.Call(instance, method);

      if (method.ReturnType == typeof(void))
      {
        var target = Expression.Label(typeof(object));
        var nullRef = Expression.Constant(null);
        body = Expression.Block(
          body,
           Expression.Return(target, nullRef),
          Expression.Label(target, nullRef));
      }
#if NETFX_CORE
      else if (method.ReturnType.IsValueType())
#else
      else if (method.ReturnType.IsValueType)
#endif
      {
        body = Expression.Convert(body, typeof(object));
      }

      var lambda = Expression.Lambda<DynamicMethodDelegate>(
        body,
        targetExpression,
        parametersExpression);

      return (DynamicMethodDelegate)lambda.Compile();
    }
		private string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) {
			ArrayList methodParameterNames = new ArrayList();
			try {
				System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters();

				int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0);

				for (int i = 0; i <= methodBaseGetParametersCount; i++) {
					methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name);
				}
			} catch (Exception ex) {
				LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex);
			}

			return (string[])methodParameterNames.ToArray(typeof(string));
		}
Example #18
0
        protected MethodBaseInfo(System.Reflection.MethodBase methodInfo, Dictionary<Type, TypeInfo> referenceTracker)
            : base(methodInfo, referenceTracker)
        {
            var bindingFlags = methodInfo.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
            bindingFlags |= methodInfo.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
            BindingFlags = bindingFlags;

            var genericArguments = methodInfo.IsGenericMethod ? methodInfo.GetGenericArguments() : null;
            GenericArgumentTypes = ReferenceEquals(null, genericArguments) || genericArguments.Length == 0
                ? null
                : genericArguments.Select(x => TypeInfo.Create(referenceTracker, x, false, false)).ToList();

            var parameters = methodInfo.GetParameters();
            ParameterTypes = parameters.Length == 0
                ? null
                : parameters.Select(x => TypeInfo.Create(referenceTracker, x.ParameterType, false, false)).ToList();
        }
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            // We do have an openId response, it's the provider calling back
            if (response != null)
            {
                // look for IAuthenticationResponse parameter and pass the response object to the action as we can't call GetResponse() twice later in the action method
                var parameterName = methodInfo.GetParameters().Where(pi => pi.ParameterType.Equals(typeof(IAuthenticationResponse))).Select(pi => pi.Name).SingleOrDefault();
                if (!String.IsNullOrEmpty(parameterName))
                {
                    controllerContext.RouteData.Values.Add(parameterName, response);
                }
                return true;
            }
            return false;
        }
Example #20
0
        /// <summary>
        /// 设置参数值
        /// </summary>
        /// <param name="method"></param>
        /// <param name="reqMsg"></param>
        public static object[] CreateParameterValues(System.Reflection.MethodInfo method, ParameterCollection collection)
        {
            var index = 0;
            var pis = method.GetParameters();
            var parameters = new object[pis.Length];
            foreach (var p in pis)
            {
                //给参数赋值
                if (collection[p.Name] == null)
                    parameters[index] = CoreHelper.GetTypeDefaultValue(p.ParameterType);
                else
                    parameters[index] = collection[p.Name];

                index++;
            }

            return parameters;
        }
Example #21
0
    public DynamicMethodHandle(System.Reflection.MethodInfo info, params object[] parameters)
    {
      if (info == null)
      {
        this.DynamicMethod = null;
      }
      else
      {
        this.MethodName = info.Name;
        var infoParams = info.GetParameters();
        object[] inParams = null;
        if (parameters == null)
        {
          inParams = new object[] { null };

        }
        else
        {
          inParams = parameters;
        }
        var pCount = infoParams.Length;
#if NETFX_CORE
        var isgeneric = info.ReturnType.IsGenericType();
        if (pCount > 0 &&
           ((pCount == 1 && infoParams[0].ParameterType.IsArray) ||
           (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0)))
#else
        var isgeneric = info.ReturnType.IsGenericType;
        if (pCount > 0 &&
           ((pCount == 1 && infoParams[0].ParameterType.IsArray) ||
           (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0)))
#endif
        {
          this.HasFinalArrayParam = true;
          this.MethodParamsLength = pCount;
          this.FinalArrayElementType = infoParams[pCount - 1].ParameterType;
        }
        IsAsyncTask = (info.ReturnType == typeof(System.Threading.Tasks.Task));
        IsAsyncTaskObject = (isgeneric && (info.ReturnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>)));
        this.DynamicMethod = DynamicMethodHandlerFactory.CreateMethod(info);
      }
    }
        /// <summary>
        /// 处理输入参数
        /// </summary>
        /// <param name="reqMsg"></param>
        /// <param name="method"></param>
        private void HandleBegin(RequestMessage reqMsg, System.Reflection.MethodInfo method)
        {
            //设置Invoke方式
            reqMsg.InvokeMethod = true;

            var pis = method.GetParameters();
            if (pis.Length > 0)
            {
                if (reqMsg.Parameters.Count > 0)
                {
                    string jsonString = reqMsg.Parameters.ToString();
                    reqMsg.Parameters.Clear();
                    reqMsg.Parameters["InvokeParameter"] = jsonString;
                }
                else
                {
                    reqMsg.Parameters["InvokeParameter"] = null;
                }
            }
        }
 private MyCommandArgs ParseArgs(List<string> x, System.Reflection.MethodInfo method)
 {
     MyCommandMethodArgs retVal = new MyCommandMethodArgs();
     var paramInfos = method.GetParameters();
     List<object> parameters = new List<object>();
     for (int i = 0; i < paramInfos.Length && i < x.Count; i++)
     {
         var paramType = paramInfos[i].ParameterType;
         var parseMet = paramType.GetMethod("TryParse", new Type[] { typeof(System.String), paramType.MakeByRefType() });
         if (parseMet != null)
         {
             var output = Activator.CreateInstance(paramType);
             var args = new object[] { x[i], output };
             var par = parseMet.Invoke(null, args);
             parameters.Add(args[1]);
         }
         else
             parameters.Add(x[i]);
     }
     if (paramInfos.Length == parameters.Count)
         retVal.Args = parameters.ToArray();
     return retVal;
 }
Example #24
0
        /// <summary>
        /// Generates the signature string for the specified method.
        /// </summary>
        /// <param name="aMethod">The method to generate the signature of.</param>
        /// <returns>The signature string.</returns>
        private static string GetMethodSignature(System.Reflection.MethodBase aMethod)
        {
            string[] paramTypes = aMethod.GetParameters().Select(x => x.ParameterType).Select(x => x.FullName).ToArray();
            string returnType = "";
            string declaringType = "";
            string methodName = "";
            if (aMethod.IsConstructor || aMethod is System.Reflection.ConstructorInfo)
            {
                returnType = typeof(void).FullName;
                declaringType = aMethod.DeclaringType.FullName;
                methodName = aMethod.Name;
            }
            else
            {
                returnType = ((System.Reflection.MethodInfo)aMethod).ReturnType.FullName;
                declaringType = aMethod.DeclaringType.FullName;
                methodName = aMethod.Name;
            }

            return GetMethodSignature(returnType, declaringType, methodName, paramTypes);
        }
Example #25
0
            static string GetSignature(System.Reflection.MethodInfo method)
            {
                if (method == null)
                    return null;

                System.Reflection.ParameterInfo [] parameters = method.GetParameters ();
                System.Text.StringBuilder sb = new System.Text.StringBuilder ();
                sb.Append ('(');
                foreach (System.Reflection.ParameterInfo info in parameters) {
                    sb.Append (info.ParameterType.ToString ());
                    sb.Append (',');
                }
                if (sb.Length != 0)
                    sb.Length--;

                sb.Append (')');
                return sb.ToString ();
            }
Example #26
0
        /// <summary>
        /// Конструктор узла.
        /// </summary>
        /// <param name="mi">Оборачиваемый метод.</param>
		private compiled_function_node(System.Reflection.MethodInfo mi)
		{
			_mi=mi;
			type_node ret_val=null;
			if (_mi.ReturnType!=null)
			{
				ret_val=compiled_type_node.get_type_node(mi.ReturnType);
                if (ret_val == SystemLibrary.SystemLibrary.void_type)
                {
                    ret_val = null;
                }
			}
			System.Reflection.ParameterInfo[] pinf=mi.GetParameters();
            parameter_list pal = new parameter_list();
            //if (!(_mi.IsGenericMethod))
            {
                int i = 1;
                foreach (System.Reflection.ParameterInfo pi in pinf)
                {
                    Type t = null;
                    
                    type_node par_type = null;
                    SemanticTree.parameter_type pt = SemanticTree.parameter_type.value;
//                    if (pi.ParameterType.Name.EndsWith("&") == true)
                    //(ssyy) Лучше так:
                    if (pi.ParameterType.IsByRef)
                    {
                        //t = pi.ParameterType.Assembly.GetType(pi.ParameterType.FullName.Substring(0, pi.ParameterType.FullName.Length - 1));
                        //(ssyy) Лучше так:
                        t = pi.ParameterType.GetElementType();
                        par_type = compiled_type_node.get_type_node(t);
                        pt = SemanticTree.parameter_type.var;
                    }
                    else
                    {
                        if (pi.Position == 0)
                        {
                            par_type = compiled_type_node.get_type_node(pi.ParameterType);
                            if (NetHelper.NetHelper.IsExtensionMethod(mi))
                            {
                                connected_to_type = par_type as compiled_type_node;
                            }
                        }
                    }
                    string name = pi.Name;
                    compiled_parameter crpar = new compiled_parameter(pi);
                    crpar.SetParameterType(pt);
                    pal.AddElement(crpar);
                    if (pi.IsOptional && pi.DefaultValue != null)
                        _num_of_default_parameters++;
                    i++;
                }
            }
            //else
            if (_mi.IsGenericMethod)
            {
                _generic_params_count = mi.GetGenericArguments().Length;
            }
            _is_extension_method = NetHelper.NetHelper.IsExtensionMethod(mi);
			this.return_value_type=ret_val;
			this.parameters.AddRange(pal);
		}
Example #27
0
        /// <summary>
        /// 创建一个ParameterCollection
        /// </summary>
        /// <param name="method"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static ParameterCollection CreateParameters(System.Reflection.MethodInfo method, object[] parameters)
        {
            var collection = new ParameterCollection();
            int index = 0;
            foreach (var p in method.GetParameters())
            {
                if (parameters[index] == null)
                    collection[p.Name] = CoreHelper.GetTypeDefaultValue(p.ParameterType);
                else
                    collection[p.Name] = parameters[index];

                index++;
            }

            return collection;
        }
        protected override void GenerateMethod(ILGenerator il, System.Reflection.MethodInfo method, System.Reflection.MethodInfo interfaceMethod)
        {
            // In Parameters
            ArrayList inParams = new ArrayList();
            // Ref or Out Parameters
            ArrayList refOutParams = new ArrayList();

            foreach (ParameterInfo paramInfo in interfaceMethod.GetParameters())
            {
                if (paramInfo.IsRetval || paramInfo.IsOut)
                {
                    refOutParams.Add(paramInfo);
                }
                else
                {
                    inParams.Add(paramInfo);
                }
            }

            proxyGenerator.PushTarget(il);

            //LocalBuilder methodToCall = il.DeclareLocal(typeof(MethodInfo));
            //il.Emit(OpCodes.Newobj, interfaceMethod);
            //il.Emit(OpCodes.Ldloc, methodToCall);
            il.Emit(OpCodes.Ldstr, interfaceMethod.Name);

            // Parameter #2
            LocalBuilder parameters = il.DeclareLocal(typeof(Object[]));
            il.Emit(OpCodes.Ldc_I4, inParams.Count);
            il.Emit(OpCodes.Newarr, typeof(Object));
            il.Emit(OpCodes.Stloc, parameters);

            int paramIndex = 0;
            foreach (ParameterInfo paramInfo in inParams)
            {
                il.Emit(OpCodes.Ldloc, parameters);
                il.Emit(OpCodes.Ldc_I4, paramIndex);
                il.Emit(OpCodes.Ldarg, paramInfo.Position + 1);
                if (paramInfo.ParameterType.IsValueType)
                {
                    il.Emit(OpCodes.Box, paramInfo.ParameterType);
                }
                il.Emit(OpCodes.Stelem_Ref);

                paramIndex++;
            }

            il.Emit(OpCodes.Ldloc, parameters);

            // Call Invoke method and save result
            LocalBuilder results = il.DeclareLocal(typeof(Object[]));
            il.EmitCall(OpCodes.Callvirt, InvokeMethod, null);
            il.Emit(OpCodes.Stloc, results);

            int resultIndex = (interfaceMethod.ReturnType == typeof(void) ? 0 : 1);
            foreach (ParameterInfo paramInfo in refOutParams)
            {
                il.Emit(OpCodes.Ldarg, paramInfo.Position + 1);
                il.Emit(OpCodes.Ldloc, results);

                // Cast / Unbox the return value
                il.Emit(OpCodes.Ldc_I4, resultIndex);
                il.Emit(OpCodes.Ldelem_Ref);

                Type elementType = paramInfo.ParameterType.GetElementType();
                if (elementType.IsValueType)
                {
                    il.Emit(OpCodes.Unbox, elementType);
                    il.Emit(OpCodes.Ldobj, elementType);
                    il.Emit(OpCodes.Stobj, elementType);
                }
                else
                {
                    il.Emit(OpCodes.Castclass, elementType);
                    il.Emit(OpCodes.Stind_Ref);
                }

                resultIndex++;
            }

            if (interfaceMethod.ReturnType != typeof(void))
            {
                il.Emit(OpCodes.Ldloc, results);

                // Cast / Unbox the return value
                il.Emit(OpCodes.Ldc_I4_0);
                il.Emit(OpCodes.Ldelem_Ref);
                if (interfaceMethod.ReturnType.IsValueType)
                {
                    il.Emit(OpCodes.Unbox, interfaceMethod.ReturnType);
                    il.Emit(OpCodes.Ldobj, interfaceMethod.ReturnType);
                }
                else
                {
                    il.Emit(OpCodes.Castclass, interfaceMethod.ReturnType);
                }
            }
        }
Example #29
0
    private static object CallMethod(object obj, System.Reflection.MethodInfo info, bool hasParameters, params object[] parameters)
    {
#if IOS
      var infoParams = info.GetParameters();
      var infoParamsCount = infoParams.Length;
      bool hasParamArray = infoParamsCount > 0 && infoParams[infoParamsCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0;
      bool specialParamArray = false;
      if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(string[])))
        specialParamArray = true;
      if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(object[])))
        specialParamArray = true;
      object[] par = null;
      if (infoParamsCount == 1 && specialParamArray)
      {
        par = new object[] { parameters };
      }
      else if (infoParamsCount > 1 && hasParamArray && specialParamArray)
      {
        par = new object[infoParamsCount];
        for (int i = 0; i < infoParamsCount - 1; i++)
          par[i] = parameters[i];
        par[infoParamsCount - 1] = parameters[infoParamsCount - 1];
      }
      else
      {
        par = parameters;
      }

      object result = null;
      try
      {
        result = info.Invoke(obj, par);
      }
      catch (Exception e)
      {
        Exception inner = null;
        if (e.InnerException == null)
          inner = e;
        else
          inner = e.InnerException;
        throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
      }
      return result;
#else
      var mh = GetCachedMethod(obj, info, parameters);
      if (mh == null || mh.DynamicMethod == null)
        throw new NotImplementedException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodNotImplemented);
      return CallMethod(obj, mh, hasParameters, parameters);
#endif
    }
Example #30
0
        /// <summary>
        /// Returns an collection containing a single ITestCaseData item,
        /// constructed from the arguments provided in the constructor and
        /// possibly converted to match the specified method.
        /// </summary>
        /// <param name="method">The method for which data is being provided</param>
        /// <returns></returns>
        public System.Collections.Generic.IEnumerable<ITestCaseData> GetTestCasesFor(System.Reflection.MethodInfo method)
        {
            ParameterSet parms;

            try
            {
                ParameterInfo[] parameters = method.GetParameters();
                int argsNeeded = parameters.Length;
                int argsProvided = Arguments.Length;

                parms = new ParameterSet(this);

                // Special handling for params arguments
                if (argsNeeded > 0 && argsProvided >= argsNeeded - 1)
                {
                    ParameterInfo lastParameter = parameters[argsNeeded - 1];
                    Type lastParameterType = lastParameter.ParameterType;
                    Type elementType = lastParameterType.GetElementType();

                    if (lastParameterType.IsArray && lastParameter.IsDefined(typeof(ParamArrayAttribute), false))
                    {
                        if (argsProvided == argsNeeded)
                        {
                            Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType();
                            if (!lastParameterType.IsAssignableFrom(lastArgumentType))
                            {
                                Array array = Array.CreateInstance(elementType, 1);
                                array.SetValue(parms.Arguments[argsProvided - 1], 0);
                                parms.Arguments[argsProvided - 1] = array;
                            }
                        }
                        else
                        {
                            object[] newArglist = new object[argsNeeded];
                            for (int i = 0; i < argsNeeded && i < argsProvided; i++)
                                newArglist[i] = parms.Arguments[i];

                            int length = argsProvided - argsNeeded + 1;
                            Array array = Array.CreateInstance(elementType, length);
                            for (int i = 0; i < length; i++)
                                array.SetValue(parms.Arguments[argsNeeded + i - 1], i);

                            newArglist[argsNeeded - 1] = array;
                            parms.Arguments = newArglist;
                            argsProvided = argsNeeded;
                        }
                    }
                }

                //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
                //    parms.Arguments = new object[]{parms.Arguments};

                // Special handling when sole argument is an object[]
                if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
                {
                    if (argsProvided > 1 ||
                        argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[]))
                    {
                        parms.Arguments = new object[] { parms.Arguments };
                    }
                }

                if (argsProvided == argsNeeded)
                    PerformSpecialConversions(parms.Arguments, parameters);
            }
            catch (Exception ex)
            {
                parms = new ParameterSet(ex);
            }
            
            return new ITestCaseData[] { parms };
        }