public void SaveAllTest()
        {
            var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1");
            var type1           = assemblyBuilder.DefineType("class1");
            var type2           = assemblyBuilder.DefineType("class2");

            assemblyBuilder.Save();

            Assert.AreEqual(2, assemblyBuilder.AssemblyBuilder.GetTypes().Length);
        }
Example #2
0
        public void TestSaveAll()
        {
            var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1");
            var type1           = assemblyBuilder.DefineType("class1");
            var type2           = assemblyBuilder.DefineType("class2");

#if NETAPPCORE
            assemblyBuilder.Save();
#endif

            Assert.AreEqual(2, assemblyBuilder.AssemblyBuilder.GetTypes().Length);
        }
        /// <summary>
        /// 使用扩展属性对架构类进行包装。
        /// </summary>
        /// <param name="schemaType">架构类。</param>
        /// <param name="properties">扩展的属性列表。</param>
        /// <returns></returns>
        private static Type BuildWrapType(Type schemaType, PropertyInfo[] properties)
        {
            var dyAssemblyBuilder = new DynamicAssemblyBuilder("SchemaExtension_" + schemaType.Name);
            var dyTypeBuilder     = dyAssemblyBuilder.DefineType(schemaType.Name, baseType: schemaType);

            foreach (var property in properties)
            {
                var defaultValue      = GetPropertyDefaultValue(property);
                var dyPropertyBuilder = dyTypeBuilder.DefineProperty(property.Name, property.PropertyType);
                dyPropertyBuilder.DefineGetSetMethods();
                SetPropertyCustomAttributes(property, dyPropertyBuilder);
            }

            foreach (var con in schemaType.GetConstructors())
            {
                var parameters    = con.GetParameters();
                var dyConsBuilder = dyTypeBuilder.DefineConstructor(parameters.Select(s => s.ParameterType).ToArray(), ilCoding: (b) =>
                {
                    b.Emitter
                    .ldarg_0
                    .For(1, parameters.Length + 1, (e, i) => e.ldarg(i))
                    .call(con).ret();
                });
            }

            return(dyTypeBuilder.CreateType());
        }
Example #4
0
        /// <summary>
        /// 定义 MetadataTypeAttribute 类。
        /// </summary>
        private void DefineMetadataType()
        {
            if (validations.IsNullOrEmpty() && eValidations.IsNullOrEmpty())
            {
                return;
            }

            var metadataType = assemblyBuilder.DefineType("<Metadata>__" + TypeName);

            if (validations != null)
            {
                foreach (var property in validations.Keys)
                {
                    var propertyBuilder = metadataType.DefineProperty(property.Name, typeof(IProperty));
                    propertyBuilder.DefineGetSetMethods();

                    foreach (var expression in validations[property])
                    {
                        propertyBuilder.SetCustomAttribute(expression);
                    }
                }
            }

            if (eValidations != null)
            {
                foreach (var expression in eValidations)
                {
                    metadataType.SetCustomAttribute(expression);
                }
            }

            InnerBuilder.SetCustomAttribute <MetadataTypeAttribute>(metadataType.CreateType());
        }
Example #5
0
 /// <summary>
 /// 初始化 <see cref="EntityTypeBuilder"/> 类的新实例。
 /// </summary>
 /// <param name="typeName">动态类的类型名称。</param>
 /// <param name="assemblyBuilder">一个 <see cref="DynamicAssemblyBuilder"/> 容器。</param>
 /// <param name="baseType">所要继承的抽象类型,默认为 <see cref="EntityObject"/> 类。</param>
 public EntityTypeBuilder(string typeName, DynamicAssemblyBuilder assemblyBuilder = null, Type baseType = null)
 {
     _assemblyBuilder = assemblyBuilder ?? new DynamicAssemblyBuilder($"<DynamicType>_{typeName}");
     TypeName         = typeName;
     InnerBuilder     = _assemblyBuilder.DefineType(TypeName, baseType: baseType ?? typeof(EntityObject));
     EntityType       = InnerBuilder.UnderlyingSystemType;
     Properties       = new List <IProperty>();
 }
Example #6
0
        private static ProxyType BuildSchemaProxyType(List <string> assemblyList)
        {
            var proxyType = new ProxyType();
            var fileName  = Util.GenerateTempFileName();

            assemblyList.Add(fileName);
            var assemblyBuilder = new DynamicAssemblyBuilder("__Schema_Proxy", fileName);

            var tableTypeBuilder     = assemblyBuilder.DefineType("Table", baseType: typeof(MarshalByRefObject));
            var columnTypeBuilder    = assemblyBuilder.DefineType("Column", baseType: typeof(MarshalByRefObject));
            var referenceTypeBuilder = assemblyBuilder.DefineType("Reference", baseType: typeof(MarshalByRefObject));

            tableTypeBuilder.ImplementInterface(typeof(_IIdentity));
            columnTypeBuilder.ImplementInterface(typeof(_IIdentity));
            referenceTypeBuilder.ImplementInterface(typeof(_IIdentity));

            proxyType.TableType     = tableTypeBuilder.UnderlyingSystemType;
            proxyType.ColumnType    = columnTypeBuilder.UnderlyingSystemType;
            proxyType.ReferenceType = referenceTypeBuilder.UnderlyingSystemType;

            //定义Table代理类的属性
            foreach (var property in SchemaExtensionManager.GetWrapType <Table>().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var propertyType = Replace(property.PropertyType, proxyType);
                tableTypeBuilder.DefineProperty(property.Name, propertyType).DefineGetSetMethods();
            }

            //定义Table代理类的属性
            foreach (var property in SchemaExtensionManager.GetWrapType <Column>().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var propertyType = Replace(property.PropertyType, proxyType);
                columnTypeBuilder.DefineProperty(property.Name, propertyType).DefineGetSetMethods();
            }

            //定义Table代理类的属性
            foreach (var property in SchemaExtensionManager.GetWrapType <Reference>().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var propertyType = Replace(property.PropertyType, proxyType);
                referenceTypeBuilder.DefineProperty(property.Name, propertyType).DefineGetSetMethods();
            }

            assemblyBuilder.Save();
            return(proxyType);
        }
Example #7
0
        public void TestAssemblyBuilder()
        {
            var assemblyBuilder = new DynamicAssemblyBuilder("DynamicAssembly1");

            var interfaceBuilder = assemblyBuilder.DefineInterface("IInterface");
            var typeBuilder      = assemblyBuilder.DefineType("Class1");
            var enumBuilder      = assemblyBuilder.DefineEnum("Enum1");
            var assembly         = assemblyBuilder.Save();

            Assert.AreEqual("Class1", typeBuilder.TypeBuilder.Name);
            Assert.AreEqual("DynamicAssembly1", assembly.GetExportedTypes().Length);
        }
Example #8
0
        private static Type InternalBuildImplementType(Type definedType)
        {
            var assemblyBuilder = new DynamicAssemblyBuilder("ImplAssembly");
            var typeBuilder     = assemblyBuilder.DefineType(definedType.Name + "_Impl");

            if (definedType.IsInterface)
            {
                typeBuilder.ImplementInterface(definedType);
            }
            else
            {
                typeBuilder.BaseType = definedType;
            }

            //实现属性
            foreach (var property in definedType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var getMethod = property.GetGetMethod();
                var setMethod = property.GetSetMethod();
                if (definedType.IsInterface || (getMethod != null && getMethod.IsVirtual) || (setMethod != null && setMethod.IsVirtual))
                {
                    var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.PropertyType);
                    if (getMethod != null)
                    {
                        propertyBuilder.DefineGetMethod();
                    }

                    if (setMethod != null)
                    {
                        propertyBuilder.DefineSetMethod();
                    }
                }
            }

            //实现方法
            foreach (var method in definedType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
            {
                if ((definedType.IsInterface || method.IsVirtual) && !Regex.IsMatch(method.Name, @"^set_|get_"))
                {
                    var parameters    = method.GetParameters();
                    var methodBuilder = typeBuilder.DefineMethod(method.Name, method.ReturnType, parameters.Select(s => s.ParameterType).ToArray());

                    foreach (var par in parameters)
                    {
                        methodBuilder.DefineParameter(par.Name, par.IsOut, par.DefaultValue != DBNull.Value, par.DefaultValue);
                    }
                }
            }

            return(typeBuilder.CreateType());
        }
        /// <summary>
        /// 创建 SQLiteFunction 子类。
        /// </summary>
        /// <param name="functionName">函数的名称。</param>
        /// <param name="paramsCount">参数的个数。</param>
        /// <param name="actionIL">自定义函数的代码IL。</param>
        /// <returns></returns>
        protected virtual Type BuildFunctionType(string functionName, int paramsCount, Action <BuildContext> actionIL)
        {
            var scalar   = _funcTypeType.GetField("Scalar");
            var bindings = new[] {
                Expression.Bind(_funcAttrType.GetProperty("Name"), Expression.Constant(functionName)),
                Expression.Bind(_funcAttrType.GetProperty("Arguments"), Expression.Constant(paramsCount)),
                Expression.Bind(_funcAttrType.GetProperty("FuncType"), Expression.MakeMemberAccess(null, scalar))
            };

            var typeBuilder = _assemblyBuilder.DefineType(string.Format("SQLiteFunction_{0}_{1}", functionName, paramsCount), baseType: _funcType);

            typeBuilder.SetCustomAttribute(Expression.MemberInit(Expression.New(_funcAttrType), bindings));
            typeBuilder.DefineMethod("Invoke", typeof(object), new Type[] { typeof(object[]) }, ilCoding: actionIL).DefineParameter("args");
            return(typeBuilder.CreateType());
        }
Example #10
0
        private static Type BuildProfileProxyType(Type profileType, List <string> assemblyList)
        {
            var fileName = Util.GenerateTempFileName();

            assemblyList.Add(fileName);
            var assemblyBuilder = new DynamicAssemblyBuilder("__Profile_Proxy", fileName);

            var typeBuilder = assemblyBuilder.DefineType("Profile", baseType: typeof(MarshalByRefObject));

            //定义Table代理类的属性
            foreach (var property in profileType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                typeBuilder.DefineProperty(property.Name, property.PropertyType).DefineGetSetMethods();
            }

            assemblyBuilder.Save();
            return(typeBuilder.UnderlyingSystemType);
        }
Example #11
0
        /// <summary>
        /// 使用扩展属性对架构类进行包装。
        /// </summary>
        /// <param name="schemaType">架构类。</param>
        /// <param name="properties">扩展的属性列表。</param>
        /// <returns></returns>
        private static Type BuildWrapType(PropertyInfo[] properties)
        {
            var dyAssemblyBuilder = new DynamicAssemblyBuilder("ProfileExtension");
            var dyTypeBuilder     = dyAssemblyBuilder.DefineType("ProfileEx", baseType: typeof(Profile));

            foreach (var property in properties)
            {
                var defaultValue      = GetPropertyDefaultValue(property);
                var dyPropertyBuilder = dyTypeBuilder.DefineProperty(property.Name, property.PropertyType);
                dyPropertyBuilder.DefineGetSetMethods();
                SetPropertyCustomAttributes(property, dyPropertyBuilder);
            }

            var wrapType = dyTypeBuilder.CreateType();

            propertyCache = wrapType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(s => new PropertyMap(s)).ToList();
            return(wrapType);
        }
Example #12
0
        /// <summary>
        /// 使用指定的属性集合创建新的对象类型。
        /// </summary>
        /// <param name="newTypeName"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        private static Type BuildNewObjectType(string newTypeName, IEnumerable <PropertyInfo> properties)
        {
            var assembly    = new DynamicAssemblyBuilder("__DynamicAssembly_ExtendTypes");
            var typeBuilder = assembly.DefineType(newTypeName);
            //构造方法的参数类型集合
            var constructorParTypes = new List <Type>();
            //属性set方法的集合
            var setMethodBuilders = new List <DynamicMethodBuilder>();

            foreach (var pro in properties)
            {
                if (pro.CanRead)
                {
                    var pbuilder = typeBuilder.DefineProperty(pro.Name, pro.PropertyType);

                    //定义get和set方法
                    pbuilder.DefineGetMethod();
                    setMethodBuilders.Add(pbuilder.DefineSetMethod(pro.CanWrite ? VisualDecoration.Public : VisualDecoration.Internal));

                    constructorParTypes.Add(pro.PropertyType);
                }
            }

            //定义一个构造方法,使用两个类型中的所有属性作为方法的参数
            if (constructorParTypes.Count > 0)
            {
                typeBuilder.DefineConstructor(constructorParTypes.ToArray()).AppendCode(e =>
                {
                    //在构造方法中,对每一个属性进行赋值
                    e.Each(setMethodBuilders, (e1, b, i) =>
                           e1.ldarg_0.ldarg(i + 1).call(b.MethodBuilder)
                           ).ret();
                });
            }

            return(typeBuilder.CreateType());
        }
        private DynamicTypeBuilder CreateBuilder()
        {
            var assemblyBuilder = new DynamicAssemblyBuilder("assemblyTests");

            return(assemblyBuilder.DefineType("testClass"));
        }
Example #14
0
        /// <summary>
        /// 构造实体类 <paramref name="entityType"/> 的代理类。
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="entityName"></param>
        /// <param name="assemblyBuilder"></param>
        /// <param name="injection"></param>
        /// <returns></returns>
        public static Type BuildType(Type entityType, string entityName, DynamicAssemblyBuilder assemblyBuilder = null, IInjectionProvider injection = null)
        {
            var typeBuilder = assemblyBuilder.DefineType(entityName ?? entityType.Name, baseType: entityType);

            typeBuilder.ImplementInterface(typeof(ICompiledEntity));
            typeBuilder.SetCustomAttribute(() => new SerializableAttribute());

            //重写构造器
            foreach (var cons in entityType.GetConstructors(BindingFlags.Public | BindingFlags.Instance))
            {
                var parameters = cons.GetParameters();
                typeBuilder.DefineConstructor(parameters.Select(s => s.ParameterType).ToArray()).AppendCode(e =>
                {
                    e.ldarg_0.For(0, parameters.Length, (b, i) => b.ldarg(i + 1))
                    .call(cons).nop.ret();
                });
            }

            //重写属性
            var properties = from s in entityType.GetProperties()
                             let getMth = s.GetGetMethod()
                                          where getMth.IsVirtual && !getMth.IsFinal
                                          select s;

            foreach (var property in properties)
            {
                var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.PropertyType);

                var get    = property.GetGetMethod();
                var set    = property.GetSetMethod();
                var isEnum = property.PropertyType.GetNonNullableType().IsEnum;
                var opType = isEnum ? typeof(Enum) : property.PropertyType;

                if (get != null)
                {
                    var op_Explicit = ReflectionCache.GetMember("PropertyValue_Explicit", opType, "op_Explicit", (k, n) => typeof(PropertyValue).GetMethods().FirstOrDefault(s => s.Name == n && s.ReturnType == k));
                    propertyBuilder.DefineGetMethod(ilCoding: code =>
                    {
                        code.Emitter.DeclareLocal(typeof(PropertyValue));
                        code.Emitter.DeclareLocal(get.ReturnType);
                        code.Emitter
                        .nop
                        .ldarg_0
                        .ldtoken(entityType)
                        .call(MethodCache.TypeGetTypeFromHandle)
                        .ldstr(property.Name)
                        .call(MethodCache.GetProperty)
                        .call(MethodCache.GetValue)
                        .Assert(op_Explicit != null, e1 => e1.call(op_Explicit),
                                e1 => e1.call(MethodCache.PVGetValue.MakeGenericMethod(property.PropertyType)))
                        .Assert(isEnum, e1 => e1.unbox_any(property.PropertyType))
                        .stloc_1
                        .ldloc_1
                        .ret();
                    });
                }

                if (set != null)
                {
                    var op_Implicit = ReflectionCache.GetMember("PropertyValue_Implicit", opType, "op_Implicit", (k, n) => typeof(PropertyValue).GetMethods().FirstOrDefault(s => s.Name == n && s.GetParameters()[0].ParameterType == k));
                    propertyBuilder.DefineSetMethod(ilCoding: code =>
                    {
                        code.Emitter
                        .nop
                        .ldarg_0
                        .ldtoken(entityType)
                        .call(MethodCache.TypeGetTypeFromHandle)
                        .ldstr(property.Name)
                        .call(MethodCache.GetProperty)
                        .ldarg_1
                        .Assert(isEnum, e1 => e1.box(property.PropertyType))
                        .Assert(op_Implicit != null, e1 => e1.call(op_Implicit),
                                e1 => e1.ldtoken(property.PropertyType).call(MethodCache.TypeGetTypeFromHandle).call(MethodCache.PVNewValue))
                        .call(MethodCache.SetValue)
                        .nop
                        .ret();
                    });
                }
            }

            var initMethod = typeBuilder.DefineMethod("InitializeValue",
                                                      parameterTypes: new[] { typeof(IProperty), typeof(PropertyValue) },
                                                      ilCoding: code =>
            {
                code.Emitter.
                ldarg_0.ldarg_1.ldarg_2.
                callvirt(MethodCache.InitValue).ret();
            });

            injection?.Inject(new EntityInjectionContext
            {
                EntityType      = entityType,
                AssemblyBuilder = assemblyBuilder,
                TypeBuilder     = typeBuilder
            });

            return(typeBuilder.CreateType());
        }
Example #15
0
        /// <summary>
        /// 构造实体类 <paramref name="entityType"/> 的代理类。
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="entityName"></param>
        /// <param name="assemblyBuilder"></param>
        /// <param name="injection"></param>
        /// <returns></returns>
        public static Type BuildType(Type entityType, string entityName, DynamicAssemblyBuilder assemblyBuilder = null, IInjectionProvider injection = null)
        {
            var typeBuilder = assemblyBuilder.DefineType(entityName ?? entityType.Name, baseType: entityType);

            typeBuilder.ImplementInterface(typeof(ICompiledEntity));
            typeBuilder.SetCustomAttribute(() => new SerializableAttribute());

            var properties = from s in entityType.GetProperties()
                             let getMth = s.GetGetMethod()
                                          where getMth.IsVirtual && !getMth.IsFinal
                                          select s;

            foreach (var property in properties)
            {
                var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.PropertyType);

                var get    = property.GetGetMethod();
                var set    = property.GetSetMethod();
                var isEnum = property.PropertyType.GetNonNullableType().IsEnum;
                var opType = isEnum ? typeof(Enum) : property.PropertyType;

                if (get != null)
                {
                    var op_Explicit = typeof(PropertyValue).GetMethods().FirstOrDefault(s => s.Name == "op_Explicit" && s.ReturnType == opType);
                    propertyBuilder.DefineGetMethod(ilCoding: code =>
                    {
                        code.Emitter.DeclareLocal(get.ReturnType);
                        code.Emitter
                        .nop
                        .ldarg_0
                        .ldtoken(entityType)
                        .call(MthTypeGetTypeFromHandle)
                        .ldstr(property.Name)
                        .call(MthGetProperty)
                        .call(MthGetValue)
                        .Assert(op_Explicit != null, e1 => e1.call(op_Explicit), e1 => e1.call(MthPVGetValue).castclass(opType))
                        .Assert(isEnum, e1 => e1.unbox_any(property.PropertyType))
                        .stloc_0
                        .ldloc_0
                        .ret();
                    });
                }

                if (set != null)
                {
                    var op_Implicit = typeof(PropertyValue).GetMethods().FirstOrDefault(s => s.Name == "op_Implicit" && s.GetParameters()[0].ParameterType == opType);
                    propertyBuilder.DefineSetMethod(ilCoding: code =>
                    {
                        code.Emitter
                        .nop
                        .ldarg_0
                        .ldtoken(entityType)
                        .call(MthTypeGetTypeFromHandle)
                        .ldstr(property.Name)
                        .call(MthGetProperty)
                        .ldarg_1
                        .Assert(isEnum, e1 => e1.box(property.PropertyType))
                        .Assert(op_Implicit != null, e1 => e1.call(op_Implicit), e1 => e1.ldnull.call(MthPVNewValue))
                        .call(MthSetValue)
                        .nop
                        .ret();
                    });
                }
            }

            var initMethod = typeBuilder.DefineMethod("InitializeValue",
                                                      parameterTypes: new[] { typeof(IProperty), typeof(PropertyValue) },
                                                      ilCoding: code =>
            {
                code.Emitter.
                ldarg_0.ldarg_1.ldarg_2.
                callvirt(MthInitValue).ret();
            });

            injection?.Inject(entityType, assemblyBuilder, typeBuilder);

            return(typeBuilder.CreateType());
        }
Example #16
0
        /// <summary>
        /// 构造实体类 <paramref name="entityType"/> 的代理类。
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="assemblyBuilder"></param>
        /// <returns></returns>
        public static Type BuildType(Type entityType, DynamicAssemblyBuilder assemblyBuilder = null)
        {
            var typeBuilder = assemblyBuilder.DefineType(entityType.Name, baseType: entityType);

            typeBuilder.ImplementInterface(typeof(ICompiledEntity));

            var properties = from s in entityType.GetProperties()
                             let getMth = s.GetGetMethod()
                                          where getMth.IsVirtual && !getMth.IsFinal
                                          select s;

            foreach (var property in properties)
            {
                var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.PropertyType);

                var get    = property.GetGetMethod();
                var set    = property.GetSetMethod();
                var isEnum = property.PropertyType.GetNonNullableType().IsEnum;
                var opType = isEnum ? typeof(Enum) : property.PropertyType;

                if (get != null)
                {
                    var op_Explicit = typeof(PropertyValue).GetMethods().FirstOrDefault(s => s.Name == "op_Explicit" && s.ReturnType == opType);
                    propertyBuilder.DefineGetMethod(ilCoding: code =>
                    {
                        code.Emitter.DeclareLocal(get.ReturnType);
                        code.Emitter
                        .nop
                        .ldarg_0
                        .ldtoken(entityType)
                        .call(mthTypeGetTypeFromHandle)
                        .ldstr(property.Name)
                        .call(mthGetProperty)
                        .call(mthGetValue)
                        .Assert(op_Explicit != null, e1 => e1.call(op_Explicit), e1 => e1.call(mthPVGetValue).isinst(opType))
                        .Assert(isEnum, e1 => e1.unbox_any(property.PropertyType))
                        .stloc_0
                        .ldloc_0
                        .ret();
                    });
                }

                if (set != null)
                {
                    var op_Implicit = typeof(PropertyValue).GetMethods().FirstOrDefault(s => s.Name == "op_Implicit" && s.GetParameters()[0].ParameterType == opType);
                    propertyBuilder.DefineSetMethod(ilCoding: code =>
                    {
                        code.Emitter
                        .nop
                        .ldarg_0
                        .ldtoken(entityType)
                        .call(mthTypeGetTypeFromHandle)
                        .ldstr(property.Name)
                        .call(mthGetProperty)
                        .ldarg_1
                        .Assert(isEnum, e1 => e1.box(property.PropertyType))
                        .Assert(op_Implicit != null, e1 => e1.call(op_Implicit), e1 => e1.ldnull.call(mthPVNewValue))
                        .call(mthSetValue)
                        .nop
                        .ret();
                    });
                }
            }

            return(typeBuilder.CreateType());
        }
        public void DefineTypeTest()
        {
            var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1");

            assemblyBuilder.DefineType("class1");
        }