コード例 #1
0
        private FastInvoke.FastInvokeHandler GetHandler(string key, MethodInfo method)
        {
            _initializers.TryGetValue(ValueTuple.Create((Type)null, key == null ? null : key.ToString()), out var result);

            if (result == null)
            {
                result = FastInvoke.GetMethodInvoker(method);
                _initializers.GetOrAdd(ValueTuple.Create((Type)null, key), result);
            }
            return(result as FastInvoke.FastInvokeHandler);
        }
コード例 #2
0
ファイル: Class1.cs プロジェクト: jinyuttt/FastMapperEmit
        private static FastInvoke GetFastInvokPTP <T>(Type type, T obj)
        {
            string        name          = typeof(T).FullName + "To" + type.FullName + "_" + MapType.PTP;
            DynamicMethod dynamicMethod = new DynamicMethod(name, typeof(object), new Type[] { typeof(object) }, type.Module);
            var           il            = dynamicMethod.GetILGenerator();
            var           src           = il.DeclareLocal(obj.GetType());
            var           tar           = il.DeclareLocal(type);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Isinst, obj.GetType());
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Newobj, type.GetConstructor(new Type[0]));
            il.Emit(OpCodes.Stloc_1);
            var source = obj.GetType().GetProperties();

            foreach (var pty in source)
            {
                var p = type.GetProperty(pty.Name);
                if (p != null)
                {
                    if (p.PropertyType.Equals(pty.PropertyType) || !p.PropertyType.IsValueType)
                    {
                        il.Emit(OpCodes.Ldloc_1);
                        il.Emit(OpCodes.Ldloc_0);
                        il.Emit(OpCodes.Call, pty.GetMethod);
                        il.Emit(OpCodes.Call, p.SetMethod);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldloc_1);
                        il.Emit(OpCodes.Ldloc_0);
                        il.Emit(OpCodes.Call, pty.GetMethod);

                        if (p.PropertyType.IsValueType)
                        {
                            var mth = GetMethod(p.PropertyType);
                            // Convert.ToInt32();
                            var m = typeof(Convert).GetMethod(mth, new Type[] { pty.PropertyType });
                            if (m == null && pty.PropertyType.IsClass)
                            {
                                m = typeof(Convert).GetMethod(mth, new Type[] { typeof(object) });
                            }
                            il.Emit(OpCodes.Call, m);
                        }
                        il.Emit(OpCodes.Call, p.SetMethod);
                    }
                }
            }
            il.Emit(OpCodes.Ldloc_1);
            il.Emit(OpCodes.Ret);
            FastInvoke fastInvok = (FastInvoke)dynamicMethod.CreateDelegate(typeof(FastInvoke));

            return(fastInvok);
        }
コード例 #3
0
        public static void MethodProxy()
        {
            Action <bool> action = e =>
            {
                Console.WriteLine(e + ", " + DateTime.Now.ToString());
            };

            var result = FastInvoke.MethodProxy(action);

            result(action.Method, new object[] { false });
        }
コード例 #4
0
        private static FastInvoke GetFastInvokPTPI(Type dest, Type sourceType)
        {
            string        name          = sourceType.FullName + "To" + dest.FullName + "_" + MapType.PTPI;
            DynamicMethod dynamicMethod = new DynamicMethod(name, typeof(object), new Type[] { typeof(object) }, dest.Module);
            var           il            = dynamicMethod.GetILGenerator();
            var           src           = il.DeclareLocal(sourceType);
            var           tar           = il.DeclareLocal(dest);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Isinst, sourceType);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Newobj, dest.GetConstructor(new Type[0]));
            il.Emit(OpCodes.Stloc_1);
            var source = sourceType.GetProperties();

            foreach (var pty in source)
            {
                var p = dest.GetProperty(pty.Name, BindingFlags.IgnoreCase | BindingFlags.Public);
                if (p != null)
                {
                    if (p.PropertyType.Equals(pty.PropertyType) || !p.PropertyType.IsValueType)
                    {
                        il.Emit(OpCodes.Ldloc_1);
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Call, pty.GetMethod);
                        il.Emit(OpCodes.Call, p.SetMethod);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldloc_1);
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Call, pty.GetMethod);

                        if (p.PropertyType.IsValueType)
                        {
                            var mth = GetMethod(p.PropertyType);

                            var m = typeof(Convert).GetMethod(mth, new Type[] { pty.PropertyType });
                            if (m == null && pty.PropertyType.IsClass)
                            {
                                m = typeof(Convert).GetMethod(mth, new Type[] { typeof(object) });
                            }
                            il.Emit(OpCodes.Call, m);
                        }
                        il.Emit(OpCodes.Call, p.SetMethod);
                    }
                }
            }
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);
            FastInvoke fastInvok = (FastInvoke)dynamicMethod.CreateDelegate(typeof(FastInvoke));

            return(fastInvok);
        }
コード例 #5
0
        private FastInvokeHandler GetHandler(string key, MethodInfo method)
        {
            var objInstance = ServiceResolver.Current.GetService(null, key);

            if (objInstance == null)
            {
                objInstance = FastInvoke.GetMethodInvoker(method);
                ServiceResolver.Current.Register(key, objInstance, null);
            }
            return(objInstance as FastInvokeHandler);
        }
コード例 #6
0
        private async Task <HttpResultMessage <object> > RemoteExecuteAsync(ServiceEntry entry, HttpMessage httpMessage)
        {
            HttpResultMessage <object> resultMessage = new HttpResultMessage <object>();
            var provider = _concurrent.GetValueOrDefault(httpMessage.RoutePath);
            var list     = new List <object>();

            if (provider.Item1 == null)
            {
                provider.Item2 = ServiceLocator.GetService <IServiceProxyFactory>().CreateProxy(httpMessage.ServiceKey, entry.Type);
                provider.Item3 = provider.Item2.GetType().GetTypeInfo().DeclaredMethods.Where(p => p.Name == entry.MethodName).FirstOrDefault();;
                provider.Item1 = FastInvoke.GetMethodInvoker(provider.Item3);
                _concurrent.GetOrAdd(httpMessage.RoutePath, ValueTuple.Create <FastInvokeHandler, object, MethodInfo>(provider.Item1, provider.Item2, provider.Item3));
            }
            foreach (var parameterInfo in provider.Item3.GetParameters())
            {
                var value         = httpMessage.Parameters[parameterInfo.Name];
                var parameterType = parameterInfo.ParameterType;
                var parameter     = _typeConvertibleService.Convert(value, parameterType);
                list.Add(parameter);
            }
            try
            {
                var methodResult = provider.Item1(provider.Item2, list.ToArray());

                var task = methodResult as Task;
                if (task == null)
                {
                    resultMessage.Entity = methodResult;
                }
                else
                {
                    await task;
                    var   taskType = task.GetType().GetTypeInfo();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Entity = taskType.GetProperty("Result").GetValue(task);
                    }
                }
                resultMessage.IsSucceed  = resultMessage.Entity != null;
                resultMessage.StatusCode = resultMessage.IsSucceed ? (int)StatusCode.Success : (int)StatusCode.RequestError;
            }
            catch (Exception ex)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError(ex, "执行远程调用逻辑时候发生了错误。");
                }
                resultMessage = new HttpResultMessage <object> {
                    Entity = null, Message = "执行发生了错误。", StatusCode = (int)StatusCode.RequestError
                };
            }
            return(resultMessage);
        }
コード例 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="MethodName"></param>
        /// <param name="paramsValue"></param>
        /// <returns></returns>
        public static object Excute(object obj, string MethodName, object[] paramsValue)
        {
            MethodInfo methodInfo = obj.GetType().GetMethod(MethodName);

            if (methodInfo != null)
            {
                FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                return(fastInvoker(obj, paramsValue));
            }
            DMSFrame.Loggers.LoggerManager.FileLogger.LogWithTime(MethodName + "未找到");
            return(null);
        }
コード例 #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="MethodName"></param>
        /// <param name="paramsValue"></param>
        /// <returns></returns>
        public static object Excute(object obj, string MethodName, object[] paramsValue)
        {
            MethodInfo methodInfo = obj.GetType().GetMethod(MethodName);

            if (methodInfo != null)
            {
                FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                return(fastInvoker(obj, paramsValue));
            }
            Log.Debug(ReflectionUtils.GetMethodBaseInfo(System.Reflection.MethodBase.GetCurrentMethod()), MethodName + "未找到", null);
            return(null);
        }
コード例 #9
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="property">列对应的实体属性</param>
 internal Column(PropertyInfo property)
 {
     this.property = property;
     PropertyName  = Name = property.Name;
     if (property.CanWrite)
     {
         this.setValueHandle = FastInvoke.GetMethodInvoker(property.GetSetMethod());
     }
     if (property.CanRead)
     {
         this.getValueHandle = FastInvoke.GetMethodInvoker(property.GetGetMethod());
     }
 }
コード例 #10
0
        /// <summary>
        /// 获取当前类关联的DB信息
        /// </summary>
        /// <returns></returns>
        private static DBInfo GetDB()
        {
            Type cType            = typeof(T);
            DataBaseAttribute att = FastInvoke.GetClassAttribute <DataBaseAttribute>(cType);

            if (att == null)
            {
                throw new Exception(cType.FullName + "类还没配置DataBaseAttribute标签");
            }
            string dbName = att.DataBaseName;

            DataAccessLoader.InitConfig();
            return(DataAccessLoader.GetDBInfo(dbName));
        }
コード例 #11
0
        private static object DeserializeList(Type type, byte[] datas)
        {
            var stype = type.GenericTypeArguments[0];

            var gtype = type.GetGenericTypeDefinition().MakeGenericType(stype);

            var result = Activator.CreateInstance(gtype);

            var addMethod = gtype.GetMethod("Add");

            var methodInvoker = FastInvoke.GetMethodInvoker(addMethod);

            var len    = 0;
            var offset = 0;

            //容器大小
            len     = BitConverter.ToInt32(datas, offset);
            offset += 4;
            byte[] cdata = new byte[len];
            Buffer.BlockCopy(datas, offset, cdata, 0, len);
            offset += len;

            //子项内容
            var slen    = 0;
            var soffset = 0;

            while (soffset < len)
            {
                slen = BitConverter.ToInt32(cdata, soffset);
                var sdata = new byte[slen + 4];
                Buffer.BlockCopy(cdata, soffset, sdata, 0, slen + 4);
                soffset += slen + 4;

                if (slen > 0)
                {
                    int lloffset = 0;
                    var sobj     = Deserialize(stype, sdata, ref lloffset);
                    if (sobj != null)
                    {
                        methodInvoker.Invoke(result, new object[] { sobj });
                    }
                }
                else
                {
                    methodInvoker.Invoke(result, null);
                }
            }
            return(result);
        }
コード例 #12
0
        /// <summary>
        /// 生成对应转换
        /// </summary>
        /// <param name="TSource"></param>
        /// <param name="TDest"></param>
        /// <param name="mapType"></param>
        public static void Bind(Type TSource, Type TDest, MapType mapType = MapType.PTP)
        {
            string name = TSource.FullName + "To" + TDest.FullName + "_" + mapType;

            FastInvoke fastInvok = FastInvokeCache.Instance.GetFastInvok(name, mapType);

            if (fastInvok != null)
            {
                return;
            }
            else
            {
                switch (mapType)
                {
                case MapType.PTP:
                    fastInvok = GetFastInvokPTP(TDest, TSource);
                    break;

                case MapType.PTPI:
                    fastInvok = GetFastInvokPTPI(TDest, TSource);
                    break;

                case MapType.FTF:
                    fastInvok = GetFastInvokFTF(TDest, TSource);
                    break;

                case MapType.FTFI:
                    fastInvok = GetFastInvokFTFI(TDest, TSource);
                    break;

                case MapType.PTF_TP:
                    fastInvok = GetFastInvokPTF_TP(TDest, TSource);
                    break;

                case MapType.FPTFP:
                    fastInvok = GetFastInvokFPTFP(TDest, TSource);
                    break;

                case MapType.FPTFPI:
                    fastInvok = GetFastInvokFPTFP(TDest, TSource);
                    break;

                default:
                    fastInvok = GetFastInvokPTP(TDest, TSource);
                    break;
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// 获取委托
        /// </summary>
        /// <param name="name"></param>
        /// <param name="mapType"></param>
        /// <returns></returns>
        internal FastInvoke GetFastInvok(string name, MapType mapType)
        {
            FastInvoke fastInvoke = null;

            switch (mapType)
            {
            case MapType.PTP:
                dicPTP.TryGetValue(name, out fastInvoke);
                break;

            case MapType.PTPI:

                dicPTPI.TryGetValue(name, out fastInvoke);
                break;

            case MapType.FTF:

                dicFTF.TryGetValue(name, out fastInvoke);
                break;

            case MapType.FTFI:

                dicFTFI.TryGetValue(name, out fastInvoke);
                break;

            case MapType.PTF_TP:

                dicPTF_TP.TryGetValue(name, out fastInvoke);
                break;

            case MapType.FPTFP:

                dicFPTFP.TryGetValue(name, out fastInvoke);
                break;

            case MapType.FPTFPI:

                dicFPTFPI.TryGetValue(name, out fastInvoke);
                break;

            default:

                dicOhers.TryGetValue(name, out fastInvoke);
                break;
            }
            return(fastInvoke);
        }
コード例 #14
0
        public void MasstransitConfig(IRabbitMqBusFactoryConfigurator configurator, IContainer container, ILogger logger, IJimuBus bus, MassTransitOptions options)
        {
            //-- request handler, extract queue name from request
            var groupHandlers = _requestHandlers.GroupBy(x =>
            {
                var requestType     = x.GetTypeInfo().ImplementedInterfaces.First().GenericTypeArguments.First();
                var requestInstance = container.Resolve(requestType);
                if (requestInstance == null)
                {
                    throw new Exception($"JimuRequest: {requestType.FullName} resolve failure");
                }
                var requestQueueName = requestInstance.GetType().InvokeMember("QueueName", BindingFlags.GetProperty, null, requestInstance, null) + "";
                if (string.IsNullOrWhiteSpace(requestQueueName))
                {
                    throw new Exception($"JimuRequest: {requestType.FullName} must specify QueueName property");
                }
                return(requestQueueName);
            });


            groupHandlers.ToList().ForEach(x =>
            {
                configurator.ReceiveEndpoint(x.Key, ep =>
                {
                    logger.Debug($"MassTransitRabbitMq: RequestQueueName: { x.Key}, handler count: {x.Count()}");
                    x.ToList().ForEach(handler =>
                    {
                        var requestType     = handler.GetTypeInfo().ImplementedInterfaces.First().GenericTypeArguments.First();
                        var respType        = handler.GetTypeInfo().ImplementedInterfaces.First().GenericTypeArguments[1];
                        var handlerMethod   = typeof(HandlerExtensions).GetMethod("Handler").MakeGenericMethod(requestType);
                        var requestInstance = container.Resolve(handler);
                        var myHandlerObj    = Activator.CreateInstance(typeof(RequestHandler <,>).MakeGenericType(requestType, respType), new object[] { requestInstance, bus });
                        var requestHandler  = myHandlerObj.GetType().InvokeMember("Handler", BindingFlags.GetProperty, null, myHandlerObj, null);
                        var fastInvoker     = FastInvoke.GetMethodInvoker(handlerMethod);
                        try
                        {
                            fastInvoker.Invoke(null, new object[] { ep, requestHandler, null });
                        }
                        catch (Exception ex)
                        {
                            logger.Error($"error occure when handling RabbitMq request: {x.Key}", ex);
                        }
                    });
                });
            });
        }
コード例 #15
0
    /// <summary>
    /// 获取web函数
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public void Load(Type type)
    {
        Dictionary <string, FastInvokeHandler> dic = new Dictionary <string, FastInvokeHandler>(StringComparer.OrdinalIgnoreCase);

        MethodInfo[] methods = type.GetMethods(FastValueGetSet.AllBindingFlags);
        foreach (MethodInfo info in methods)
        {
            string    key = GetMethodInfoKey(info);
            WebMethod att = info.GetCustomAttribute(typeof(WebMethod)) as WebMethod;
            if (att != null)
            {
                FastInvokeHandler handle = FastInvoke.GetMethodInvoker(info);
                dic[key] = handle;
            }
        }
        _dicMethods = dic;
    }
コード例 #16
0
        static EntityView()
        {
            cachedFields = new FasterList <KeyValuePair <Type, ActionCast <T> > >();

            var type = typeof(T);

            var fields = type.GetFields(BindingFlags.Public |
                                        BindingFlags.Instance);

            for (int i = fields.Length - 1; i >= 0; --i)
            {
                var field = fields[i];

                ActionCast <T> setter = FastInvoke <T> .MakeSetter(field);

                cachedFields.Add(new KeyValuePair <Type, ActionCast <T> >(field.FieldType, setter));
            }
        }
コード例 #17
0
 /// <summary>
 /// 通过制定Key和Exchange 订阅消息
 /// </summary>
 /// <typeparam name="T">消息类型</typeparam>
 /// <typeparam name="TH">消息消费类型</typeparam>
 /// <param name="subkey">消息路由键</param>
 /// <param name="brokerName">交换机名称</param>
 public void AddSubscription <T, TH>(string subkey, string brokerName)
     where T : IMQEvent
     where TH : IEventHandler <T>
 {
     lock (_subInfos)
     {
         var eventkey = GetEventKey <T>();
         var flag     = _subInfos.Exists(x => !x.IsDynamic && x.SubKey == subkey && x.EventKey == eventkey && x.HandlerType == typeof(TH) && x.EventType == typeof(T) && x.BrokerName == brokerName);
         if (!flag)
         {
             var method  = typeof(TH).GetMethod("Handle", new Type[] { typeof(T) });
             var handler = FastInvoke.GetMethodInvoker(method);
             var info    = SubscriptionInfo.Typed(subkey, eventkey, typeof(TH), typeof(T), handler, brokerName);
             _subInfos.Add(info);
         }
     }
     SubMessage(subkey, brokerName);
 }
コード例 #18
0
        private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate)
        {
            var serviceId         = _serviceIdGenerator.GenerateServiceId(method);
            var attributes        = method.GetCustomAttributes().ToList();
            var serviceDescriptor = new ServiceDescriptor
            {
                Id        = serviceId,
                RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name)
            };

            var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>();

            foreach (var descriptorAttribute in descriptorAttributes)
            {
                descriptorAttribute.Apply(serviceDescriptor);
            }
            serviceDescriptor.EnableAuthorization(!serviceDescriptor.EnableAuthorization()
                ? attributes.Any(p => p is AuthorizationFilterAttribute) :
                                                  serviceDescriptor.EnableAuthorization());
            var fastInvoker = FastInvoke.GetMethodInvoker(method);

            return(new ServiceEntry
            {
                Descriptor = serviceDescriptor,
                Attributes = attributes,
                Func = (key, parameters) =>
                {
                    var instance = _serviceProvider.GetInstances(key, method.DeclaringType);
                    var list = new List <object>();

                    foreach (var parameterInfo in method.GetParameters())
                    {
                        var value = parameters[parameterInfo.Name];
                        var parameterType = parameterInfo.ParameterType;
                        var parameter = _typeConvertibleService.Convert(value, parameterType);
                        list.Add(parameter);
                    }
                    var result = fastInvoker(instance, list.ToArray()); //method.Invoke(instance, list.ToArray());
                    return Task.FromResult(result);
                }
            });
        }
コード例 #19
0
        /// <summary>
        /// 获取该控件的默认绑定属性名
        /// </summary>
        /// <param name="ctr">控件</param>
        /// <returns></returns>
        private static string GetContorlBinderName(Control ctr)
        {
            Type type = ctr.GetType();

            PropertyInfo[] destproper = type.GetProperties();
            //int index = 0;
            ///读取属性别名
            foreach (PropertyInfo pinf in destproper)
            {
                object att = FastInvoke.GetPropertyAttribute(pinf, typeof(BindableAttribute));
                if (att != null)
                {
                    if (((BindableAttribute)att).Bindable)
                    {
                        return(pinf.Name);
                    }
                }
            }
            return(null);
        }
コード例 #20
0
        private async Task RemoteExecuteAsync(ServiceEntry entry, HttpMessage httpMessage, HttpResultMessage <object> resultMessage)
        {
            var provider = _concurrent.GetValueOrDefault(httpMessage.RoutePath);
            var list     = new List <object>();

            if (provider.Item1 == null)
            {
                provider.Item2 = ServiceLocator.GetService <IServiceProxyFactory>().CreateProxy(httpMessage.ServiceKey, entry.Type);
                provider.Item3 = provider.Item2.GetType().GetTypeInfo().DeclaredMethods.Where(p => p.Name == entry.MethodName).FirstOrDefault();;
                provider.Item1 = FastInvoke.GetMethodInvoker(provider.Item3);
                _concurrent.GetOrAdd(httpMessage.RoutePath, ValueTuple.Create <FastInvokeHandler, object, MethodInfo>(provider.Item1, provider.Item2, provider.Item3));
            }
            foreach (var parameterInfo in provider.Item3.GetParameters())
            {
                var value         = httpMessage.Parameters[parameterInfo.Name];
                var parameterType = parameterInfo.ParameterType;
                var parameter     = _typeConvertibleService.Convert(value, parameterType);
                list.Add(parameter);
            }
            var methodResult = provider.Item1(provider.Item2, list.ToArray());

            var task = methodResult as Task;

            if (task == null)
            {
                resultMessage.Entity    = methodResult;
                resultMessage.IsSucceed = resultMessage.Entity != null;
            }
            else
            {
                await task;
                var   taskType = task.GetType().GetTypeInfo();
                if (taskType.IsGenericType)
                {
                    resultMessage.Entity = taskType.GetProperty("Result").GetValue(task);
                }
                resultMessage.IsSucceed = resultMessage.Entity != null;
            }
        }
コード例 #21
0
ファイル: RPCReversal.cs プロジェクト: nygula/SAEA
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private static object ReversalMethod(object obj, MethodInfo method, object[] args)
        {
            object result = null;

            try
            {
                var inputs = args;

                var @params = method.GetParameters();

                if (@params == null || @params.Length == 0)
                {
                    inputs = null;
                }
                result = FastInvoke.Do(obj, method, inputs);
            }
            catch (Exception ex)
            {
                throw new RPCPamarsException($"{obj}/{method.Name},用户自定义业务代码出现异常:{ex.Message}", ex);
            }
            return(result);
        }
コード例 #22
0
ファイル: LSLScriptInstance.cs プロジェクト: jhurliman/simian
        public void Init(byte[] scriptBinary, LSLScriptInstance instance)
        {
            m_instance = instance;

            // Load the assembly into this AppDomain and create an instance of the
            // SecondLife.Script class (the main script class)
            Assembly scriptAssembly = Assembly.Load(scriptBinary);

            m_script = scriptAssembly.CreateInstance("SecondLife.Script") as LSLScriptBase;
            m_script.Init(this);

            // Create a dictionary of FastInvoke delegates for each method in the script
            MethodInfo[] methodInfos = m_script.GetType().GetMethods();
            m_methods = new Dictionary <string, FastInvokeDelegate>();
            for (int i = 0; i < methodInfos.Length; i++)
            {
                if (methodInfos[i].Module.Assembly == scriptAssembly)
                {
                    m_methods.Add(methodInfos[i].Name, FastInvoke.Create(methodInfos[i]));
                }
            }
        }
コード例 #23
0
        private ServiceEntry Create(MethodInfo method)
        {
            var serviceId = _serviceIdGenerator.GenerateServiceId(method);

            var serviceDescriptor = new ServiceDescriptor
            {
                Id = serviceId,
            };
            var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>();

            foreach (var descriptorAttribute in descriptorAttributes)
            {
                descriptorAttribute.Apply(serviceDescriptor);
            }
            var fastInvoker = FastInvoke.GetMethodInvoker(method);

            return(new ServiceEntry
            {
                Descriptor = serviceDescriptor,
                Attributes = method.GetCustomAttributes().ToList(),
                Func = (key, parameters) =>
                {
                    var instance = _serviceProvider.GetInstances(key, method.DeclaringType);
                    var list = new List <object>();

                    foreach (var parameterInfo in method.GetParameters())
                    {
                        var value = parameters[parameterInfo.Name];
                        var parameterType = parameterInfo.ParameterType;
                        var parameter = _typeConvertibleService.Convert(value, parameterType);
                        list.Add(parameter);
                    }

                    var result = fastInvoker(instance, list.ToArray()); //method.Invoke(instance, list.ToArray());
                    return Task.FromResult(result);
                }
            });
        }
コード例 #24
0
        private void Add(MethodInfo m, string ctl_name, Type ctl_type, bool isTask)
        {
            var sb = new StringBuilder();

            sb.Append('/');
            sb.Append(ctl_name);
            sb.Append('/');
            sb.Append(m.Name);
            var key  = sb.ToString();
            var info = new ActionInfo()
            {
                ControllerType = ctl_type,
                Method         = FastInvoke.GetMethodInvoker(m),
                InAags         = m.GetParameters()
            };

            info.SetReturnType(m.ReturnType, isTask);
            if (info.IsTask)
            {
                info.SetResGetter();
            }
            actionsDic.Add(key, info);
        }
コード例 #25
0
ファイル: CommandPattern.cs プロジェクト: yanh19930226/jimu
        public void MasstransitConfig(IRabbitMqBusFactoryConfigurator configurator, IContainer container, ILogger logger, IJimuBus bus, MassTransitOptions options)
        {
            //-- command consumer, extract queue name from command
            var groupConsumers = _consumers.GroupBy(x =>
            {
                var commandType     = x.GetTypeInfo().ImplementedInterfaces.First().GenericTypeArguments.First();
                var commandInstance = container.Resolve(commandType);
                if (commandInstance == null)
                {
                    throw new Exception($"JimuCommand: {commandType.FullName} resolve failure");
                }
                var commandQueueName = commandInstance.GetType().InvokeMember("QueueName", BindingFlags.GetProperty, null, commandInstance, null) + "";
                if (string.IsNullOrWhiteSpace(commandQueueName))
                {
                    throw new Exception($"JimuCommand: {commandType.FullName} must specify QueueName property");
                }
                return(commandQueueName);
            });

            groupConsumers.ToList().ForEach(x =>
            {
                configurator.ReceiveEndpoint(x.Key, ep =>
                {
                    logger.Debug($"MassTransitRabbitMq: CommandQueueName: { x.Key}, consumers count: {x.Count()}");
                    x.ToList().ForEach(consumer =>
                    {
                        var commandType      = consumer.GetTypeInfo().ImplementedInterfaces.First().GenericTypeArguments.First();
                        var handlerMethod    = typeof(HandlerExtensions).GetMethod("Handler").MakeGenericMethod(commandType);
                        var consumerInstance = container.Resolve(consumer);
                        var myHandlerObj     = Activator.CreateInstance(typeof(CommandHandler <>).MakeGenericType(commandType), new object[] { consumerInstance, bus });
                        var consumerHandler  = myHandlerObj.GetType().InvokeMember("Handler", BindingFlags.GetProperty, null, myHandlerObj, null);
                        var fastInvoker      = FastInvoke.GetMethodInvoker(handlerMethod);
                        fastInvoker.Invoke(null, new object[] { ep, consumerHandler, null });
                    });
                });
            });
        }
コード例 #26
0
        /// <summary>
        /// 添加委托
        /// </summary>
        /// <param name="name"></param>
        /// <param name="mapType"></param>
        /// <param name="fastInvok"></param>
        internal void Add(string name, MapType mapType, FastInvoke fastInvok)
        {
            switch (mapType)
            {
            case MapType.PTP:
                dicPTP[name] = fastInvok;
                break;

            case MapType.PTPI:
                dicPTPI[name] = fastInvok;
                break;

            case MapType.FTF:
                dicFTF[name] = fastInvok;
                break;

            case MapType.FTFI:
                dicFTFI[name] = fastInvok;
                break;

            case MapType.PTF_TP:
                dicPTF_TP[name] = fastInvok;
                break;

            case MapType.FPTFP:
                dicFPTFP[name] = fastInvok;
                break;

            case MapType.FPTFPI:
                dicFPTFPI[name] = fastInvok;
                break;

            default:
                dicOhers[name] = fastInvok;
                break;
            }
        }
コード例 #27
0
            public int Compare(object x, object y)
            {
                if (fastInvoker == null)
                {
                    var propInfo = x.GetType().GetProperty(sortBy);
                    fastInvoker = FastInvoke.GetMethodInvoker(propInfo.GetGetMethod());
                }
                var x1 = fastInvoker.Invoke(x, null) as IComparable;
                var y1 = fastInvoker.Invoke(y, null) as IComparable;

                if (x1 == null || y1 == null)
                {
                    return(0);
                }
                else
                {
                    var result = x1.CompareTo(y1);
                    if (direction == ListSortDirection.Descending)
                    {
                        result = -result;
                    }
                    return(result);
                }
            }
コード例 #28
0
ファイル: PublicSubscribePattern.cs プロジェクト: wnttmk/jimu
        public void MasstransitConfig(IRabbitMqBusFactoryConfigurator configurator, IContainer container, ILogger logger, IJimuBus bus, MassTransitOptions _options)
        {
            if (_subscribers.Any())
            {
                //-- event subscriber, generate default event queue, if not specify in options

                var eventQueueName = string.IsNullOrEmpty(_options.EventQueueName) ? $"{AppDomain.CurrentDomain.FriendlyName}-{Guid.NewGuid()}" : _options.EventQueueName;

                configurator.ReceiveEndpoint(eventQueueName, ep =>
                {
                    _subscribers.ForEach(subscriber =>
                    {
                        var subscriberType     = subscriber.GetTypeInfo().ImplementedInterfaces.First().GenericTypeArguments.First();
                        var handlerMethod      = typeof(HandlerExtensions).GetMethod("Handler").MakeGenericMethod(subscriberType);
                        var subscriberInstance = container.Resolve(subscriber);
                        var myHandlerObj       = Activator.CreateInstance(typeof(EventHandler <>).MakeGenericType(subscriberType), new object[] { subscriberInstance, bus });
                        var eventHandler       = myHandlerObj.GetType().InvokeMember("Handler", BindingFlags.GetProperty, null, myHandlerObj, null);
                        var fastInvoker        = FastInvoke.GetMethodInvoker(handlerMethod);
                        fastInvoker.Invoke(null, new object[] { ep, eventHandler, null });
                    });
                });
                logger.Debug($"MassTransitRabbitMq: EventQueueName: { eventQueueName}, subscribers count: {_subscribers.Count()}");
            }
        }
コード例 #29
0
 /// <summary>
 /// 初始化代理类
 /// </summary>
 internal void InitProxyType(EntityProxyBuilder proxyBuilder)
 {
     _proxyType = proxyBuilder.CreateProxyType(_entityType);
     _createProxyInstanceHandler = FastInvoke.GetInstanceCreator(_proxyType);
 }
コード例 #30
0
        static public bool Prefix(SpellBookMemorizingPanel __instance, ref bool ___m_IsInit, ref List <SpellSlotItem> ___m_CommonSpellSlots, ref SpellSlotItem[] ___m_SpecialSpellSlots, ref Transform ___m_SpecialSlotsContainer, ref TextMeshProUGUI ___m_LabelSpecialSlots, ref Image ___m_SpecialSlotsBackground)
        {
            // *******************
            // This check: check if this spellbook belongs to arcanist.
            // *******************
            if (Game.Instance.UI.SpellBookController.CurrentSpellbook.Blueprint.CharacterClass != Main.arcanist)
            {
                return(true);
            }

            var        spellBookController = Game.Instance.UI.SpellBookController;
            var        spellBook           = spellBookController.CurrentSpellbook;
            var        currentLevel        = spellBookController.CurrentBookLevel;
            var        t = Game.Instance.BlueprintRoot.LocalizedTexts.UserInterfacesText.SpellBookTexts;
            FastInvoke SubstituteText_Invoker = Helpers.CreateInvoker <SpellBookMemorizingPanel>("SubstituteText");

            spellBook.Blueprint.Spontaneous = false;

            if (!___m_IsInit)
            {
                return(false);
            }
            bool returnValue = (bool)SubstituteText_Invoker(__instance);

            UnityModManager.Logger.Log($"SubstituteText invoker returns {returnValue}");
            if (returnValue)
            {
                return(false);
            }
            if (currentLevel < 0 || currentLevel > spellBookController.MaxCasterLevel)
            {
                return(false);
            }
            if (spellBookController.CurrentSpellbook == null)
            {
                return(false);
            }
            foreach (SpellSlotItem spellSlotItem in ___m_CommonSpellSlots)
            {
                spellSlotItem.DeactivateSlotItem();
                spellSlotItem.SetActive(true);
            }
            foreach (SpellSlotItem spellSlotItem2 in ___m_SpecialSpellSlots)
            {
                spellSlotItem2.DeactivateSlotItem();
                spellSlotItem2.SetActive(false);
            }
            //
            // *********************
            // Patch Start
            // [num] controls how many normal slot of tier [currentLevel] spell has.
            // For arcanists, we have to switch this to her known spell slot number.
            // *********************
            int num;

            num = ArcanistPatch_Helpers.getArcanistMemorizeSlotCnt(currentLevel);
            //num = spellBookController.CurrentSpellbook.CalcSlotsLimit(currentLevel, SpellSlotType.Common);
            // *********************
            // Patch End
            // *********************
            int num2 = spellBookController.CurrentSpellbook.CalcSlotsLimit(currentLevel, SpellSlotType.Favorite);

            foreach (SpellSlotItem spellSlotItem3 in ___m_CommonSpellSlots)
            {
                spellSlotItem3.DeactivateSlotItem();
            }
            int[] array = new int[]
            {
                0,
                0,
                0
            };
            int num3 = (num <= 8) ? 2 : 3;
            int num4 = (int)Mathf.Floor((float)(num / num3));
            int num5 = num % num3;

            if (num > 8)
            {
                array[1] = num4 + num5;
                array[0] = num4;
                array[2] = num4;
            }
            else if (num > 1)
            {
                array[0] = num4 + num5;
                array[1] = num4;
            }
            else if (num > 0)
            {
                array[0] = 1;
            }
            int num6 = 0;

            foreach (int num7 in array)
            {
                for (int k = 0; k < num7; k++)
                {
                    int index = num6 * ___m_CommonSpellSlots.Count / 3 + k;
                    ___m_CommonSpellSlots[index].ActivateSlotItem(SpellSlotType.Common);
                }
                num6++;
            }
            if (___m_SpecialSpellSlots.Length > 0 && num2 > 0)
            {
                ___m_SpecialSlotsContainer.gameObject.SetActive(true);
                if (spellBookController.CurrentSpellbook.Blueprint.CantripsType == CantripsType.Orisions)
                {
                    ___m_LabelSpecialSlots.text       = t.DomainSlots;
                    ___m_SpecialSlotsBackground.color = BlueprintRoot.Instance.UIRoot.SpellBookColors.DomainSlotColor;
                }
                else
                {
                    ___m_LabelSpecialSlots.text       = t.FavoriteSchoolSlots;
                    ___m_SpecialSlotsBackground.color = BlueprintRoot.Instance.UIRoot.SpellBookColors.FavoriteSlotColor;
                }
                foreach (SpellSlotItem spellSlotItem4 in ___m_SpecialSpellSlots)
                {
                    if (num2 <= 0)
                    {
                        break;
                    }
                    SpellSlotType type = (spellBookController.CurrentSpellbook.Blueprint.CantripsType != CantripsType.Orisions) ? SpellSlotType.Favorite : SpellSlotType.Domain;
                    spellSlotItem4.ActivateSlotItem(type);
                    num2--;
                }
            }
            else
            {
                ___m_SpecialSlotsContainer.gameObject.SetActive(false);
            }
            IEnumerable <SpellSlot> memorizedSpellSlots = spellBookController.CurrentSpellbook.GetMemorizedSpellSlots(currentLevel);

            foreach (SpellSlot spellMechanicSlot in memorizedSpellSlots)
            {
                __instance.AddSlot(spellMechanicSlot);
            }

            spellBook.Blueprint.Spontaneous = true;
            return(false);
        }