Esempio n. 1
0
        /// <summary>
        /// 代理执行方法
        /// </summary>
        /// <param name="action"></param>
        /// <param name="obj"></param>
        /// <param name="nameValues"></param>
        /// <returns></returns>
        private static ActionResult MethodInvoke(MethodInfo action, FastInvoke.FastInvokeHandler actionInvoker, object obj, NameValueCollection nameValues)
        {
            ActionResult result = null;

            try
            {
                var @params = action.GetParameters();

                if (@params != null && @params.Length > 0)
                {
                    var list = FillPamars(@params, nameValues);

                    result = (ActionResult)actionInvoker.Invoke(obj, list.ToArray());
                }
                else
                {
                    result = (ActionResult)actionInvoker.Invoke(obj, null);
                }
            }
            catch (Exception ex)
            {
                result = new ContentResult($"{obj}/{action.Name},出现异常:{ex.Message}", System.Net.HttpStatusCode.InternalServerError);
            }
            return(result);
        }
Esempio n. 2
0
        public static object InvokeMethod(this object obj, string method, object[] args)
        {
            MethodInfo mi = null;

            foreach (var m in obj.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (m.Name == method && m.GetParameters().Length == args.Length)
                {
                    bool equalParameters = true;
                    for (int i = 0; i < m.GetParameters().Length; i++)
                    {
                        var type = m.GetParameters()[i];
                        if (!type.ParameterType.IsInstanceOfType(args[i]))
                        {
                            equalParameters = false;
                            break;
                        }
                    }
                    if (equalParameters)
                    {
                        mi = m;
                        break;
                    }
                }
            }
            if (mi == null)
            {
                throw new NotSupportedException();
            }
            FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(mi);
            return(fastInvoker(obj, args));
        }
Esempio n. 3
0
        public static FastInvoke.FastInvokeHandler GetMethod(Type type, string method, params Type[] args)
        {
            FastInvoke.FastInvokeHandler handler = null;
            ConcurrentDictionary <MethodInfo, FastInvoke.FastInvokeHandler> invokes = null;
            MethodInfo methodInfo = type.GetMethod(method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, args, null);

            if (methodInfo != null)
            {
                if (invokeCache.TryGetValue(type, out invokes))
                {
                    if (invokes.TryGetValue(methodInfo, out handler))
                    {
                        return(handler);
                    }
                }

                handler = FastInvoke.GetMethodInvoker(methodInfo);
                if (handler != null && invokes == null)
                {
                    invokes = new ConcurrentDictionary <MethodInfo, FastInvoke.FastInvokeHandler>();
                    invokeCache.TryAdd(type, invokes);
                }

                invokes.TryAdd(methodInfo, handler);
            }
            return(handler);
        }
Esempio n. 4
0
        object InvokeMethod(object[] ConnectionArgs, string FileName, string MethodName, object[] Args)
        {
            try
            {
                Type[] types = new Type[Args.Length];
                for (int i = 0; i < types.Length; i++)
                {
                    if (Args[i] != null)
                    {
                        types[i] = Args[i].GetType();
                    }
                    else
                    {
                        types[i] = Type.GetType("System.Object");
                    }
                }

                Type       type       = GetType(FileName, MethodName, types);
                MethodInfo methodInfo = GetMethod(MethodName, type, types);
                object     obj        = null;
                if (!methodInfo.IsStatic)
                {
                    obj = Activator.CreateInstance(type, ConnectionArgs);
                }
                FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                return(fastInvoker(obj, Args));
            }
            catch (Exception ee)
            {
                logger.Error(string.Format("[{0}]访问方法InvokeMethod(object[] ConnectionArgs, string FileName, string MethodName, object[] Args)出错,原因为“{1}”,参数列表:{2},{3}", ApplicationContext.Current.UserName, ee.Message, FileName, MethodName));
                return(null);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 执行反射方法,针对系统程序集
        /// </summary>
        /// <param name="type">要反射的类型</param>
        /// <param name="methodName">方法名</param>
        /// <param name="args">参数</param>
        /// <param name="instance">类型实例对象</param>
        /// <param name="isStaticMethod">是否静态方法</param>
        /// <param name="parmaTypes">方法参数类型集合</param>
        /// <param name="methodGenericTypes">方法的泛型参数</param>
        /// <returns>返回执行结果</returns>
        public static object ExecuteReflectMethod(Type type, string methodName, object[] args, ref object instance, bool isStaticMethod = false, Type[] parmaTypes = null, Type[] methodGenericTypes = null)
        {
            BindingFlags bindFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

            if (!isStaticMethod)
            {
                if (instance == null)
                {
                    instance = Activator.CreateInstance(type);
                }
            }
            MethodInfo method = parmaTypes != null?type.GetMethod(methodName, bindFlags, null, parmaTypes, null) : type.GetMethod(methodName, bindFlags);

            if (method == null)
            {
                return(null);
            }
            if (methodGenericTypes != null)
            {
                method = method.MakeGenericMethod(methodGenericTypes);
            }
            //反射执行方法
            FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(method);
            try
            {
                object executedObj = fastInvoker(instance, args);
                return(executedObj);
            }
            catch
            {
                return(method.Invoke(instance, args));
            }
        }
Esempio n. 6
0
        private object FastMethodInvoke(SrvRquest srvRquest)
        {
            SrvPath srvPath = null;

            if (dicSrv.TryGetValue(srvRquest.SrvName, out srvPath))
            {
                MethodInfo info = null;
                if (srvPath.SrvMethodInfo.TryGetValue(srvRquest.SrvMethod, out info))
                {
                    if (srvPath.SrvInstance == null)
                    {
                        srvPath.SrvInstance = Activator.CreateInstance(srvPath.SrvType);
                    }
                    //
                    List <object> list = new List <object>();
                    foreach (SrvParam param in srvRquest.SrvParam)
                    {
                        list.Add(param.ParamObj);
                    }
                    FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(info);
                    object result = fastInvoker.Invoke(srvPath, list.ToArray());
                    return(result);
                }
                return(null);
            }
            return(null);
        }
Esempio n. 7
0
        public static object InvokeGenericMethod(this object obj, Type genericType, string method, object[] args)
        {
            MethodInfo mi            = obj.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).First(m => m.Name == method && m.IsGenericMethod);
            MethodInfo miConstructed = mi.MakeGenericMethod(genericType);

            FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(miConstructed);
            return(fastInvoker(obj, args));
        }
Esempio n. 8
0
        ///	<summary>
        ///	执行代理类指定方法,有返回值。不支持没有返回值的远程方法。
        ///	</summary>
        ///	<param	name="methodName">方法名称</param>
        ///	<param	name="param">参数数组,数组中每个成员,代表一个实际参数,没有参数就直接传入null</param>
        ///	<returns>远程方法返回值</returns>
        public object ExecuteQuery(string methodName, object[] param)
        {
            object rtnObj = null;

            string[]      args  = new string[2];
            List <string> list  = new List <string>();
            List <string> list1 = new List <string>();
            List <string> list2 = new List <string>();

            object[] obj = new object[3];

            try
            {
                if (this._typeName == null)
                {
                    //记录Web服务访问类名错误日志代码位置
                    throw new TypeLoadException("Web服务访问类名【" + this._wsdlName + "】不正确,请检查!");
                }
                //调用方法



                MethodInfo mi = this._typeName.GetMethod(methodName);
                FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(mi);


                if (mi == null)
                {
                    //记录Web服务方法名错误日志代码位置
                    throw new TypeLoadException("Web服务访问方法名【" + methodName + "】不正确,请检查!");
                }
                try
                {
                    if (param == null)
                    {
                        //另一个方式,出多,实际不用
                        rtnObj = fastInvoker(_instance, null);
                    }
                    else
                    {
                        rtnObj = mi.Invoke(_instance, param);
                    }
                }
                catch (TypeLoadException tle)
                {
                    //记录Web服务方法参数个数错误日志代码位置
                    throw new TypeLoadException("Web服务访问方法【" + methodName + "】参数个数不正确,请检查!", new TypeLoadException(tle.StackTrace));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, new Exception(ex.StackTrace));
            }
            return(rtnObj);
        }
Esempio n. 9
0
        object InvokeMethod(string FileName, string MethodName, object[] Args)
        {
            String errorPara = "";

            try
            {
                Type   type   = null;
                Int32  repeat = 0;
                Type[] types  = new Type[Args.Length];

                while (type == null && repeat < 3)
                {
                    repeat++;
                    if (repeat > 1)
                    {
                        Thread.Sleep(300);
                    }
                    for (int i = 0; i < types.Length; i++)
                    {
                        if (Args[i] != null)
                        {
                            types[i] = Args[i].GetType();
                        }
                        else
                        {
                            types[i] = Type.GetType("System.Object");
                        }
                        errorPara += ", " + types[i].ToString();
                    }
                    type = GetType(FileName, MethodName, types);
                }

                MethodInfo methodInfo = GetMethod(MethodName, type, types);
                object     obj        = null;
                if (!methodInfo.IsStatic)
                {
                    obj = Activator.CreateInstance(type, false);
                }
                FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                object result = fastInvoker(obj, Args);

                return(result);
            }
            catch (Exception ee)
            {
                logger.Error(string.Format("[{0}]访问方法object InvokeMethod(string FileName, string MethodName, object[] Args)出错,原因为“{1}”,参数列表:{2},{3}, Para={4}",
                                           ApplicationContext.Current.UserName, ee.Message, FileName, MethodName, errorPara));
                return(null);
            }
        }
Esempio n. 10
0
        private void Tran()
        {
            for (int i = 0; i < sqlColltion.Count; i++)
            {
                BaseEntitie obj = sqlColltion[i];
                Type        type;
                type = obj.GetType();
                FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(type.GetMethod("get_Action"));
                object      o           = fastInvoker(obj, null);
                string      s_ClassName = type.Name.Replace("Info", "Dao");
                IDataAccess o_Class     = (IDataAccess)CacheFactory.CreateObject("AYJZ.DataAccess." + s_ClassName);
                int         iReturn     = 0;
                switch (Convert.ToInt16(o))
                {
                case DatabaseActions.Insert:
                    iReturn = o_Class.Insert(obj, trans);
                    break;

                case DatabaseActions.Update:
                    iReturn = o_Class.Update(obj, trans);
                    break;

                case DatabaseActions.Delete:
                    iReturn = o_Class.Delete(obj, trans);
                    break;

                case DatabaseActions.Query:
                    iReturn = o_Class.Insert(obj, trans);
                    break;

                case DatabaseActions.Ingore:
                    iReturn = o_Class.Insert(obj, trans);
                    break;

                default:
                    iReturn = 0;
                    break;
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="method"></param>
        /// <param name="methodInvoker"></param>
        /// <param name="obj"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private static object ReversalMethod(MethodInfo method, FastInvoke.FastInvokeHandler methodInvoker, object obj, object[] args)
        {
            object result = null;

            try
            {
                var inputs = args;

                var @params = method.GetParameters();

                if (@params == null || @params.Length == 0)
                {
                    inputs = null;
                }
                result = methodInvoker.Invoke(obj, inputs);
            }
            catch (Exception ex)
            {
                throw new RPCPamarsException($"{obj}/{method.Name},用户自定义业务代码出现异常:{ex.Message}", ex);
            }
            return(result);
        }
Esempio n. 12
0
        public Boolean Validate(int allowErrorNum, out List <string> errMsgList)
        {
            Boolean result = true;

            errMsgList = new List <string>();

            //创建扩展验证器
            foreach (InvokerInfo info in container.ExtValidators)
            {
                try
                {
                    Assembly ass = Assembly.Load(info.Assembly);
                    Type     t   = ass.GetType(info.ClassName, true);
                    typeHashtable.Add(info.ClassName, Activator.CreateInstance(t));

                    List <Type> typeList = new List <Type>();
                    for (int i = 0; i < info.ParamsType.Count; i++)
                    {
                        switch (info.ParamsType[i].ToUpper())
                        {
                        case "STRING":
                            typeList.Add(typeof(string));
                            break;

                        default:
                            throw new Exception();
                        }
                    }
                    MethodInfo methodInfo = t.GetMethod(info.MethodName, typeList.ToArray());
                    methodHashtable.Add(info.MethodName, methodInfo);
                }
                catch (Exception ex)
                {
                    result = false;
                    throw ex;
                }
            }

            //验证工作表是否存在
            ISheet st = null;

            st = workbook.GetSheet(dataSheetName);
            bool tr = true;

            if (st == null)
            {
                errMsgList.Add($"文件中必须存在名为{dataSheetName}的工作表");
                return(result);
            }


            IEnumerator it = st.GetRowEnumerator();

            //验证表头是否正确
            try
            {
                // 判断是否添加动态列方法
                if (container.DynamicTable)
                {
                    AddDynamicCols(st);
                }

                var headRowNo = container.HeadRowNo;
                foreach (KeyValuePair <int, string> name in container.ColsDesc)
                {
                    if (!name.Value.Trim().Equals(st.GetRow(headRowNo).GetCell(name.Key).StringCellValue.Trim()))
                    {
                        result = false;
                        errMsgList.Add($"表格式不正确。第{name.Key}列应该是{name.Value}");
                        return(result);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //验证列表中的数据是否正确
            for (int i = container.DataStartRowNo; i < st.LastRowNum; i++)
            {
                //格式验证
                try
                {
                    foreach (KeyValuePair <int, IValidators> v in container.FormatValidators)
                    {
                        IValidators validator = v.Value;
                        if (!validator.Validate(st.GetRow(i).GetCell(v.Key)))
                        {
                            result = false;
                            errMsgList.Add($"第{i}行/第{v.Key}列格式验证不通过,原因:{validator.ErrorMessage}");
                            if (errMsgList.Count >= allowErrorNum)
                            {
                                return(result);
                            }
                        }
                    }
                }
                catch
                {
                    result = false;
                    errMsgList.Add("数据格式不正确,数据格式验证出现异常");
                    return(result);
                }

                //扩展验证(存在性验证)
                foreach (InvokerInfo info in container.ExtValidators)
                {
                    try
                    {
                        List <object> objectList = new List <object>();

                        for (int r = 0; r < info.ParamsType.Count; r++)
                        {
                            switch (info.ParamsType[r].ToUpper())
                            {
                            case "STRING":
                                objectList.Add(Convert.ToString(st.GetRow(r).GetCell(info.ParamsColNo[r])));
                                break;

                            default:
                                throw new Exception();
                            }
                        }
                        MethodInfo methodInfo = (MethodInfo)methodHashtable[info.MethodName];
                        FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                        string extMsg = (string)fastInvoker(typeHashtable[info.ClassName], objectList.ToArray());
                        if (!string.IsNullOrEmpty(extMsg))
                        {
                            result = false;
                            errMsgList.Add($"第{i}行验证通不过 原因:{extMsg}");
                            if (errMsgList.Count >= allowErrorNum)
                            {
                                return(result);
                            }
                        }
                    }

                    catch (Exception ex)
                    {
                        result = false;
                        throw ex;
                    }
                }
            }

            return(result);
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            Type       t          = typeof(Person);
            MethodInfo methodInfo = t.GetMethod("Say");
            Person     person     = new Person();
            string     word       = "hello";
            Person     p          = null;

            object[] param     = new object[] { word, p, 3 };
            int      TestTimes = 10000; //测试次数,可自行调节看效果

            #region 快速反射
            try
            {
                Stopwatch watch1 = new Stopwatch();
                FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                watch1.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    fastInvoker(person, param);
                }
                watch1.Stop();
                Console.WriteLine(TestTimes.ToString() + " times invoked by FastInvoke: " + watch1.ElapsedMilliseconds + "ms");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("快速反射 错误:" + ex.Message);
            }
            #endregion
            #region  统方式反射
            try
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    methodInfo.Invoke(person, param);
                }
                watch.Stop();
                Console.WriteLine(TestTimes.ToString() + " times invoked by Reflection: " + watch.ElapsedMilliseconds + "ms");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("传统方式反射 直接错误:" + ex.Message);
                Console.WriteLine("传统方式反射 内部错误:" + ex.InnerException.Message);
            }
            #endregion



            #region 直接调用
            try
            {
                Stopwatch watch2 = new Stopwatch();
                watch2.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    person.Say(ref word, out p, 3);
                }
                watch2.Stop();
                Console.WriteLine(TestTimes.ToString() + " times invoked by DirectCall: " + watch2.ElapsedMilliseconds + "ms");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("直接调用 错误:" + ex.Message);
            }
            #endregion

            Console.ReadLine();
        }