示例#1
0
        private void BuildTypedSetterForNullable(
            MemberInfo mi,
            TypeBuilderHelper nestedType,
            Type memberType)
        {
            Type       methodType = mi.DeclaringType;
            MethodInfo setMethod  = null;

            if (mi is PropertyInfo)
            {
                setMethod = ((PropertyInfo)mi).GetSetMethod();

                if (setMethod == null)
                {
                    if (_type != _originalType)
                    {
                        setMethod  = _type.GetMethod("set_" + mi.Name);
                        methodType = _type;
                    }

                    if (setMethod == null || !IsMethodAccessible(setMethod))
                    {
                        return;
                    }
                }
            }

            Type       setterType = (memberType.IsEnum ? Enum.GetUnderlyingType(memberType) : memberType);
            MethodInfo methodInfo =
                _memberAccessor.GetMethod("Set" + setterType.Name, typeof(object), setterType);

            if (methodInfo == null)
            {
                return;
            }

            MethodBuilderHelper method = nestedType.DefineMethod(methodInfo);

            EmitHelper emit = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .ldarg_2
            .newobj(typeof(Nullable <>).MakeGenericType(memberType), memberType)
            .end();

            if (mi is FieldInfo)
            {
                emit.stfld((FieldInfo)mi);
            }
            else
            {
                emit.callvirt(setMethod);
            }

            emit
            .ret()
            ;
        }
        private void CreateProperty(TypeBuilderHelper typeBuilderHelper)
        {
            var dbObjectContainerField  = typeBuilderHelper.DefineField("dbObjectContainer", typeof(DbObjectContainer), FieldAttributes.Private);
            var objectContainerProperty = typeBuilderHelper.TypeBuilder.DefineProperty("DbObjectContainer",
                                                                                       PropertyAttributes.HasDefault,
                                                                                       typeof(DbObjectContainer),
                                                                                       new[] { typeof(DbObjectContainer) });
            var attributes = MethodAttributes.Public | MethodAttributes.SpecialName |
                             MethodAttributes.HideBySig;
            var objectContainerGetMethod = typeBuilderHelper.DefineMethod("get_DbObjectContainer",
                                                                          attributes, typeof(DbObjectContainer), Type.EmptyTypes);
            var objectContainerGetMethodEmit = objectContainerGetMethod.Emitter;

            objectContainerGetMethodEmit
            .ldarg_0
            .ldfld(dbObjectContainerField)
            .ret();

            var objectContainerSetMethod = typeBuilderHelper.DefineMethod("set_DbObjectContainer",
                                                                          attributes, null, typeof(DbObjectContainer));
            var objectContainerSetMethodEmit = objectContainerSetMethod.Emitter;

            objectContainerSetMethodEmit
            .ldarg_0
            .ldarg_1
            .stfld(dbObjectContainerField)
            .ret();
            objectContainerProperty.SetGetMethod(objectContainerGetMethod);
            objectContainerProperty.SetSetMethod(objectContainerSetMethod);
        }
示例#3
0
        public Type Build(AssemblyBuilderHelper assemblyBuilder)
        {
            if (assemblyBuilder == null)
            {
                throw new ArgumentNullException("assemblyBuilder");
            }

            // Check InternalsVisibleToAttributes of the source type's assembly.
            // Even if the sourceType is public, it may have internal fields and props.
            //
            _friendlyAssembly = false;

            // Usually, there is no such attribute in the source assembly.
            // Therefore we do not cache the result.
            //
            var attributes = _originalType.Type.Assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true);

            foreach (InternalsVisibleToAttribute visibleToAttribute in attributes)
            {
                var an = new AssemblyName(visibleToAttribute.AssemblyName);

                if (AssemblyName.ReferenceMatchesDefinition(assemblyBuilder.AssemblyName, an))
                {
                    _friendlyAssembly = true;
                    break;
                }
            }

            if (!_originalType.Type.IsVisible && !_friendlyAssembly)
            {
                return(typeof(ExprTypeAccessor <,>).MakeGenericType(_type, _originalType));
            }

            var typeName = GetTypeName();

            _typeBuilder = assemblyBuilder.DefineType(typeName, _accessorType);

            _typeBuilder.DefaultConstructor.Emitter
            .ldarg_0
            .call(TypeHelper.GetDefaultConstructor(_accessorType))
            ;

            BuildCreateInstanceMethods();
            BuildTypeProperties();
            BuildMembers();
            BuildObjectFactory();

            _typeBuilder.DefaultConstructor.Emitter
            .ret()
            ;

            var result = _typeBuilder.Create();

            foreach (TypeBuilderHelper tb in _nestedTypes)
            {
                tb.Create();
            }

            return(result);
        }
示例#4
0
        private void BuildTypedSetter(
            MemberInfo mi,
            TypeBuilderHelper nestedType,
            Type memberType,
            string typedPropertyName)
        {
            Type       methodType = mi.DeclaringType;
            MethodInfo setMethod  = null;

            if (mi is PropertyInfo)
            {
                setMethod = ((PropertyInfo)mi).GetSetMethod();

                if (setMethod == null)
                {
                    if (_type != _originalType)
                    {
                        setMethod  = _type.GetMethod("set_" + mi.Name);
                        methodType = _type;
                    }

                    if (setMethod == null || !IsMethodAccessible(setMethod))
                    {
                        return;
                    }
                }
            }

            MethodInfo methodInfo =
                _memberAccessor.GetMethod("Set" + typedPropertyName, typeof(object), memberType);

            if (methodInfo == null)
            {
                return;
            }

            MethodBuilderHelper method = nestedType.DefineMethod(methodInfo);

            EmitHelper emit = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .ldarg_2
            .end();

            if (mi is FieldInfo)
            {
                emit.stfld((FieldInfo)mi);
            }
            else
            {
                emit.callvirt(setMethod);
            }

            emit
            .ret()
            ;
        }
示例#5
0
        private void DefineType(IEnumerable <string> langs)
        {
            var tb = TypeBuilderHelper.Define("TTT", typeof(Record));

            langs.ToList().ForEach(l => {
                tb.DefineProperty(l.Replace("-", "_"), typeof(string));
            });
            this.TmpType = tb.CreateType();
        }
示例#6
0
        private void BuildMember(MemberInfo mi)
        {
            TypeBuilderHelper nestedType = _typeBuilder.DefineNestedType(
                "Accessor$" + mi.Name, TypeAttributes.NestedPrivate, typeof(MemberAccessor));

            ConstructorBuilderHelper ctorBuilder = BuildNestedTypeConstructor(nestedType);

            BuildGetter(mi, nestedType);
            BuildSetter(mi, nestedType);
            BuildInitMember(mi, ctorBuilder);

            Type type = mi is FieldInfo ? ((FieldInfo)mi).FieldType : ((PropertyInfo)mi).PropertyType;

            BuildIsNull(mi, nestedType, type);

            if (type.IsEnum)
            {
                type = Enum.GetUnderlyingType(type);
            }

            string typedPropertyName = type.Name;

            if (type.IsGenericType)
            {
                Type underlyingType = Nullable.GetUnderlyingType(type);

                if (underlyingType != null)
                {
                    BuildTypedGetterForNullable(mi, nestedType, underlyingType);
                    BuildTypedSetterForNullable(mi, nestedType, underlyingType);

                    if (underlyingType.IsEnum)
                    {
                        underlyingType = Enum.GetUnderlyingType(underlyingType);
                        type           = typeof(Nullable <>).MakeGenericType(underlyingType);
                    }
                    typedPropertyName = "Nullable" + underlyingType.Name;
                }
                else
                {
                    typedPropertyName = null;
                }
            }

            if (typedPropertyName != null)
            {
                BuildTypedGetter(mi, nestedType, typedPropertyName);
                BuildTypedSetter(mi, nestedType, type, typedPropertyName);
            }

            BuildCloneValueMethod(mi, nestedType, type);

            // FW 1.1 wants nested types to be created before parent.
            //
            _nestedTypes.Add(nestedType);
        }
示例#7
0
        /// <summary>
        /// 映射物理表
        /// </summary>
        /// <param name="absTable">抽象表类型</param>
        /// <param name="targetTableName">目标物理表名</param>
        /// <returns></returns>
        public static Type MapTable(Type absTable, string targetTableName)
        {
            var config = TypeBuilderHelper.GetConfig(absTable);

            config.AssemblyName = "EFCore.Sharding";
            config.Attributes.RemoveAll(x => x.Attribute == typeof(TableAttribute));
            config.FullName = $"EFCore.Sharding.{targetTableName}";

            return(TypeBuilderHelper.BuildType(config));
        }
示例#8
0
        private void BuildTypedGetter(
            MemberInfo mi,
            TypeBuilderHelper nestedType,
            string typedPropertyName)
        {
            var methodType = mi.DeclaringType;
            var getMethod  = null as MethodInfo;

            if (mi is PropertyInfo)
            {
                getMethod = ((PropertyInfo)mi).GetGetMethod();

                if (getMethod == null)
                {
                    if (_type != _originalType)
                    {
                        getMethod  = _type.GetMethod("get_" + mi.Name);
                        methodType = _type;
                    }

                    if (getMethod == null || !IsMethodAccessible(getMethod))
                    {
                        return;
                    }
                }
            }

            var methodInfo = _memberAccessor.GetMethod("Get" + typedPropertyName, typeof(object));

            if (methodInfo == null)
            {
                return;
            }

            var method = nestedType.DefineMethod(methodInfo);
            var emit   = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .end();

            if (mi is FieldInfo)
            {
                emit.ldfld((FieldInfo)mi);
            }
            else
            {
                emit.callvirt(getMethod);
            }

            emit
            .ret()
            ;
        }
示例#9
0
        /// <summary>
        /// 映射物理表
        /// </summary>
        /// <param name="absTable">抽象表类型</param>
        /// <param name="targetTableName">目标物理表名</param>
        /// <returns></returns>
        public static Type MapTable(Type absTable, string targetTableName)
        {
            var config = TypeBuilderHelper.GetConfig(absTable);

            //实体必须放到Entity层中,不然会出现莫名调试BUG,原因未知
            config.AssemblyName = "Coldairarrow.Entity";
            config.Attributes.RemoveAll(x => x.Attribute == typeof(TableAttribute));
            config.FullName = $"Coldairarrow.Entity.{targetTableName}";

            return(TypeBuilderHelper.BuildType(config));
        }
        public void LinqJoin()
        {
            using (var db = Helper.CreatePCORIDataContext(ConnectionString))
            {
                var query = db.ReportedOutcomeCommonMeasures
                            .Join(db.Encounters, pro => pro.PatientID, enc => enc.PatientID, (pro, enc) => new { PRO = pro, ENC = enc });

                Logger.Debug(query.Expression.ToString());

                var pe_pro = Expression.Parameter(typeof(ReportedOutcome), "pro");
                var pe_enc = Expression.Parameter(typeof(Encounter), "enc");

                var joinType = TypeBuilderHelper.CreateType("PRO_Enc", new IPropertyDefinition[] {
                    new TypedPropertyDefinition <ReportedOutcome> {
                        Name = "PRO"
                    },
                    new TypedPropertyDefinition <Encounter> {
                        Name = "ENC"
                    }
                });

                var joinBindings = new[] {
                    Expression.Bind(joinType.GetProperty("PRO"), pe_pro),
                    Expression.Bind(joinType.GetProperty("ENC"), pe_enc)
                };

                var resultSelector = Expression.Lambda(
                    Expression.MemberInit(Expression.New(joinType), joinBindings),
                    pe_pro,
                    pe_enc
                    );

                var joinCall = Expression.Call(
                    typeof(Queryable),
                    "Join",
                    new Type[] {
                    typeof(ReportedOutcome),
                    typeof(Encounter),
                    typeof(string),
                    joinType
                },
                    new Expression[] {
                    db.ReportedOutcomeCommonMeasures.AsQueryable().Expression,
                    db.Encounters.AsQueryable().Expression,
                    Expression.Quote(Expression.Lambda(Expression.Property(pe_pro, "PatientID"), pe_pro)),
                    Expression.Quote(Expression.Lambda(Expression.Property(pe_enc, "PatientID"), pe_enc)),
                    Expression.Quote(resultSelector)
                }
                    );


                Logger.Debug(joinCall.ToString());
            }
        }
示例#11
0
		public Type Build(AssemblyBuilderHelper assemblyBuilder)
		{
			if (assemblyBuilder == null) throw new ArgumentNullException("assemblyBuilder");

			// Check InternalsVisibleToAttributes of the source type's assembly.
			// Even if the sourceType is public, it may have internal fields and props.
			//
			_friendlyAssembly = false;

			// Usually, there is no such attribute in the source assembly.
			// Therefore we do not cache the result.
			//
			var attributes = _originalType.Type.Assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true);

			foreach (InternalsVisibleToAttribute visibleToAttribute in attributes)
			{
				var an = new AssemblyName(visibleToAttribute.AssemblyName);

				if (AssemblyName.ReferenceMatchesDefinition(assemblyBuilder.AssemblyName, an))
				{
					_friendlyAssembly = true;
					break;
				}
			}

			if (!_originalType.Type.IsVisible && !_friendlyAssembly)
				return typeof (ExprTypeAccessor<,>).MakeGenericType(_type, _originalType);

			var typeName = GetTypeName();

			_typeBuilder = assemblyBuilder.DefineType(typeName, _accessorType);

			_typeBuilder.DefaultConstructor.Emitter
				.ldarg_0
				.call    (TypeHelper.GetDefaultConstructor(_accessorType))
				;

			BuildCreateInstanceMethods();
			BuildTypeProperties();
			BuildMembers();
			BuildObjectFactory();

			_typeBuilder.DefaultConstructor.Emitter
				.ret()
				;

			var result = _typeBuilder.Create();

			foreach (TypeBuilderHelper tb in _nestedTypes)
				tb.Create();

			return result;
		}
        public static void UpdateType(string typeName, TypeBuilderHelper typeBuilderHelper, FieldInfo[] fieldInfos)
        {
            //Serialize
            var serializerEmit  = typeBuilderHelper.DefineMethod(typeof(ISerializable).GetMethod("Serialize", new Type[] { typeof(BinaryWriter), typeof(IDictionary <object, int>), typeof(int) })).Emitter;
            var deserializeEmit =
                typeBuilderHelper.DefineMethod(typeof(ISerializable).GetMethod("Deserialize", new Type[] { typeof(BinaryReader), typeof(IDictionary <int, object>) })).Emitter;

            //Write type name so we can construct it again
            serializerEmit
            .ldarg_1
            .ldstr(typeName)
            .call(typeof(BinaryWriter).GetMethod("Write", new[] { typeof(string) }))
            //Add current object to the object graph
            .ldarg_2
            .ldarg_0
            .ldarg_3
            .call(typeof(IDictionary <object, int>).GetMethod("Add", new[] { typeof(object), typeof(int) }))
            .ldarg_3
            .ldc_i4_1
            .add
            .starg(3);
            //Serialize/Deserialize properties
            foreach (var fieldInfo in fieldInfos)
            {
                var fieldType = fieldInfo.FieldType;
                if (fieldType.IsPrimitive || fieldType == typeof(string) || fieldType == typeof(DateTime) || fieldType == typeof(decimal))
                {
                    primitiveSerializeEmitter.Emit(fieldInfo, ref serializerEmit, ref deserializeEmit);
                }
                else if (fieldType.IsArray)
                {
                    arraySerializeEmitter.Emit(fieldInfo, ref serializerEmit, ref deserializeEmit);
                }
                else if (fieldType.IsGenericType && (fieldType.GetGenericTypeDefinition() == typeof(IDictionary <,>) || fieldType.GetGenericTypeDefinition() == typeof(Dictionary <,>)))
                {
                    dictGenericEmitter.Emit(fieldInfo, ref serializerEmit, ref deserializeEmit);
                }
                else if (fieldType.IsGenericType && (fieldType.GetGenericTypeDefinition() == typeof(IList <>) || fieldType.GetGenericTypeDefinition() == typeof(List <>)))
                {
                    iListGenericEmitter.Emit(fieldInfo, ref serializerEmit, ref deserializeEmit);
                }
                else if (fieldType.IsClass)
                {
                    objectGenericEmitter.Emit(fieldInfo, ref serializerEmit, ref deserializeEmit);
                }
            }
            serializerEmit.ret();
            deserializeEmit.ret();
        }
示例#13
0
        private static ConstructorBuilderHelper BuildNestedTypeConstructor(TypeBuilderHelper nestedType)
        {
            Type[] parameters = { typeof(TypeAccessor), typeof(MemberInfo) };

            var ctorBuilder = nestedType.DefinePublicConstructor(parameters);

            ctorBuilder.Emitter
            .ldarg_0
            .ldarg_1
            .ldarg_2
            .call(TypeHelper.GetConstructor(typeof(MemberAccessor), parameters))
            .ret()
            ;

            return(ctorBuilder);
        }
        public static Type MapTable(Type absTable, string targetTableName)
        {
            var config = TypeBuilderHelper.GetConfig(absTable);

            config.AssemblyName = "EFCore.Sharding";

            var theTableAttribute = config.Attributes
                                    .Where(x => x.Attribute == typeof(TableAttribute))
                                    .FirstOrDefault();

            if (theTableAttribute != null)
            {
                theTableAttribute.ConstructorArgs[0] = targetTableName;
            }

            config.FullName = $"EFCore.Sharding.{targetTableName}";

            return(TypeBuilderHelper.BuildType(config));
        }
示例#15
0
        public Type Build(AssemblyBuilderHelper assemblyBuilder)
        {
            _typeBuilder = assemblyBuilder.DefineType(GetTypeName(), typeof(DuckType), _interfaceType);

            if (!BuildMembers(_interfaceType))
            {
                return(null);
            }

            foreach (Type t in _interfaceType.GetInterfaces())
            {
                if (!BuildMembers(t))
                {
                    return(null);
                }
            }

            return(_typeBuilder.Create());
        }
        /// <summary>
        ///     Get the type of the schema. If it is an array, get the array type.
        /// </summary>
        /// <param name="schema">The JSON schema.</param>
        /// <param name="ns">The namespace.</param>
        /// <returns>The type of the schema.</returns>
        public static Type GetType(JsonSchema schema, string ns = "")
        {
            string toRet   = DEFAULT_TYPE;
            var    builder = new TypeBuilderHelper(ns);

            // Set the type to the type if it is not an array
            if (!IsArray(schema))
            {
                if (schema.Title != null)
                {
                    return(builder.GetCustomType(schema.Title, true));
                }
                if (schema.Type != null)
                {
                    toRet = TypeUtils.GetPrimitiveTypeAsString(schema.Type);
                }
            }
            else
            {
                // Set the type to the title if it exists
                if (schema.Title != null)
                {
                    return(builder.GetCustomType(schema.Title, true));
                }
                if (schema.Items != null && schema.Items.Count > 0)
                {
                    // Set the type to the title of the items
                    if (schema.Items[0].Title != null)
                    {
                        return(builder.GetCustomType(schema.Items[0].Title, true));
                    }
                    // Set the type to the type of the items
                    if (schema.Items[0].Type != null)
                    {
                        toRet = TypeUtils.GetPrimitiveTypeAsString(schema.Items[0].Type);
                    }
                }
            }

            return(Type.GetType(toRet, true));
        }
示例#17
0
        static void Main(string[] args)
        {
            //IRepository db1 = DbFactory.GetRepository("oracle", DatabaseType.Oracle);
            //IRepository db2 = DbFactory.GetRepository("oracle2", DatabaseType.Oracle);
            //var list = db1.GetList<Base_User>();
            //var list2 = db2.GetList<Base_User>();
            var db = DbFactory.GetRepository();

            db.HandleSqlLog = Console.WriteLine;
            string tableName  = "Base_User1";
            var    typeConfig = TypeBuilderHelper.GetConfig(typeof(Base_User));

            typeConfig.FullName = tableName;
            typeConfig.Attributes[0].ConstructorArgs[0] = tableName;
            var type       = TypeBuilderHelper.BuildType(typeConfig);
            var type2      = TypeBuilderHelper.BuildType(typeConfig);
            var properties = type.GetProperties();

            Console.WriteLine(type == type2);
            Base_User base_User = new Base_User
            {
                Id       = GuidHelper.GenerateKey(),
                UserId   = GuidHelper.GenerateKey(),
                UserName = GuidHelper.GenerateKey()
            };
            Base_User base_User2 = new Base_User
            {
                Id       = GuidHelper.GenerateKey(),
                UserId   = GuidHelper.GenerateKey(),
                UserName = GuidHelper.GenerateKey()
            };

            db.Insert(base_User.ToJson().ToObject(type));
            db.Insert(base_User2.ChangeType(type2));
            Console.WriteLine("完成");
            Console.ReadLine();
        }
示例#18
0
        private void BuildTypedGetterForNullable(
            MemberInfo mi,
            TypeBuilderHelper nestedType,
            Type memberType)
        {
            var methodType = mi.DeclaringType;
            var getMethod  = null as MethodInfo;

            if (mi is PropertyInfo)
            {
                getMethod = ((PropertyInfo)mi).GetGetMethod();

                if (getMethod == null)
                {
                    if (_type != _originalType)
                    {
                        getMethod  = _type.GetMethod("get_" + mi.Name);
                        methodType = _type;
                    }

                    if (getMethod == null || !IsMethodAccessible(getMethod))
                    {
                        return;
                    }
                }
            }

            var setterType = (memberType.IsEnum ? Enum.GetUnderlyingType(memberType) : memberType);
            var methodInfo = _memberAccessor.GetMethod("Get" + setterType.Name, typeof(object));

            if (methodInfo == null)
            {
                return;
            }

            var method       = nestedType.DefineMethod(methodInfo);
            var nullableType = typeof(Nullable <>).MakeGenericType(memberType);
            var emit         = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .end();

            if (mi is FieldInfo)
            {
                emit.ldflda((FieldInfo)mi);
            }
            else
            {
                var locNullable = emit.DeclareLocal(nullableType);

                emit
                .callvirt(getMethod)
                .stloc(locNullable)
                .ldloca(locNullable)
                ;
            }

            emit
            .call(nullableType, "get_Value")
            .ret()
            ;
        }
示例#19
0
        private void BuildCloneValueMethod(
            MemberInfo mi,
            TypeBuilderHelper nestedType,
            Type memberType
            )
        {
            var methodType = mi.DeclaringType;
            var getMethod  = null as MethodInfo;
            var setMethod  = null as MethodInfo;

            if (mi is PropertyInfo)
            {
                getMethod = ((PropertyInfo)mi).GetGetMethod();

                if (getMethod == null)
                {
                    if (_type != _originalType)
                    {
                        getMethod  = _type.GetMethod("get_" + mi.Name);
                        methodType = _type;
                    }

                    if (getMethod == null || !IsMethodAccessible(getMethod))
                    {
                        return;
                    }
                }

                setMethod = ((PropertyInfo)mi).GetSetMethod();

                if (setMethod == null)
                {
                    if (_type != _originalType)
                    {
                        setMethod  = _type.GetMethod("set_" + mi.Name);
                        methodType = _type;
                    }

                    if (setMethod == null || !IsMethodAccessible(setMethod))
                    {
                        return;
                    }
                }
            }

            var method = nestedType.DefineMethod(_memberAccessor.GetMethod("CloneValue", typeof(object), typeof(object)));
            var emit   = method.Emitter;

            emit
            .ldarg_2
            .castType(methodType)
            .ldarg_1
            .castType(methodType)
            .end();

            if (mi is FieldInfo)
            {
                emit.ldfld((FieldInfo)mi);
            }
            else
            {
                emit.callvirt(getMethod);
            }

            if (typeof(string) != memberType && TypeHelper.IsSameOrParent(typeof(ICloneable), memberType))
            {
                if (memberType.IsValueType)
                {
                    emit
                    .box(memberType)
                    .callvirt(typeof(ICloneable), "Clone")
                    .unbox_any(memberType)
                    ;
                }
                else
                {
                    var valueIsNull = emit.DefineLabel();

                    emit
                    .dup
                    .brfalse_s(valueIsNull)
                    .callvirt(typeof(ICloneable), "Clone")
                    .castclass(memberType)
                    .MarkLabel(valueIsNull)
                    ;
                }
            }

            if (mi is FieldInfo)
            {
                emit.stfld((FieldInfo)mi);
            }
            else
            {
                emit.callvirt(setMethod);
            }

            emit
            .ret()
            ;
        }
示例#20
0
		private void BuildTypedGetterForNullable(
			MemberInfo        mi,
			TypeBuilderHelper nestedType,
			Type              memberType)
		{
			var methodType = mi.DeclaringType;
			var getMethod  = null as MethodInfo;

			if (mi is PropertyInfo)
			{
				getMethod = ((PropertyInfo)mi).GetGetMethod();

				if (getMethod == null)
				{
					if (_type != _originalType)
					{
						getMethod  = _type.GetMethod("get_" + mi.Name);
						methodType = _type;
					}

					if (getMethod == null || !IsMethodAccessible(getMethod))
						return;
				}
			}

			var setterType = (memberType.IsEnum ? Enum.GetUnderlyingType(memberType) : memberType);
			var methodInfo = _memberAccessor.GetMethod("Get" + setterType.Name, typeof(object));

			if (methodInfo == null)
				return;

			var method       = nestedType.DefineMethod(methodInfo);
			var nullableType = typeof(Nullable<>).MakeGenericType(memberType);
			var emit         = method.Emitter;

			emit
				.ldarg_1
				.castType (methodType)
				.end();

			if (mi is FieldInfo)
			{
				emit.ldflda  ((FieldInfo)mi);
			}
			else
			{
				var locNullable = emit.DeclareLocal(nullableType);

				emit
					.callvirt (getMethod)
					.stloc    (locNullable)
					.ldloca   (locNullable)
					;
			}

			emit
				.call(nullableType, "get_Value")
				.ret()
				;
		}
示例#21
0
		private void BuildTypedGetter(
			MemberInfo        mi,
			TypeBuilderHelper nestedType,
			string            typedPropertyName)
		{
			var methodType = mi.DeclaringType;
			var getMethod  = null as MethodInfo;

			if (mi is PropertyInfo)
			{
				getMethod = ((PropertyInfo)mi).GetGetMethod();

				if (getMethod == null)
				{
					if (_type != _originalType)
					{
						getMethod  = _type.GetMethod("get_" + mi.Name);
						methodType = _type;
					}

					if (getMethod == null || !IsMethodAccessible(getMethod))
						return;
				}
			}

			var methodInfo = _memberAccessor.GetMethod("Get" + typedPropertyName, typeof(object));

			if (methodInfo == null)
				return;

			var method = nestedType.DefineMethod(methodInfo);
			var emit   = method.Emitter;

			emit
				.ldarg_1
				.castType (methodType)
				.end();

			if (mi is FieldInfo) emit.ldfld   ((FieldInfo)mi);
			else                 emit.callvirt(getMethod);

			emit
				.ret()
				;
		}
示例#22
0
		private static ConstructorBuilderHelper BuildNestedTypeConstructor(TypeBuilderHelper nestedType)
		{
			Type[] parameters = { typeof(TypeAccessor), typeof(MemberInfo) };

			var ctorBuilder = nestedType.DefinePublicConstructor(parameters);

			ctorBuilder.Emitter
				.ldarg_0
				.ldarg_1
				.ldarg_2
				.call    (TypeHelper.GetConstructor(typeof(MemberAccessor), parameters))
				.ret()
				;

			return ctorBuilder;
		}
 private void CreateInsertFunction(Type type, TypeBuilderHelper helper)
 {
     throw new NotImplementedException();
 }
 private void CreateReadObjectFunction(Type type, TypeBuilderHelper helper)
 {
 }
示例#25
0
        private void BuildGetter(MemberInfo mi, TypeBuilderHelper nestedType)
        {
            Type       methodType = mi.DeclaringType;
            MethodInfo getMethod  = null;

            if (mi is PropertyInfo)
            {
                getMethod = ((PropertyInfo)mi).GetGetMethod();

                if (getMethod == null)
                {
                    if (_type != _originalType)
                    {
                        getMethod  = _type.GetMethod("get_" + mi.Name);
                        methodType = _type;
                    }

                    if (getMethod == null || !IsMethodAccessible(getMethod))
                    {
                        return;
                    }
                }
            }

            MethodBuilderHelper method = nestedType.DefineMethod(
                _memberAccessor.GetMethod("GetValue", typeof(object)));

            EmitHelper emit = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .end();

            if (mi is FieldInfo)
            {
                FieldInfo fi = (FieldInfo)mi;

                emit
                .ldfld(fi)
                .boxIfValueType(fi.FieldType)
                ;
            }
            else
            {
                PropertyInfo pi = (PropertyInfo)mi;

                emit
                .callvirt(getMethod)
                .boxIfValueType(pi.PropertyType)
                ;
            }

            emit
            .ret()
            ;

            nestedType.DefineMethod(_memberAccessor.GetProperty("HasGetter").GetGetMethod()).Emitter
            .ldc_i4_1
            .ret()
            ;
        }
        private void CreateUpdateFunction(Type type, TypeBuilderHelper typeBuilderHelper)
        {
            var classMetadata       = ClassMetaDataManager.Instace.GetClassMetaData(type);
            var properties          = classMetadata.Properties;
            var mappingTable        = classMetadata.MappingTable;
            var methodEmit          = typeBuilderHelper.DefineMethod(typeof(IDbFunctionHelper).GetMethod("Update")).Emitter;
            var resultLocal         = methodEmit.DeclareLocal(typeof(int));
            var commandLocal        = methodEmit.DeclareLocal(typeof(DbCommand));
            var commandParameters   = methodEmit.DeclareLocal(typeof(DbParameterCollection));
            var queryBuilder        = new StringBuilder("UPDATE " + mappingTable + " SET ");
            var objectNotDirtyLabel = methodEmit.DefineLabel();

            foreach (var mappingInfo in properties.Values)
            {
                if (mappingInfo.MappingField != "Id")
                {
                    queryBuilder.Append(mappingInfo.MappingField + "=@" + mappingInfo.MappingField + ", ");
                }
            }
            var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2);

            queryBuilder.Length = 0;
            queryBuilder.Append(tmpString);
            queryBuilder.Append(" WHERE Id = @Id");
            methodEmit
            .ldarg_1
            .call(typeof(IDbObject).GetMethod("get_IsDirty"))
            .brfalse(objectNotDirtyLabel)
            .ldc_i4_0
            .stloc(resultLocal)
            .ldarg_2
            .call(typeof(DbConnection).GetMethod("CreateCommand"))
            .stloc(commandLocal)
            .ldloc(commandLocal)
            .ldstr(queryBuilder.ToString())
            .call(typeof(DbCommand).GetMethod("set_CommandText"))
            .ldloc(commandLocal)
            .call(typeof(DbCommand).GetMethod("get_Parameters"))
            .stloc(commandParameters);
            foreach (var mappingInfo in properties.Values)
            {
                var propertyInfo = mappingInfo.PropertyInfo;
                var mappingField = mappingInfo.MappingField;
                var propertyType = propertyInfo.PropertyType;
                if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal))
                {
                    methodEmit
                    .ldloc(commandParameters)
                    .ldstr("@" + mappingField)                                      //Param 1 for MySqlParameter constructor
                    .ldarg_1
                    .call(propertyInfo.GetGetMethod())                              //Param 2 for MySqlParameter constructor
                    .newobj(typeof(MySqlParameter), typeof(string), typeof(object)) // Param for Add of DbParameterCollection
                    .call(typeof(DbParameterCollection).GetMethod("Add", new[] { typeof(object) }))
                    ;
                }
                else                 //Property that need to be convert to byte array before set
                {
                    var propetyValueLocal       = methodEmit.DeclareLocal(propertyType);
                    var dbSerializerHelperLocal = methodEmit.DeclareLocal(typeof(DbSerializerHelper));
                    var memoryStreamLocal       = methodEmit.DeclareLocal(typeof(MemoryStream));
                    var propertyByteArray       = methodEmit.DeclareLocal(typeof(byte[]));
                    methodEmit
                    .ldarg_1
                    .call(propertyInfo.GetGetMethod())
                    .stloc(propetyValueLocal)
                    .newobj(typeof(MemoryStream), Type.EmptyTypes)
                    .stloc(memoryStreamLocal);
                    methodEmit.BeginExceptionBlock();
                    methodEmit
                    .ldloc(memoryStreamLocal)
                    .newobj(typeof(BinaryWriter), typeof(Stream))
                    .newobj(typeof(DbSerializerHelper), typeof(BinaryWriter))
                    .stloc(dbSerializerHelperLocal)
                    .ldloc(dbSerializerHelperLocal)
                    .ldarg_1
                    .call(propertyInfo.GetGetMethod())
                    .call(typeof(DbSerializerHelper).GetMethod("Write", new[] { propertyType }))
                    .ldloc(memoryStreamLocal)
                    .call(typeof(MemoryStream).GetMethod("ToArray"))
                    .stloc(propertyByteArray)
                    .ldloc(commandParameters)
                    .ldstr("@" + mappingField)
                    .ldloc(propertyByteArray)
                    .newobj(typeof(MySqlParameter), typeof(string), typeof(object))                             // Param for Add of DbParameterCollection
                    .call(typeof(DbParameterCollection).GetMethod("Add", new[] { typeof(object) }))
                    .BeginFinallyBlock()
                    .ldloc(memoryStreamLocal)
                    .call(typeof(IDisposable).GetMethod("Dispose"))
                    .EndExceptionBlock()
                    ;
                }
            }

            methodEmit
            .ldloc(commandLocal)
            .call(typeof(DbCommand).GetMethod("ExecuteNonQuery"))
            .stloc(resultLocal)
            .ldarg_1
            .ldc_bool(false)
            .call(typeof(IDbObject).GetMethod("set_IsDirty"))
            .MarkLabel(objectNotDirtyLabel);

            //Update relation
            var          relations          = classMetadata.RelationProperties;
            LocalBuilder queryExecutorLocal = null;

            if (relations.Count > 0)
            {
                queryExecutorLocal = methodEmit.DeclareLocal(typeof(IQueryExecutor));
                var dbObjectContainerField = typeBuilderHelper.TypeBuilder.GetField("dbObjectContainer");
                methodEmit
                .ldfld(dbObjectContainerField)
                .call(typeof(DbObjectContainer).GetMethod("get_QueryExecutor"))
                .stloc(queryExecutorLocal);
            }
            foreach (var relationInfo in relations.Values)
            {
                var propertyInfo = relationInfo.PropertyInfo;
                var propertyType = propertyInfo.PropertyType;
                var elementType  = propertyType.IsGenericType ? propertyType.GetGenericArguments()[0] : propertyType;
                var listPersistentDbObjectLocal = methodEmit.DeclareLocal(typeof(IList <long>));
                var listCurrentType             = typeof(List <>).MakeGenericType(elementType);
                var addElementMethod            = typeof(ICollection <>).MakeGenericType(elementType).GetMethod("Add");
                var countElementMethod          = typeof(ICollection <>).MakeGenericType(elementType).GetMethod("Count");
                var listConstructorMethod       =
                    listCurrentType.GetConstructor(new[] { typeof(IEnumerable <>).MakeGenericType(elementType) });
                var listCurrentDbObjectLocal = methodEmit.DeclareLocal(listCurrentType);
                var mappingColumn            = relationInfo.PartnerKey;
                var relationCommandLocal     = methodEmit.DeclareLocal(typeof(DbCommand));
                var readerLocal           = methodEmit.DeclareLocal(typeof(DbDataReader));
                var relationTimeInfoLocal = methodEmit.DeclareLocal(typeof(TimeRelationInfo));
                var commandText           = "SELECT " + mappingColumn + " FROM " + mappingTable + " WHERE Id = @Id";
                methodEmit
                .ldarg_2
                .call(typeof(DbConnection).GetMethod("CreateCommand"))
                .stloc(relationCommandLocal)
                .ldloc(relationCommandLocal)
                .ldstr(commandText)
                .call(typeof(DbCommand).GetMethod("set_CommandText"))
                .ldloc(relationCommandLocal)
                .call(typeof(DbCommand).GetMethod("ExecuteReader"))
                .stloc(readerLocal)
                .ldstr(mappingColumn)
                .ldloc(readerLocal)
                .call(typeof(DbSerializerHelper).GetMethod("ReadRelationTimeInfo"))
                .stloc(relationTimeInfoLocal)
                .ldloc(relationTimeInfoLocal)
                .ldfld(typeof(TimeRelationInfo).GetField("idList"))
                .stloc(listPersistentDbObjectLocal)
                ;
                if (relationInfo.RelationKind == RelationInfo.RELATION_1_1)
                {
                    methodEmit
                    .newobj(listCurrentType, Type.EmptyTypes)
                    .stloc(listCurrentDbObjectLocal)
                    .ldloc(listCurrentDbObjectLocal)
                    .ldarg_1
                    .call(propertyInfo.GetGetMethod())
                    .call(addElementMethod)
                    ;
                }
                else
                {
                    methodEmit
                    .ldarg_1
                    .call(propertyInfo.GetGetMethod())
                    .newobj(listConstructorMethod)
                    .stloc(listCurrentDbObjectLocal)
                    ;
                }

                var lenLocal                                    = methodEmit.DeclareLocal(typeof(int));
                var iLocal                                      = methodEmit.DeclareLocal(typeof(int));
                var beginForLabel                               = methodEmit.DefineLabel();
                var beginForBodyLabel                           = methodEmit.DefineLabel();
                var itemLocal                                   = methodEmit.DeclareLocal(elementType);
                var itemIdLocal                                 = methodEmit.DeclareLocal(typeof(long));
                var itemNullLabel                               = methodEmit.DefineLabel();
                var getCurrentObjectElementMethod               = listCurrentType.GetMethod("get_Item", new[] { typeof(int) });
                var listPersistentContainCurrentElementLabel    = methodEmit.DefineLabel();
                var listPersistentNotContainCurrentElementLabel = methodEmit.DefineLabel();

                methodEmit
                .ldloc(listCurrentDbObjectLocal)
                .call(countElementMethod)
                .stloc(lenLocal)
                .ldc_i4_0
                .stloc(iLocal)
                .br(beginForLabel)
                .MarkLabel(beginForBodyLabel)
                .ldloc(listCurrentDbObjectLocal)
                .ldloc(iLocal)
                .call(getCurrentObjectElementMethod)
                .stloc(itemLocal)
                .ldloc(itemLocal)
                .brfalse(itemNullLabel)
                .ldloc(itemLocal)
                .call(typeof(IDbObject).GetMethod("get_Id"))
                .stloc(itemIdLocal)
                .ldloc(listPersistentDbObjectLocal)
                .ldloc(itemIdLocal)
                .call(typeof(ICollection <long>).GetMethod("Contain"))
                .brtrue(listPersistentContainCurrentElementLabel)

                .ldloc(queryExecutorLocal)
                .ldloc(itemLocal)
                .ldnull

                .call(typeof(IQueryExecutor).GetMethod("Insert", new[] { typeof(IDbObject), typeof(IsolationLevel?), typeof(long), typeof(string) }))

                .br(listPersistentNotContainCurrentElementLabel)
                .MarkLabel(listPersistentContainCurrentElementLabel)

                .MarkLabel(listPersistentNotContainCurrentElementLabel)
                .MarkLabel(itemNullLabel)
                .ldloc(iLocal)
                .ldc_i4_1
                .add
                .stloc(iLocal)
                .MarkLabel(beginForLabel)
                .ldloc(iLocal)
                .ldloc(lenLocal)
                .blt(beginForBodyLabel)
                ;
            }
        }
示例#27
0
		private void BuildSetter(MemberInfo mi, TypeBuilderHelper nestedType)
		{
			var methodType = mi.DeclaringType;
			var setMethod  = null as MethodInfo;

			if (mi is PropertyInfo)
			{
				setMethod = ((PropertyInfo)mi).GetSetMethod();

				if (setMethod == null)
				{
					if (_type != _originalType)
					{
						setMethod  = _type.GetMethod("set_" + mi.Name);
						methodType = _type;
					}

					if (setMethod == null || !IsMethodAccessible(setMethod))
						return;
				}
			}
			//else if (((FieldInfo)mi).IsLiteral)
			//	return;

			var method = nestedType.DefineMethod(_memberAccessor.GetMethod("SetValue", typeof(object), typeof(object)));
			var emit   = method.Emitter;

			emit
				.ldarg_1
				.castType (methodType)
				.ldarg_2
				.end();

			if (mi is FieldInfo)
			{
				var fi = (FieldInfo)mi;

				emit
					.CastFromObject (fi.FieldType)
					.stfld          (fi)
					;
			}
			else
			{
				var pi = (PropertyInfo)mi;

				emit
					.CastFromObject (pi.PropertyType)
					.callvirt       (setMethod)
					;
			}

			emit
				.ret()
				;

			nestedType.DefineMethod(_memberAccessor.GetProperty("HasSetter").GetGetMethod()).Emitter
				.ldc_i4_1
				.ret()
				;
		}
示例#28
0
        private static Type EnsureDelegateType(BuildContext context, MethodInfo method)
        {
            // The delegate should be defined as inner type of context.TypeBuilder.
            // It's possible, but we can not define and use newly defined type as Emit target in its owner type.
            // To solve this problem, we should create a top level delegate and make sure its name is unique.
            //
            string delegateName = context.TypeBuilder.TypeBuilder.FullName + "$" + method.Name + "$Delegate";
            Type   delegateType = (Type)context.Items[delegateName];

            if (delegateType == null)
            {
                ParameterInfo[] pi         = method.GetParameters();
                Type[]          parameters = new Type[pi.Length];

                for (int i = 0; i < pi.Length; i++)
                {
                    parameters[i] = pi[i].ParameterType;
                }

                const MethodImplAttributes mia = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
                const MethodAttributes     ma  = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;

                TypeBuilderHelper delegateBuilder = context.AssemblyBuilder.DefineType(delegateName,
                                                                                       TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass,
                                                                                       typeof(MulticastDelegate));

                // Create constructor
                //
                ConstructorBuilderHelper ctorBuilder = delegateBuilder.DefineConstructor(
                    MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard,
                    typeof(object), typeof(IntPtr));
                ctorBuilder.ConstructorBuilder.SetImplementationFlags(mia);

                MethodBuilderHelper methodBuilder;

                // Define the BeginInvoke method for the delegate
                //
                Type[] beginParameters = new Type[parameters.Length + 2];

                Array.Copy(parameters, 0, beginParameters, 0, parameters.Length);
                beginParameters[parameters.Length]     = typeof(AsyncCallback);
                beginParameters[parameters.Length + 1] = typeof(object);

                methodBuilder = delegateBuilder.DefineMethod("BeginInvoke", ma, typeof(IAsyncResult), beginParameters);
                methodBuilder.MethodBuilder.SetImplementationFlags(mia);

                // Define the EndInvoke method for the delegate
                //
                methodBuilder = delegateBuilder.DefineMethod("EndInvoke", ma, method.ReturnType, typeof(IAsyncResult));
                methodBuilder.MethodBuilder.SetImplementationFlags(mia);

                // Define the Invoke method for the delegate
                //
                methodBuilder = delegateBuilder.DefineMethod("Invoke", ma, method.ReturnType, parameters);
                methodBuilder.MethodBuilder.SetImplementationFlags(mia);

                context.Items[delegateName] = delegateType = delegateBuilder.Create();
            }

            return(delegateType);
        }
示例#29
0
        private JsonSchemaWrapper ResolveSchemaHelper(Uri curr, Uri parent, string data)
        {
            var definition = new
            {
                csharpType       = string.Empty,
                csharpInterfaces = new string[] { },
                properties       = new Dictionary <string, JObject>()
            };
            var deserialized = JsonConvert.DeserializeAnonymousType(data, definition);
            var dependencies = new List <JsonSchemaWrapper>();

            MatchCollection matches = Regex.Matches(data, @"\""\$ref\""\s*:\s*\""(.*.json)\""");

            foreach (Match match in matches)
            {
                // Get the full path to the file, and change the reference to match
                var currPath = new Uri(match.Groups[1].Value, UriKind.RelativeOrAbsolute);
                var currUri  = IoUtils.GetAbsoluteUri(parent, currPath, true);

                JsonSchemaWrapper schema;

                if (!_schemas.ContainsKey(currUri))
                {
                    schema = ResolveSchemaHelper(parent, currUri);
                    _schemas.Add(currUri, schema);
                }
                else
                {
                    schema = _schemas[currUri];
                }

                // Add schema to dependencies
                dependencies.Add(schema);
            }

            // Go through properties to see if there needs to be more resolving
            if (deserialized != null && deserialized.properties != null)
            {
                foreach (var s in deserialized.properties)
                {
                    var properties = s.Value.Properties();

                    // Check that the property also has a top level key called properties or items
                    foreach (var prop in properties)
                    {
                        var isProp = prop.Name.Equals("properties");
                        var isItem = prop.Name.Equals("items");

                        // TODO ehhhh let's avoid hardcoding this
                        if (isProp || (isItem && prop.Value.ToString().Contains("\"properties\"")))
                        {
                            var propData = isProp ? s.Value.ToString() : prop.Value.ToString();

                            // Create dummy internal Uri
                            var dummyUri = new Uri(new Uri(curr + "/"), s.Key);

                            JsonSchemaWrapper schema = ResolveSchemaHelper(dummyUri, curr, propData);

                            if (!_schemas.ContainsKey(dummyUri))
                            {
                                _schemas.Add(dummyUri, schema);
                            }
                        }
                    }
                }
            }

            // Set up schema and wrapper to return
            JsonSchema parsed;

            try
            {
                parsed = JsonSchema.Parse(StandardizeReferences(parent, data), _resolver);
            }
            catch (Exception)
            {
                _log.Error("Could not parse the schema: " + curr + "\nMake sure your schema is compatible." +
                           "Examine the stack trace below.");
                throw;
            }

            parsed.Id    = curr.ToString();
            parsed.Title = parsed.Title.SanitizeIdentifier();
            var toReturn = new JsonSchemaWrapper(parsed)
            {
                Namespace = _ns, Dependencies = dependencies
            };

            // If csharpType is specified
            if (deserialized != null && !string.IsNullOrEmpty(deserialized.csharpType))
            {
                // Create directories and set namespace
                int    lastIndex = deserialized.csharpType.LastIndexOf('.');
                string cType     = deserialized.csharpType.Substring(lastIndex == -1 ? 0 : lastIndex + 1);

                toReturn.Namespace    = deserialized.csharpType.Substring(0, lastIndex);
                toReturn.Schema.Title = cType;

                if (_createDirs)
                {
                    IoUtils.CreateDirectoryFromNamespace(_baseDir, toReturn.Namespace);
                }
            }

            // If csharpInterfaces is specified
            if (deserialized != null && deserialized.csharpInterfaces != null)
            {
                foreach (string s in deserialized.csharpInterfaces)
                {
                    // Try to resolve the type
                    Type t = Type.GetType(s, false);

                    // If type cannot be found, create a new type
                    if (t == null)
                    {
                        var builder = new TypeBuilderHelper(toReturn.Namespace);
                        t = builder.GetCustomType(s, !s.Contains("."));
                    }

                    toReturn.Interfaces.Add(t);
                }
            }

            return(toReturn);
        }
示例#30
0
		private void BuildGetter(MemberInfo mi, TypeBuilderHelper nestedType)
		{
			var methodType = mi.DeclaringType;
			var getMethod  = null as MethodInfo;

			if (mi is PropertyInfo)
			{
				getMethod = ((PropertyInfo)mi).GetGetMethod();

				if (getMethod == null)
				{
					if (_type != _originalType)
					{
						getMethod  = _type.GetMethod("get_" + mi.Name);
						methodType = _type;
					}

					if (getMethod == null || !IsMethodAccessible(getMethod))
						return;
				}
			}

			var method = nestedType.DefineMethod(_memberAccessor.GetMethod("GetValue", typeof(object)));
			var emit   = method.Emitter;

			emit
				.ldarg_1
				.castType (methodType)
				.end();

			if (mi is FieldInfo)
			{
				var fi = (FieldInfo)mi;

				emit
					.ldfld          (fi)
					.boxIfValueType (fi.FieldType)
					;
			}
			else
			{
				if (methodType.IsValueType)
				{
					var loc = emit.DeclareLocal(methodType);

					emit
						.stloc      ((byte)loc.LocalIndex)
						.ldloca_s   ((byte)loc.LocalIndex);
				}

				var pi = (PropertyInfo)mi;

				emit
					.callvirt       (getMethod)
					.boxIfValueType (pi.PropertyType)
					;
			}

			emit
				.ret()
				;

			nestedType.DefineMethod(_memberAccessor.GetProperty("HasGetter").GetGetMethod()).Emitter
				.ldc_i4_1
				.ret()
				;
		}
示例#31
0
        private void BuildSetter(MemberInfo mi, TypeBuilderHelper nestedType)
        {
            var methodType = mi.DeclaringType;
            var setMethod  = null as MethodInfo;

            if (mi is PropertyInfo)
            {
                setMethod = ((PropertyInfo)mi).GetSetMethod();

                if (setMethod == null)
                {
                    if (_type != _originalType)
                    {
                        setMethod  = _type.GetMethod("set_" + mi.Name);
                        methodType = _type;
                    }

                    if (setMethod == null || !IsMethodAccessible(setMethod))
                    {
                        return;
                    }
                }
            }
            //else if (((FieldInfo)mi).IsLiteral)
            //	return;

            var method = nestedType.DefineMethod(_memberAccessor.GetMethod("SetValue", typeof(object), typeof(object)));
            var emit   = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .ldarg_2
            .end();

            if (mi is FieldInfo)
            {
                var fi = (FieldInfo)mi;

                emit
                .CastFromObject(fi.FieldType)
                .stfld(fi)
                ;
            }
            else
            {
                var pi = (PropertyInfo)mi;

                emit
                .CastFromObject(pi.PropertyType)
                .callvirt(setMethod)
                ;
            }

            emit
            .ret()
            ;

            nestedType.DefineMethod(_memberAccessor.GetProperty("HasSetter").GetGetMethod()).Emitter
            .ldc_i4_1
            .ret()
            ;
        }
示例#32
0
		private void BuildIsNull(
			MemberInfo        mi,
			TypeBuilderHelper nestedType,
			Type              memberType)
		{
			var methodType = mi.DeclaringType;
			var getMethod  = null as MethodInfo;
			var isNullable = TypeHelper.IsNullable(memberType);
			var isValueType = (!isNullable && memberType.IsValueType);

			if (!isValueType && mi is PropertyInfo)
			{
				getMethod = ((PropertyInfo)mi).GetGetMethod();

				if (getMethod == null)
				{
					if (_type != _originalType)
					{
						getMethod  = _type.GetMethod("get_" + mi.Name);
						methodType = _type;
					}

					if (getMethod == null)
						return;
				}
			}

			var methodInfo = _memberAccessor.GetMethod("IsNull");

			if (methodInfo == null)
				return;

			var method = nestedType.DefineMethod(methodInfo);
			var emit   = method.Emitter;

			if (isValueType)
			{
				emit
					.ldc_i4_0
					.end()
					;
			}
			else
			{
				LocalBuilder locObj = null;

				if (isNullable)
					locObj = method.Emitter.DeclareLocal(memberType);

				emit
					.ldarg_1
					.castType (methodType)
					.end();

				if (mi is FieldInfo) emit.ldfld   ((FieldInfo)mi);
				else                 emit.callvirt(getMethod);

				if (isNullable)
				{
					emit
						.stloc(locObj)
						.ldloca(locObj)
						.call(memberType, "get_HasValue")
						.ldc_i4_0
						.ceq
						.end();
				}
				else
				{
					emit
						.ldnull
						.ceq
						.end();
				}
			}

			emit
				.ret()
				;
		}
示例#33
0
        private void BuildIsNull(
            MemberInfo mi,
            TypeBuilderHelper nestedType,
            Type memberType)
        {
            var methodType  = mi.DeclaringType;
            var getMethod   = null as MethodInfo;
            var isNullable  = TypeHelper.IsNullable(memberType);
            var isValueType = (!isNullable && memberType.IsValueType);

            if (!isValueType && mi is PropertyInfo)
            {
                getMethod = ((PropertyInfo)mi).GetGetMethod();

                if (getMethod == null)
                {
                    if (_type != _originalType)
                    {
                        getMethod  = _type.GetMethod("get_" + mi.Name);
                        methodType = _type;
                    }

                    if (getMethod == null)
                    {
                        return;
                    }
                }
            }

            var methodInfo = _memberAccessor.GetMethod("IsNull");

            if (methodInfo == null)
            {
                return;
            }

            var method = nestedType.DefineMethod(methodInfo);
            var emit   = method.Emitter;

            if (isValueType)
            {
                emit
                .ldc_i4_0
                .end()
                ;
            }
            else
            {
                LocalBuilder locObj = null;

                if (isNullable)
                {
                    locObj = method.Emitter.DeclareLocal(memberType);
                }

                emit
                .ldarg_1
                .castType(methodType)
                .end();

                if (mi is FieldInfo)
                {
                    emit.ldfld((FieldInfo)mi);
                }
                else
                {
                    emit.callvirt(getMethod);
                }

                if (isNullable)
                {
                    emit
                    .stloc(locObj)
                    .ldloca(locObj)
                    .call(memberType, "get_HasValue")
                    .ldc_i4_0
                    .ceq
                    .end();
                }
                else
                {
                    emit
                    .ldnull
                    .ceq
                    .end();
                }
            }

            emit
            .ret()
            ;
        }
示例#34
0
		private void BuildCloneValueMethod(
			MemberInfo        mi,
			TypeBuilderHelper nestedType,
			Type              memberType
			)
		{
			var methodType = mi.DeclaringType;
			var getMethod  = null as MethodInfo;
			var setMethod  = null as MethodInfo;

			if (mi is PropertyInfo)
			{
				getMethod = ((PropertyInfo)mi).GetGetMethod();

				if (getMethod == null)
				{
					if (_type != _originalType)
					{
						getMethod  = _type.GetMethod("get_" + mi.Name);
						methodType = _type;
					}

					if (getMethod == null || !IsMethodAccessible(getMethod))
						return;
				}

				setMethod = ((PropertyInfo)mi).GetSetMethod();

				if (setMethod == null)
				{
					if (_type != _originalType)
					{
						setMethod  = _type.GetMethod("set_" + mi.Name);
						methodType = _type;
					}

					if (setMethod == null || !IsMethodAccessible(setMethod))
						return;
				}
			}

			var method = nestedType.DefineMethod(_memberAccessor.GetMethod("CloneValue", typeof(object), typeof(object)));
			var emit   = method.Emitter;

			emit
				.ldarg_2
				.castType (methodType)
				.ldarg_1
				.castType (methodType)
				.end();

			if (mi is FieldInfo)
				emit.ldfld   ((FieldInfo)mi);
			else
				emit.callvirt(getMethod);

			if (typeof(string) != memberType && TypeHelper.IsSameOrParent(typeof(ICloneable), memberType))
			{
				if (memberType.IsValueType)
					emit
						.box       (memberType)
						.callvirt  (typeof(ICloneable), "Clone")
						.unbox_any (memberType)
						;
				else
				{
					var valueIsNull = emit.DefineLabel();

					emit
						.dup
						.brfalse_s (valueIsNull)
						.callvirt  (typeof(ICloneable), "Clone")
						.castclass (memberType)
						.MarkLabel (valueIsNull)
						;
				}
			}

			if (mi is FieldInfo)
				emit.stfld   ((FieldInfo)mi);
			else
				emit.callvirt(setMethod);

			emit
				.ret()
				;
		}
示例#35
0
        private void BuildMember(MemberInfo mi)
        {
            bool isValueType             = _originalType.IsValueType;
            TypeBuilderHelper nestedType = _typeBuilder.DefineNestedType(
                "Accessor$" + mi.Name, TypeAttributes.NestedPrivate, typeof(MemberAccessor));

            ConstructorBuilderHelper ctorBuilder = BuildNestedTypeConstructor(nestedType);

            BuildGetter(mi, nestedType);
            if (!isValueType)
            {
                BuildSetter(mi, nestedType);
            }
            BuildInitMember(mi, ctorBuilder);

            Type type = mi is FieldInfo ? ((FieldInfo)mi).FieldType : ((PropertyInfo)mi).PropertyType;

            BuildIsNull(mi, nestedType, type);

            if (type.IsEnum)
            {
                type = Enum.GetUnderlyingType(type);
            }

            string typedPropertyName = type.Name;

            if (type.IsGenericType)
            {
                Type underlyingType = Nullable.GetUnderlyingType(type);

                if (underlyingType != null)
                {
                    BuildTypedGetterForNullable(mi, nestedType, underlyingType);
                    if (!isValueType)
                    {
                        BuildTypedSetterForNullable(mi, nestedType, underlyingType);
                    }

                    if (underlyingType.IsEnum)
                    {
                        // Note that PEVerify will complain on using Nullable<SomeEnum> as Nullable<Int32>.
                        // It works in the current CLR implementation, bu may not work in future releases.
                        //
                        underlyingType = Enum.GetUnderlyingType(underlyingType);
                        type           = typeof(Nullable <>).MakeGenericType(underlyingType);
                    }

                    typedPropertyName = "Nullable" + underlyingType.Name;
                }
                else
                {
                    typedPropertyName = null;
                }
            }

            if (typedPropertyName != null)
            {
                BuildTypedGetter(mi, nestedType, typedPropertyName);
                if (!isValueType)
                {
                    BuildTypedSetter(mi, nestedType, type, typedPropertyName);
                }
            }

            if (!isValueType)
            {
                BuildCloneValueMethod(mi, nestedType, type);
            }

            // FW 1.1 wants nested types to be created before parent.
            //
            _nestedTypes.Add(nestedType);
        }
示例#36
0
		private void BuildTypedSetterForNullable(
			MemberInfo        mi,
			TypeBuilderHelper nestedType,
			Type              memberType)
		{
			var methodType = mi.DeclaringType;
			var setMethod  = null as MethodInfo;

			if (mi is PropertyInfo)
			{
				setMethod = ((PropertyInfo)mi).GetSetMethod();

				if (setMethod == null)
				{
					if (_type != _originalType)
					{
						setMethod  = _type.GetMethod("set_" + mi.Name);
						methodType = _type;
					}

					if (setMethod == null || !IsMethodAccessible(setMethod))
						return;
				}
			}

			var setterType = (memberType.IsEnum ? Enum.GetUnderlyingType(memberType) : memberType);
			var methodInfo = _memberAccessor.GetMethod("Set" + setterType.Name, typeof(object), setterType);

			if (methodInfo == null)
				return;

			var method = nestedType.DefineMethod(methodInfo);
			var emit   = method.Emitter;

			emit
				.ldarg_1
				.castType (methodType)
				.ldarg_2
				.newobj   (typeof(Nullable<>).MakeGenericType(memberType), memberType)
				.end();

			if (mi is FieldInfo) emit.stfld   ((FieldInfo)mi);
			else                 emit.callvirt(setMethod);

			emit
				.ret()
				;
		}
示例#37
0
        public Type Build(Type sourceType, AssemblyBuilderHelper assemblyBuilder)
        {
            if (sourceType == null)
            {
                throw new ArgumentNullException("sourceType");
            }
            if (assemblyBuilder == null)
            {
                throw new ArgumentNullException("assemblyBuilder");
            }

            // Check InternalsVisibleToAttributes of the source type's assembly.
            // Even if the sourceType is public, it may have internal fields and props.
            //
            _friendlyAssembly = false;

            // Usually, there is no such attribute in the source assembly.
            // Therefore we do not cache the result.
            //
            object[] attributes = sourceType.Assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true);

            foreach (InternalsVisibleToAttribute visibleToAttribute in attributes)
            {
                AssemblyName an = new AssemblyName(visibleToAttribute.AssemblyName);

                if (AssemblyName.ReferenceMatchesDefinition(assemblyBuilder.AssemblyName, an))
                {
                    _friendlyAssembly = true;
                    break;
                }
            }

            if (!sourceType.IsVisible && !_friendlyAssembly)
            {
                throw new TypeBuilderException(string.Format("Can not build type accessor for non-public type '{0}'.", sourceType.FullName));
            }

            string typeName = GetTypeAccessorClassName(_type);

            _typeBuilder = assemblyBuilder.DefineType(typeName, _accessorType);

            _typeBuilder.DefaultConstructor.Emitter
            .ldarg_0
            .call(TypeHelper.GetDefaultConstructor(_accessorType))
            ;

            BuildCreateInstanceMethods();
            BuildTypeProperties();
            BuildMembers();
            BuildObjectFactory();

            _typeBuilder.DefaultConstructor.Emitter
            .ret()
            ;

            Type result = _typeBuilder.Create();

            foreach (TypeBuilderHelper tb in _nestedTypes)
            {
                tb.Create();
            }

            return(result);
        }
示例#38
0
        private void BuildGetter(MemberInfo mi, TypeBuilderHelper nestedType)
        {
            var methodType = mi.DeclaringType;
            var getMethod  = null as MethodInfo;

            if (mi is PropertyInfo)
            {
                getMethod = ((PropertyInfo)mi).GetGetMethod();

                if (getMethod == null)
                {
                    if (_type != _originalType)
                    {
                        getMethod  = _type.GetMethod("get_" + mi.Name);
                        methodType = _type;
                    }

                    if (getMethod == null || !IsMethodAccessible(getMethod))
                    {
                        return;
                    }
                }
            }

            var method = nestedType.DefineMethod(_memberAccessor.GetMethod("GetValue", typeof(object)));
            var emit   = method.Emitter;

            emit
            .ldarg_1
            .castType(methodType)
            .end();

            if (mi is FieldInfo)
            {
                var fi = (FieldInfo)mi;

                emit
                .ldfld(fi)
                .boxIfValueType(fi.FieldType)
                ;
            }
            else
            {
                if (methodType.IsValueType)
                {
                    var loc = emit.DeclareLocal(methodType);

                    emit
                    .stloc((byte)loc.LocalIndex)
                    .ldloca_s((byte)loc.LocalIndex);
                }

                var pi = (PropertyInfo)mi;

                emit
                .callvirt(getMethod)
                .boxIfValueType(pi.PropertyType)
                ;
            }

            emit
            .ret()
            ;

            nestedType.DefineMethod(_memberAccessor.GetProperty("HasGetter").GetGetMethod()).Emitter
            .ldc_i4_1
            .ret()
            ;
        }
示例#39
0
        /// <summary>
        /// Try to get the DTO type from the parameters. If the DTO is not found, but an entity type is found, then clone the entity type to create a new DTO type..
        /// </summary>
        /// <param name="dtoTypeName">Name of the dto type.</param>
        /// <param name="dtoName">Name of the dto.</param>
        /// <param name="path">The path.</param>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="entityTypeName">Name of the entity type.</param>
        /// <returns></returns>
        private static Type GetDtoType(string dtoTypeName, string dtoName, string path, string entityName, string entityTypeName)
        {
            Type result     = null;
            Type entityType = null;

            // Search by type name
            if (!string.IsNullOrEmpty(dtoTypeName))
            {
                result = TypesManager.ResolveType(dtoTypeName);
                if (result != null)
                {
                    return(result);
                }
            }
            ISecurityManager securityManager = IoC.Get <ISecurityManager>();

            // Search by dto name
            if (!string.IsNullOrEmpty(dtoTypeName))
            {
                IMetamodelEntity metamodelEntity = securityManager.MetamodelManager.GetEntityByDtoName(dtoName);
                if (metamodelEntity != null)
                {
                    foreach (Type type in metamodelEntity.DtoTypes)
                    {
                        if (dtoName.ToLower().Equals(type.Name.ToLower()))
                        {
                            return(type);
                        }
                    }
                }
            }
            // search by entity name
            if (!string.IsNullOrEmpty(entityName))
            {
                IMetamodelEntity metamodelEntity = securityManager.MetamodelManager.GetEntityByName(entityName);
                if (metamodelEntity != null)
                {
                    if (metamodelEntity.DtoTypes.Count > 0)
                    {
                        return(metamodelEntity.DtoTypes[0]);
                    }
                    else
                    {
                        entityType = metamodelEntity.EntityType;
                    }
                }
            }
            // search by entity type
            if ((!string.IsNullOrEmpty(entityTypeName)) && (entityType == null))
            {
                entityType = TypesManager.ResolveType(entityTypeName);
                if (entityType != null)
                {
                    IMetamodelEntity metamodelEntity = securityManager.MetamodelManager.GetEntity(entityType);
                    if ((metamodelEntity != null) && (metamodelEntity.DtoTypes.Count > 0))
                    {
                        return(metamodelEntity.DtoTypes[0]);
                    }
                }
            }
            // If not found in own metamodel, because is not loaded into the system... but we can get the entity type by name from the telerik metamodel?
            if ((entityType == null) && (!string.IsNullOrEmpty(entityName)))
            {
                entityType = securityManager.Scanner.FindEntityTypeInMetamodel(entityName);
            }
            if ((entityType == null) && (!string.IsNullOrEmpty(path)))
            {
                entityType = securityManager.Scanner.FindEntityTypeInMetamodel(path);
            }
            if (entityType == null)
            {
                return(null);
            }
            result = TypeBuilderHelper.CloneCommonType(entityType, AppDomain.CurrentDomain, "Supido.Business.Dto", "SupidoDynamicModule", entityType.Name + "Dto");
            securityManager.Scanner.ProcessDynamicDto(result, entityType);
            return(result);
        }