Пример #1
0
        /// <summary>
        /// 返回一个储存了指定类型的反射信息的 ReflectInfo 类
        /// </summary>
        virtual public ReflectionInfo Create(Type type)
        {
            // 新建一个 ReflectionInfo 类
            var reflectionInfo = new ReflectionInfo();

            // 获取 ReflectInfo 类的信息
            reflectionInfo.type = type;
            var constructor = this.GetPreferredConstructor(type);

            // 由于带参数和不带参数的构造函数委托类型不同,将筛选构造函数的过程封装为一个独立的方法将带来不必要的装、拆箱步骤,所以直接在方法内处理
            if (constructor != null)
            {
                if (constructor.GetParameters().Length == 0)
                {
                    reflectionInfo.constructor = MethodUtils.CreateConstructor(type, constructor);
                }
                else
                {
                    reflectionInfo.paramsConstructor = MethodUtils.CreateConstructorWithParams(type, constructor);
                }
            }

            reflectionInfo.constructorParameters = GetConstructorParameters(constructor);
            reflectionInfo.methods    = GetMethods(type);
            reflectionInfo.properties = GetProperties(type);
            reflectionInfo.fields     = GetFields(type);

            return(reflectionInfo);
        }
Пример #2
0
 private static bool IsValidListContainsCall([NotNull] MethodCallExpression node)
 {
     return(MethodUtils.IsOperator(node.Method, MethodUtils.ListContains) &&
            node.Object != null &&
            node.Object.NodeType == ExpressionType.Constant &&
            node.Arguments[0].NodeType == ExpressionType.MemberAccess);
 }
Пример #3
0
        /// <summary>
        /// 返回接受注入的字段信息 : type 为 key,object 为 id, PropertyInfo 为值
        /// </summary>
        virtual protected SetterInfo[] GetFields(Type type)
        {
            var setters = new List <SetterInfo>();

            // 获取参数 type 的属性
            var fields = type.GetFields(
                BindingFlags.Instance |
                BindingFlags.Static |
                BindingFlags.NonPublic |
                BindingFlags.Public);

            for (int i = 0; i < fields.Length; i++)
            {
                var field      = fields[i] as FieldInfo;
                var attributes = field.GetCustomAttributes(typeof(Inject), true);

                if (attributes.Length > 0)
                {
                    var attribute = attributes[0] as Inject;
                    var method    = MethodUtils.CreateFieldSetter(type, field);
                    var info      = new SetterInfo(field.FieldType, attribute.id, method);
                    setters.Add(info);
                }
            }

            return(setters.ToArray());
        }
Пример #4
0
        /// <summary>
        /// Resolves the properties that can be injected.
        /// </summary>
        /// <param name="type">Type from which reflection will be resolved.</param>
        /// <returns>The properties.</returns>
        protected AcessorInfo[] ResolveProperties(Type type)
        {
            var setters = new List <AcessorInfo>();

            var properties = type.GetProperties(BindingFlags.Instance |
                                                BindingFlags.Static |
                                                BindingFlags.Public |
                                                BindingFlags.NonPublic);

            for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex++)
            {
                var property   = properties[propertyIndex] as PropertyInfo;
                var attributes = property.GetCustomAttributes(typeof(Inject), true);

                if (attributes.Length > 0)
                {
                    var attribute = attributes[0] as Inject;
                    var getter    = MethodUtils.CreatePropertyGetter(type, property);
                    var setter    = MethodUtils.CreatePropertySetter(type, property);
                    var info      = new AcessorInfo(property.PropertyType, property.Name, attribute.identifier, getter,
                                                    setter);
                    setters.Add(info);
                }
            }

            return(setters.ToArray());
        }
Пример #5
0
        /// <summary>
        /// Creates a <see cref="ReflectedClass"/> from a <paramref name="type"/>.
        /// </summary>
        /// <param name="type">Type from which the reflected class will be created.</param>
        public ReflectedClass Create(Type type)
        {
            var reflectedClass = new ReflectedClass();

            reflectedClass.type = type;

            var constructor = this.ResolveConstructor(type);

            if (constructor != null)
            {
                if (constructor.GetParameters().Length == 0)
                {
                    reflectedClass.constructor = MethodUtils.CreateConstructor(type, constructor);
                }
                else
                {
                    reflectedClass.paramsConstructor = MethodUtils.CreateConstructorWithParams(type, constructor);
                    ;
                }
            }

            reflectedClass.constructorParameters = this.ResolveConstructorParameters(constructor);
            reflectedClass.methods    = this.ResolveMethods(type);
            reflectedClass.properties = this.ResolveProperties(type);
            reflectedClass.fields     = this.ResolveFields(type);

            return(reflectedClass);
        }
Пример #6
0
        /// <summary>
        /// Resolves the fields that can be injected.
        /// </summary>
        /// <param name="type">Type from which reflection will be resolved.</param>
        /// <returns>The fields.</returns>
        protected AcessorInfo[] ResolveFields(Type type)
        {
            var setters = new List <AcessorInfo>();

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

            for (int fieldIndex = 0; fieldIndex < fields.Length; fieldIndex++)
            {
                var field      = fields[fieldIndex] as FieldInfo;
                var attributes = field.GetCustomAttributes(typeof(Inject), true);

                if (attributes.Length > 0)
                {
                    var attribute = attributes[0] as Inject;
                    var getter    = MethodUtils.CreateFieldGetter(type, field);
                    var setter    = MethodUtils.CreateFieldSetter(type, field);
                    var info      = new AcessorInfo(field.FieldType, field.Name, attribute.identifier, getter, setter);
                    setters.Add(info);
                }
            }

            return(setters.ToArray());
        }
Пример #7
0
        public void OnReceived(Pipe.Request request, byte[] buffer, int length)
        {
            try {
                var data      = Encoding.UTF8.GetString(buffer);
                var arguments = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);
                if ((arguments == null) || (!arguments.ContainsKey("method")))
                {
                    buffer = GetResponse(false, "invalid arguments!");
                    pipe?.Send(buffer, 0, buffer.Length, null);
                    return;
                }

                arguments.Add("context", this);
                var result = MethodUtils.Invoke(GetType(), arguments["method"] as string, arguments);
                if (result != null)
                {
                    buffer = GetResponse(true, result);
                    pipe?.Send(buffer, 0, buffer.Length, null);
                }
            }
            catch (Exception e) {
                buffer = GetResponse(false, e.Message);
                pipe?.Send(buffer, 0, buffer.Length, null);
                Tracker.LogE(e);
            }
        }
 private WhereModel TranslateCall([NotNull] MethodCallExpression callNode)
 {
     if (MethodUtils.IsOperator(callNode.Method, MethodUtils.EContains))
     {
         return(new ComparisonModel(ComparisonOperator.ContainsOrIncludes,
                                    CamlProcessorUtils.GetFieldRef(callNode.Arguments[0]),
                                    GetValue(callNode.Arguments[1])));
     }
     if (MethodUtils.IsOperator(callNode.Method, MethodUtils.ListContains))
     {
         return(new ComparisonModel(ComparisonOperator.ContainsOrIncludes,
                                    CamlProcessorUtils.GetFieldRef(callNode.Object),
                                    GetValue(callNode.Arguments[0])));
     }
     if (callNode.Method == MethodUtils.StrContains)
     {
         return(TranslateStrContains(callNode));
     }
     if (callNode.Method == MethodUtils.StrStartsWith)
     {
         return(TranslateStrStartsWith(callNode));
     }
     if (callNode.Method.Name == "Contains" &&
         callNode.Object != null &&
         (callNode.Object.Type.IsArray || callNode.Object.Type.IsIEnumerable()) &&
         callNode.Arguments.Count == 1)
     {
         return(new ComparisonModel(ComparisonOperator.ContainsOrIncludes,
                                    CamlProcessorUtils.GetFieldRef(callNode.Object),
                                    GetValue(callNode.Arguments[0])));
     }
     throw Error.SubqueryNotSupported(callNode);
 }
Пример #9
0
        /// <summary>
        /// 返回接受注入的属性信息 : type 为 key,object 为 id, PropertyInfo 为值
        /// </summary>
        virtual protected SetterInfo[] GetProperties(Type type)
        {
            var setters = new List <SetterInfo>();

            // 获取参数 type 的属性
            var properties = type.GetProperties(
                BindingFlags.Instance |
                BindingFlags.Static |
                BindingFlags.NonPublic |
                BindingFlags.Public);

            for (int i = 0; i < properties.Length; i++)
            {
                var property   = properties[i] as PropertyInfo;
                var attributes = property.GetCustomAttributes(typeof(Inject), true);

                if (attributes.Length > 0)
                {
                    var attribute = attributes[0] as Inject;
                    var method    = MethodUtils.CreatePropertySetter(type, property);
                    var info      = new SetterInfo(property.PropertyType, attribute.id, method);
                    setters.Add(info);
                }
            }

            return(setters.ToArray());
        }
Пример #10
0
        public void Initialize()
        {
            _container = new Container();
            var factoryMethod = MethodUtils.GetMethodInfo(() => EventAggregators.Default(null));

            _container.RegisterType <IEventAggregator>(Constructors.StaticFactory(factoryMethod));
            _value = 0;
        }
Пример #11
0
        /// <summary>
        /// 获取指定类型注入后需要执行的方法的信息类
        /// </summary>
        virtual protected ToluaContainer.Container.MethodInfo[] GetMethods(Type type)
        {
            var parameterlessMethods = new List <ToluaContainer.Container.MethodInfo>();
            // 获取参数 type 中的方法
            var methods = type.GetMethods(
                BindingFlags.FlattenHierarchy |
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance);

            for (int i = 0; i < methods.Length; i++)
            {
                var method = methods[i];

                // 获取方法是否附着有[Inject]特性
                var attributes = method.GetCustomAttributes(typeof(Inject), true);
                if (attributes.Length > 0)
                {
                    // 如果获取成功,继续获取方法的参数,并获取它们的 id,用它们构造 ParameterInfo 类
                    var parameters       = method.GetParameters();
                    var methodParameters = new ParameterInfo[parameters.Length];
                    for (int n = 0; n < methodParameters.Length; n++)
                    {
                        object id        = null;
                        var    parameter = parameters[n];

                        var parameterAttributes = parameter.GetCustomAttributes(typeof(Inject), true);
                        if (parameterAttributes.Length > 0)
                        {
                            id = (parameterAttributes[0] as Inject).id;
                        }

                        methodParameters[n] = new ParameterInfo(parameter.ParameterType, id);
                    }

                    var parameterlessMethod = new ToluaContainer.Container.MethodInfo(methodParameters);

                    // 根据参数个数创建方法委托
                    if (methodParameters.Length == 0)
                    {
                        parameterlessMethod.method = MethodUtils.CreateParameterlessMethod(type, method);
                    }
                    else
                    {
                        parameterlessMethod.paramsMethod = MethodUtils.CreateParameterizedMethod(type, method);
                    }

                    // 将方法委托加入数组
                    parameterlessMethods.Add(parameterlessMethod);
                }
            }

            // 以数组形式返回
            return(parameterlessMethods.ToArray());
        }
Пример #12
0
        /// <summary>
        /// Resolves the methods that can be injected.
        /// </summary>
        /// <returns>The methods with Inject attributes.</returns>
        #pragma warning disable 0618
        protected MethodInfo[] ResolveMethods(Type type)
        {
            var methodCalls = new List <MethodInfo>();

            var methods = type.GetMethods(BindingFlags.FlattenHierarchy |
                                          BindingFlags.Public |
                                          BindingFlags.NonPublic |
                                          BindingFlags.Instance);

            for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++)
            {
                var method = methods[methodIndex];

                // PostConstruct attribute will be removed on future version.
                var attributesPostConstruct = method.GetCustomAttributes(typeof(PostConstruct), true);
                var attributesInject        = method.GetCustomAttributes(typeof(Inject), true);

                if (attributesPostConstruct.Length > 0 || attributesInject.Length > 0)
                {
                    var parameters       = method.GetParameters();
                    var methodParameters = new ParameterInfo[parameters.Length];
                    for (int paramIndex = 0; paramIndex < methodParameters.Length; paramIndex++)
                    {
                        object identifier = null;
                        var    parameter  = parameters[paramIndex];

                        var parameterAttributes = parameter.GetCustomAttributes(typeof(Inject), true);
                        if (parameterAttributes.Length > 0)
                        {
                            identifier = (parameterAttributes[0] as Inject).identifier;
                        }

                        methodParameters[paramIndex] = new ParameterInfo(parameter.ParameterType, parameter.Name, identifier);
                    }

                    var methodCall = new MethodInfo(method.Name, methodParameters);

                    if (methodParameters.Length == 0)
                    {
                        methodCall.method = MethodUtils.CreateParameterlessMethod(type, method);
                    }
                    else
                    {
                        methodCall.paramsMethod = MethodUtils.CreateParameterizedMethod(type, method);
                    }

                    methodCalls.Add(methodCall);
                }
            }

            return(methodCalls.ToArray());
        }
Пример #13
0
        /// <summary>
        /// Resolves the post constructors for the type.
        /// </summary>
        /// <returns>The post constructors.</returns>
        protected PostConstructorInfo[] ResolvePostConstructors(Type type)
        {
            var postConstructors = new List <PostConstructorInfo>();

            var methods = type.GetMethods(BindingFlags.FlattenHierarchy |
                                          BindingFlags.Public |
                                          BindingFlags.NonPublic |
                                          BindingFlags.Instance);

            for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++)
            {
                var method = methods[methodIndex];

                var attributes = method.GetCustomAttributes(typeof(PostConstruct), true);
                if (attributes.Length > 0)
                {
                    var parameters = method.GetParameters();
                    var postConstructorParameters = new ParameterInfo[parameters.Length];
                    for (int paramIndex = 0; paramIndex < postConstructorParameters.Length; paramIndex++)
                    {
                        object identifier = null;
                        var    parameter  = parameters[paramIndex];

                        var parameterAttributes = parameter.GetCustomAttributes(typeof(Inject), true);
                        if (parameterAttributes.Length > 0)
                        {
                            identifier = (parameterAttributes[0] as Inject).identifier;
                        }

                        postConstructorParameters[paramIndex] = new ParameterInfo(parameter.ParameterType, identifier);
                    }

                    var postConstructor = new PostConstructorInfo(postConstructorParameters);

                    if (postConstructorParameters.Length == 0)
                    {
                        postConstructor.postConstructor = MethodUtils.CreateParameterlessMethod(type, method);
                    }
                    else
                    {
                        postConstructor.paramsPostConstructor = MethodUtils.CreateParameterizedMethod(type, method);
                    }

                    postConstructors.Add(postConstructor);
                }
            }

            return(postConstructors.ToArray());
        }
        public override IDbConnection CreateMsSqlConnection(string connectionString)
        {
            if (MsSqlFunc == null)
            {
                lock (SyncObj)
                {
                    if (MsSqlFunc == null)
                    {
                        var type = Type.GetType("System.Data.SqlClient.SqlConnection,System.Data.SqlClient");
                        AssertUtils.IsNotNull(type, "请添加System.Data.SqlClient组件");
                        MsSqlFunc = MethodUtils.CreateInstanceDelegate <Func <string, IDbConnection> >(type, new Type[] { typeof(string) });
                    }
                }
            }

            return(MsSqlFunc(connectionString));
        }
Пример #15
0
        public void GetFunc()
        {
            var resultInstance = new TypeValuePair(typeof(int), 12345);

            TypeValuePair Get <T>(T input) => resultInstance;

            var result = MethodUtils.MakeMatchArg(Get, typeof(string));

            var resolvedMethod = result
                                 .Should()
                                 .BeOfType <Func <string, TypeValuePair> >()
                                 .Which;
            var typePairResult = resolvedMethod
                                 .Invoke("Test");

            typePairResult.Should().BeEquivalentTo(resultInstance);
        }
Пример #16
0
        public void GetAction()
        {
            bool called = false;

            void Get <T>(T input) => called = true;

            var result = MethodUtils.MakeAction(Get, typeof(string));

            var resolvedMethod = result
                                 .Should()
                                 .BeOfType <Action <string> >()
                                 .Which;

            resolvedMethod
            .Invoke("Test");

            called.Should().BeTrue();
        }
        private void RecordInvocation(IMethodSymbol invokedMethodSymbol, SyntaxNode methodInvocationNode, ArgumentListSyntax methodArguments)
        {
            var argumentNodeToMethodParameter = new Dictionary <SyntaxNodeOrToken, (string parameterName, ITypeSymbol parameterType)>();

            if (methodArguments != null)
            {
                foreach (var arg in methodArguments.Arguments)
                {
                    var paramSymbol = MethodUtils.DetermineParameter(methodArguments, arg, invokedMethodSymbol);
                    Debug.Assert(arg.Expression != null);
                    Debug.Assert(paramSymbol != null);
                    argumentNodeToMethodParameter.Add(arg.Expression, (paramSymbol.Name, paramSymbol.Type));
                }
            }

            var invocationInfo = new MethodInvocationInformation(invokedMethodSymbol, methodInvocationNode, argumentNodeToMethodParameter);

            _graph.MethodInvocationSites.Add(invocationInfo);
        }
        public override IDbConnection CreateMySqlConnection(string connectionString)
        {
            if (MySqlFunc == null)
            {
                lock (SyncObj)
                {
                    if (MySqlFunc == null)
                    {
                        var type = Type.GetType("MySql.Data.MySqlClient.MySqlConnection,MySql.Data");
                        AssertUtils.IsNotNull(type, "请添加MySql.Data组件");
                        var MySqlConstructor = type.GetConstructor(new Type[] { typeof(string) });
                        // Activator.CreateInstance
                        // return MySqlCons tructor.Invoke(new object[] { connectionString }) as IDbConnection;
                        MySqlFunc = MethodUtils.CreateInstanceDelegate <Func <string, IDbConnection> >(type, new Type[] { typeof(string) });
                    }
                }
            }

            return(MySqlFunc(connectionString));
        }
Пример #19
0
 private BranchStepInfo getBranchStepInfo(StepCallback branchStep)
 {
     return(_cachedBranchStepInfos.GetOrAdd(branchStep.Method, (method) =>
     {
         var methodName = method.Name;
         var compensableAttr = MethodUtils.GetDeclaredAttribute <Compensable>(method, typeof(Compensable));
         var branchServiceKey = _sagaResolver.GetServiceKey(method.DeclaringType, methodName);
         var branchCompensationServiceKey = "";
         if (compensableAttr != null)
         {
             var compensationMethodName = (compensableAttr as Compensable).ActionName;
             branchCompensationServiceKey = _sagaResolver.GetServiceKey(method.DeclaringType, compensationMethodName);
         }
         return new BranchStepInfo()
         {
             BranchServiceKey = branchServiceKey,
             BranchCompensationServiceKey = branchCompensationServiceKey
         };
     }));
 }
Пример #20
0
        public async Task <Message> Invoke(Message message)
        {
            var result = message.CopyToResponse();
            //找到本地方法 调用
            byte   serializeType = message.SerializeType;
            string serverName    = message.ServerName;
            string methodName    = message.MessageName;

            try
            {
                ISerialize serialize   = SerializeManage.Instance.GetSerialize(serializeType);//获取序列化对象
                Type       serviceType = ServiceTypeManage.Instance.GetType(serverName);
                AssertUtils.IsNotNull(serviceType, ExceptionCode.NOTFOUND_ERROR, "服务不存在");

                object service = _rpcServiceProxyFactory.GetService(serviceType); // _serviceProvider.GetService(serviceType);
                //object service = _serviceProvider.GetService(serviceType);
                MethodInfo      methodInfo     = service.GetType().GetMethod(methodName);
                ParameterInfo[] parameterInfos = methodInfo.GetParameters();
                object[]        inParms        = null;
                if (parameterInfos.Length > 0)
                {
                    object requestObj = serialize.Deserialize(parameterInfos[0].ParameterType, message.Data);
                    inParms = new object[] { requestObj };
                }
                var callResult = await MethodUtils.InvokeMethodAsync(service, methodInfo, inParms) as RpcResult;

                AssertUtils.IsNotNull(callResult, ExceptionCode.INTETNAL_ERROR, "返回空");

                result.ReturnCode    = callResult != null ? callResult.Code : 0;
                result.ReturnMessage = callResult != null ? callResult.Message : "";

                result.Data = serialize.Serialize(GetRpcResultData(callResult));
            }
            catch (Exception ex)
            {
                result.ReturnCode    = ExceptionCode.INTETNAL_ERROR;
                result.ReturnMessage = "内部错误";
                _logger.Error($"{serverName}.{methodName}, {ex.Message},{ex.StackTrace}");
            }
            return(result);//serialize.Serialize(result);
        }
Пример #21
0
        /// <summary>
        /// 更新录像
        /// </summary>
        /// <param name="recording">录像</param>
        /// <returns>是否成功</returns>
        public static bool UpdateRecording(Recording recording)
        {
            try {
                using (var db = new RepositoyContext()) {
                    var dst = db.Set <Recording>().FirstOrDefault(a => a.id == recording.id);
                    if (dst == null)
                    {
                        return(false);
                    }

                    MethodUtils.CopyProperties(recording, ref dst);
                    db.SaveChanges();
                }

                return(true);
            }
            catch (Exception e) {
                Tracker.LogE(e);
                return(false);
            }
        }
Пример #22
0
 private static bool IsValidObjectInCall([NotNull] MethodCallExpression node)
 {
     return(MethodUtils.IsOperator(node.Method, MethodUtils.ObjIn) &&
            node.Arguments[0].NodeType == ExpressionType.MemberAccess &&
            node.Arguments[1].NodeType == ExpressionType.Constant);
 }
Пример #23
0
        public static Type CreateInterfaceProxy(Type interfaceType, Type implementType)
        {
            if (null == interfaceType)
            {
                throw new ArgumentNullException(nameof(interfaceType));
            }
            if (!interfaceType.IsInterface)
            {
                throw new InvalidOperationException($"{interfaceType.FullName} is not an interface");
            }

            if (null == implementType)
            {
                return(CreateInterfaceProxy(interfaceType));
            }

            if (implementType.IsSealed)
            {
                throw new InvalidOperationException("the implementType is sealed");
            }

            var proxyTypeName = _proxyTypeNameResolver(interfaceType, implementType);
            var type          = _proxyTypes.GetOrAdd(proxyTypeName, name =>
            {
                var typeBuilder = _moduleBuilder.DefineType(proxyTypeName, implementType.Attributes, implementType, new[] { interfaceType });
                GenericParameterUtils.DefineGenericParameter(interfaceType, typeBuilder);

                var targetField = typeBuilder.DefineField(TargetFieldName, implementType, FieldAttributes.Private);
                // constructors
                foreach (var constructor in implementType.GetConstructors())
                {
                    var constructorTypes   = constructor.GetParameters().Select(o => o.ParameterType).ToArray();
                    var constructorBuilder = typeBuilder.DefineConstructor(
                        constructor.Attributes,
                        constructor.CallingConvention,
                        constructorTypes);
                    foreach (var customAttribute in constructor.CustomAttributes)
                    {
                        constructorBuilder.SetCustomAttribute(DefineCustomAttribute(customAttribute));
                    }
                    var il = constructorBuilder.GetILGenerator();

                    il.EmitThis();
                    for (var i = 0; i < constructorTypes.Length; i++)
                    {
                        il.Emit(OpCodes.Ldarg, i + 1);
                    }
                    il.Call(constructor);

                    il.EmitThis();
                    il.EmitThis();
                    il.Emit(OpCodes.Stfld, targetField);

                    il.Emit(OpCodes.Nop);
                    il.Emit(OpCodes.Ret);
                }

                // properties
                var propertyMethods = new HashSet <string>();
                var properties      = interfaceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var property in properties)
                {
                    var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes);
                    if (property.CanRead)
                    {
                        var methodBuilder = MethodUtils.DefineInterfaceMethod(typeBuilder, property.GetMethod, targetField);
                        typeBuilder.DefineMethodOverride(methodBuilder, property.GetMethod);
                        propertyBuilder.SetGetMethod(methodBuilder);
                        propertyMethods.Add(property.GetMethod.Name);
                    }
                    if (property.CanWrite)
                    {
                        var methodBuilder = MethodUtils.DefineInterfaceMethod(typeBuilder, property.SetMethod, targetField);
                        typeBuilder.DefineMethodOverride(methodBuilder, property.SetMethod);
                        propertyBuilder.SetSetMethod(methodBuilder);
                        propertyMethods.Add(property.SetMethod.Name);
                    }
                    foreach (var customAttributeData in property.CustomAttributes)
                    {
                        propertyBuilder.SetCustomAttribute(DefineCustomAttribute(customAttributeData));
                    }
                }

                //
                var methods = interfaceType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                foreach (var method in methods)
                {
                    if (propertyMethods.Contains(method.Name) || _ignoredMethods.Contains(method.Name))
                    {
                        continue;
                    }
                    MethodUtils.DefineInterfaceMethod(typeBuilder, method, targetField);
                }

                foreach (var implementedInterface in interfaceType.GetImplementedInterfaces())
                {
                    properties = implementedInterface.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                    foreach (var property in properties)
                    {
                        var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes);
                        var field           = typeBuilder.DefineField($"_{property.Name}", property.PropertyType, FieldAttributes.Private);
                        if (property.CanRead)
                        {
                            var methodBuilder = typeBuilder.DefineMethod(property.GetMethod.Name, InterfaceMethodAttributes, property.GetMethod.CallingConvention, property.GetMethod.ReturnType, property.GetMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                            var ilGen         = methodBuilder.GetILGenerator();
                            ilGen.Emit(OpCodes.Ldarg_0);
                            ilGen.Emit(OpCodes.Ldfld, field);
                            ilGen.Emit(OpCodes.Ret);
                            typeBuilder.DefineMethodOverride(methodBuilder, property.GetMethod);
                            propertyBuilder.SetGetMethod(methodBuilder);
                            propertyMethods.Add(property.GetMethod.Name);
                        }
                        if (property.CanWrite)
                        {
                            var methodBuilder = typeBuilder.DefineMethod(property.SetMethod.Name, InterfaceMethodAttributes, property.SetMethod.CallingConvention, property.SetMethod.ReturnType, property.SetMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                            var ilGen         = methodBuilder.GetILGenerator();
                            ilGen.Emit(OpCodes.Ldarg_0);
                            ilGen.Emit(OpCodes.Ldarg_1);
                            ilGen.Emit(OpCodes.Stfld, field);
                            ilGen.Emit(OpCodes.Ret);
                            typeBuilder.DefineMethodOverride(methodBuilder, property.SetMethod);
                            propertyBuilder.SetSetMethod(methodBuilder);
                            propertyMethods.Add(property.SetMethod.Name);
                        }
                        foreach (var customAttributeData in property.CustomAttributes)
                        {
                            propertyBuilder.SetCustomAttribute(DefineCustomAttribute(customAttributeData));
                        }
                    }

                    methods = implementedInterface.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                    foreach (var method in methods.Where(x => !propertyMethods.Contains(x.Name) && !_ignoredMethods.Contains(x.Name)))
                    {
                        MethodUtils.DefineInterfaceMethod(typeBuilder, method, null);
                    }
                }

                return(typeBuilder.CreateType());
            });

            return(type);
        }
Пример #24
0
        public static Type CreateInterfaceProxy(Type interfaceType)
        {
            if (null == interfaceType)
            {
                throw new ArgumentNullException(nameof(interfaceType));
            }
            if (!interfaceType.IsInterface)
            {
                throw new InvalidOperationException($"{interfaceType.FullName} is not an interface");
            }

            var proxyTypeName = _proxyTypeNameResolver(interfaceType, null);

            if (_proxyTypes.TryGetValue(proxyTypeName, out var proxyType))
            {
                return(proxyType);
            }

            lock (_typeLock)
            {
                if (_proxyTypes.TryGetValue(proxyTypeName, out proxyType))
                {
                    return(proxyType);
                }

                var typeBuilder = _moduleBuilder.DefineType(proxyTypeName, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed, typeof(object), new[] { interfaceType });

                GenericParameterUtils.DefineGenericParameter(interfaceType, typeBuilder);

                // define default constructor
                typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);

                // properties
                var propertyMethods = new HashSet <string>();

                var properties = interfaceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var property in properties)
                {
                    var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes);
                    var field           = typeBuilder.DefineField($"_{property.Name}", property.PropertyType, FieldAttributes.Private);
                    if (property.CanRead)
                    {
                        var methodBuilder = typeBuilder.DefineMethod(property.GetMethod.Name, InterfaceMethodAttributes, property.GetMethod.CallingConvention, property.GetMethod.ReturnType, property.GetMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                        var ilGen         = methodBuilder.GetILGenerator();
                        ilGen.Emit(OpCodes.Ldarg_0);
                        ilGen.Emit(OpCodes.Ldfld, field);
                        ilGen.Emit(OpCodes.Ret);
                        typeBuilder.DefineMethodOverride(methodBuilder, property.GetMethod);
                        propertyBuilder.SetGetMethod(methodBuilder);
                        propertyMethods.Add(property.GetMethod.Name);
                    }
                    if (property.CanWrite)
                    {
                        var methodBuilder = typeBuilder.DefineMethod(property.SetMethod.Name, InterfaceMethodAttributes, property.SetMethod.CallingConvention, property.SetMethod.ReturnType, property.SetMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                        var ilGen         = methodBuilder.GetILGenerator();
                        ilGen.Emit(OpCodes.Ldarg_0);
                        ilGen.Emit(OpCodes.Ldarg_1);
                        ilGen.Emit(OpCodes.Stfld, field);
                        ilGen.Emit(OpCodes.Ret);
                        typeBuilder.DefineMethodOverride(methodBuilder, property.SetMethod);
                        propertyBuilder.SetSetMethod(methodBuilder);
                        propertyMethods.Add(property.SetMethod.Name);
                    }
                    foreach (var customAttributeData in property.CustomAttributes)
                    {
                        propertyBuilder.SetCustomAttribute(DefineCustomAttribute(customAttributeData));
                    }
                }

                // methods
                var methods = interfaceType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                foreach (var method in methods.Where(x => !propertyMethods.Contains(x.Name) && !_ignoredMethods.Contains(x.Name)))
                {
                    MethodUtils.DefineInterfaceMethod(typeBuilder, method, null);
                }

                foreach (var implementedInterface in interfaceType.GetImplementedInterfaces())
                {
                    properties = implementedInterface.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                    foreach (var property in properties)
                    {
                        var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes);
                        var field           = typeBuilder.DefineField($"_{property.Name}", property.PropertyType, FieldAttributes.Private);
                        if (property.CanRead)
                        {
                            var methodBuilder = typeBuilder.DefineMethod(property.GetMethod.Name, InterfaceMethodAttributes, property.GetMethod.CallingConvention, property.GetMethod.ReturnType, property.GetMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                            var ilGen         = methodBuilder.GetILGenerator();
                            ilGen.Emit(OpCodes.Ldarg_0);
                            ilGen.Emit(OpCodes.Ldfld, field);
                            ilGen.Emit(OpCodes.Ret);
                            typeBuilder.DefineMethodOverride(methodBuilder, property.GetMethod);
                            propertyBuilder.SetGetMethod(methodBuilder);
                            propertyMethods.Add(property.GetMethod.Name);
                        }
                        if (property.CanWrite)
                        {
                            var methodBuilder = typeBuilder.DefineMethod(property.SetMethod.Name, InterfaceMethodAttributes, property.SetMethod.CallingConvention, property.SetMethod.ReturnType, property.SetMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                            var ilGen         = methodBuilder.GetILGenerator();
                            ilGen.Emit(OpCodes.Ldarg_0);
                            ilGen.Emit(OpCodes.Ldarg_1);
                            ilGen.Emit(OpCodes.Stfld, field);
                            ilGen.Emit(OpCodes.Ret);
                            typeBuilder.DefineMethodOverride(methodBuilder, property.SetMethod);
                            propertyBuilder.SetSetMethod(methodBuilder);
                            propertyMethods.Add(property.SetMethod.Name);
                        }
                        foreach (var customAttributeData in property.CustomAttributes)
                        {
                            propertyBuilder.SetCustomAttribute(DefineCustomAttribute(customAttributeData));
                        }
                    }

                    methods = implementedInterface.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                    foreach (var method in methods.Where(x => !propertyMethods.Contains(x.Name) && !_ignoredMethods.Contains(x.Name)))
                    {
                        MethodUtils.DefineInterfaceMethod(typeBuilder, method, null);
                    }
                }

                proxyType = typeBuilder.CreateType();
                _proxyTypes[proxyTypeName] = proxyType;
                return(proxyType);
            }
        }
Пример #25
0
        public void GetMethodInfoTest()
        {
            var methodInfo = MethodUtils.GetMethodInfo <MethodUtilsTests>(c => c.GetMethodInfoTest());

            Assert.AreEqual("GetMethodInfoTest", methodInfo.Name);
        }
Пример #26
0
 private static bool IsValidEnumerableContainsCall([NotNull] MethodCallExpression node)
 {
     return(MethodUtils.IsOperator(node.Method, MethodUtils.EContains) &&
            node.Arguments[0].NodeType == ExpressionType.Constant &&
            node.Arguments[1].NodeType == ExpressionType.MemberAccess);
 }
Пример #27
0
 public static LuaObject FromFunction(MethodInfo method)
 {
     return(MethodUtils.CreateFunction(method));
 }
Пример #28
0
        public static Type CreateClassProxy(Type serviceType, Type implementType)
        {
            if (null == serviceType)
            {
                throw new ArgumentNullException(nameof(serviceType));
            }
            if (null == implementType)
            {
                implementType = serviceType;
            }
            if (serviceType.IsSealed || implementType.IsSealed)
            {
                throw new InvalidOperationException("the class type is sealed");
            }
            //
            var proxyTypeName = _proxyTypeNameResolver(serviceType, implementType);

            if (_proxyTypes.TryGetValue(proxyTypeName, out var proxyType))
            {
                return(proxyType);
            }

            lock (_typeLock)
            {
                if (_proxyTypes.TryGetValue(proxyTypeName, out proxyType))
                {
                    return(proxyType);
                }

                var typeBuilder = _moduleBuilder.DefineType(proxyTypeName, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, implementType, Type.EmptyTypes);
                GenericParameterUtils.DefineGenericParameter(implementType, typeBuilder);

                var targetField = typeBuilder.DefineField(TargetFieldName, implementType, FieldAttributes.Private);

                // constructors
                var constructors = implementType.GetConstructors();
                if (constructors.Length > 0)
                {
                    foreach (var constructor in constructors)
                    {
                        var constructorTypes   = constructor.GetParameters().Select(o => o.ParameterType).ToArray();
                        var constructorBuilder = typeBuilder.DefineConstructor(
                            constructor.Attributes,
                            constructor.CallingConvention,
                            constructorTypes);
                        foreach (var customAttribute in constructor.CustomAttributes)
                        {
                            constructorBuilder.SetCustomAttribute(DefineCustomAttribute(customAttribute));
                        }

                        var il = constructorBuilder.GetILGenerator();

                        il.EmitThis();
                        for (var i = 0; i < constructorTypes.Length; i++)
                        {
                            il.Emit(OpCodes.Ldarg, i + 1);
                        }

                        il.Call(constructor);
                        il.Emit(OpCodes.Nop);

                        il.EmitThis();
                        il.EmitThis();
                        il.Emit(OpCodes.Stfld, targetField);

                        il.Emit(OpCodes.Ret);
                    }
                }
                else
                {
                    var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, Type.EmptyTypes);
                    var il = constructorBuilder.GetILGenerator();

                    il.EmitThis();
                    il.EmitThis();
                    il.Emit(OpCodes.Stfld, targetField);

                    il.Emit(OpCodes.Ret);
                }
                // properties
                var propertyMethods = new HashSet <string>();
                foreach (var property in serviceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (property.IsVisibleAndVirtual())
                    {
                        var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes);

                        //inherit targetMethod's attribute
                        foreach (var customAttributeData in property.CustomAttributes)
                        {
                            propertyBuilder.SetCustomAttribute(DefineCustomAttribute(customAttributeData));
                        }

                        if (property.CanRead)
                        {
                            propertyMethods.Add(property.GetMethod.Name);

                            var method = MethodUtils.DefineClassMethod(typeBuilder, property.GetMethod, targetField);
                            propertyBuilder.SetGetMethod(method);
                        }
                        if (property.CanWrite)
                        {
                            propertyMethods.Add(property.SetMethod.Name);

                            var method = MethodUtils.DefineClassMethod(typeBuilder, property.SetMethod, targetField);
                            propertyBuilder.SetSetMethod(method);
                        }
                    }
                }

                // methods
                var methods = serviceType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                              .Where(m => m.IsVirtual && !m.IsFinal && m.IsVisible() && !propertyMethods.Contains(m.Name) && !_ignoredMethods.Contains(m.Name))
                              .ToArray();
                foreach (var method in methods)
                {
                    MethodUtils.DefineClassMethod(typeBuilder, method, targetField);
                }

                proxyType = typeBuilder.CreateType();
                _proxyTypes[proxyTypeName] = proxyType;
                return(proxyType);
            }
        }