Exemple #1
0
        /// <summary>
        /// Overrides the set property.
        /// </summary>
        /// <param name="propertyAccessor">The property accessor.</param>
        /// <param name="baseType">Type of the base.</param>
        /// <param name="type">The type.</param>
        /// <param name="loadMeMethodBuilder">The load me method builder.</param>
        /// <returns></returns>
        protected virtual MethodBuilder OverrideSetProperty(PropertyInfo propertyAccessor, Type baseType, TypeBuilder type, MethodBuilder loadMeMethodBuilder)
        {
            System.Reflection.MethodAttributes methodAttributes = MethodAttributes.Public
                                                                  | MethodAttributes.Virtual
                                                                  | MethodAttributes.HideBySig;

            string        methodName = "set_" + propertyAccessor.Name;
            MethodBuilder method     = type.DefineMethod(methodName, methodAttributes);
            // Preparing Reflection instances

            MethodInfo baseMethod = baseType.GetMethod(methodName);

            // Setting return type
            method.SetReturnType(typeof(void));
            // Adding parameters
            method.SetParameters(propertyAccessor.PropertyType);
            // Parameter value
            ParameterBuilder value = method.DefineParameter(1, ParameterAttributes.None, "value");
            ILGenerator      gen   = method.GetILGenerator();

            // Writing body
            //gen.Emit(OpCodes.Nop);
            //gen.Emit(OpCodes.Ldarg_0);
            //gen.Emit(OpCodes.Call, loadMeMethodBuilder);
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Call, baseMethod);
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ret);

            return(method);
        }
        private static MethodBuilder BuildMethodset_Id(TypeBuilder typeBuilder)
        {
            System.Reflection.MethodAttributes methodAttributes =
                System.Reflection.MethodAttributes.Public
                | System.Reflection.MethodAttributes.HideBySig;
            MethodBuilder method = typeBuilder.DefineMethod("set_Id", methodAttributes);
            // Preparing Reflection instances
            FieldInfo field1 = typeof(GraphDataEntity).GetField("_entityKey", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);

            // Setting return type
            method.SetReturnType(typeof(void));
            // Adding parameters
            method.SetParameters(
                typeof(String)
                );
            // Parameter value
            ParameterBuilder value = method.DefineParameter(1, ParameterAttributes.None, "value");
            ILGenerator      gen   = method.GetILGenerator();

            // Writing body
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Stfld, field1);
            gen.Emit(OpCodes.Ret);
            // finished
            return(method);
        }
Exemple #3
0
        static MethodBuilder CreatePropertyGetMethodWithBackingField(
            TypeBuilder typeBuilder, string name,
            MethodAttributes methodAttributes, FieldBuilder fieldBuilder)
        {
            MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + name, methodAttributes, fieldBuilder.FieldType, Type.EmptyTypes);

            ILGenerator getMethodILGenerator = getMethodBuilder.GetILGenerator();

            getMethodILGenerator.Emit(OpCodes.Ldarg_0);
            getMethodILGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
            getMethodILGenerator.Emit(OpCodes.Ret);

            return(getMethodBuilder);
        }
Exemple #4
0
        static MethodBuilder CreatePropertySetMethodWithBackingField(
            TypeBuilder typeBuilder, string name,
            MethodAttributes methodAttributes, FieldBuilder fieldBuilder)
        {
            MethodBuilder setMethodBuilder = typeBuilder.DefineMethod("set_" + name, methodAttributes, null, new Type[] { fieldBuilder.FieldType });

            ILGenerator setMethodILGenerator = setMethodBuilder.GetILGenerator();

            setMethodILGenerator.Emit(OpCodes.Ldarg_0);
            setMethodILGenerator.Emit(OpCodes.Ldarg_1);
            setMethodILGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            setMethodILGenerator.Emit(OpCodes.Ret);

            return(setMethodBuilder);
        }
 public InterpretedConstructor(
     InterpretedType declaringType,
     string name,
     ParameterInfo[] parameters,
     MethodAttributes attributes,
     MethodInvoker invoker,
     object invokableDefinition
     )
 {
     _declaringType      = declaringType;
     _name               = name;
     _parameters         = parameters;
     _attributes         = attributes;
     _invoker            = invoker;
     InvokableDefinition = invokableDefinition;
 }
        private void BuildAttributes()
        {
            if (method.IsStatic)
            {
                _Attributes |= System.Reflection.MethodAttributes.Static;
            }

            if (method.IsPublic)
            {
                _Attributes |= System.Reflection.MethodAttributes.Public;
            }
            else
            {
                _Attributes |= System.Reflection.MethodAttributes.Private;
            }
        }
Exemple #7
0
        private static MethodBuilder BuildMethod_Remove(TypeBuilder type, FieldInfo helperClassFieldInfo)
        {
            // Declaring method builder
            // Method attributes
            System.Reflection.MethodAttributes methodAttributes =
                System.Reflection.MethodAttributes.Public
                | System.Reflection.MethodAttributes.Virtual
                | System.Reflection.MethodAttributes.Final
                | System.Reflection.MethodAttributes.HideBySig
                | System.Reflection.MethodAttributes.NewSlot;
            MethodBuilder method = type.DefineMethod("Remove", methodAttributes);
            // Preparing Reflection instances
            FieldInfo  field1  = helperClassFieldInfo;
            MethodInfo method2 = typeof(SqlDataContextHelperClass).GetMethod(
                "Remove",
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                null,
                new Type[] {
                typeof(Object),
                typeof(String)
            },
                null
                );

            // Setting return type
            method.SetReturnType(typeof(void));
            // Adding parameters
            method.SetParameters(
                typeof(Object),
                typeof(String)
                );
            // Parameter entity
            ParameterBuilder entity = method.DefineParameter(1, ParameterAttributes.None, "entity");
            // Parameter fieldName
            ParameterBuilder fieldName = method.DefineParameter(2, ParameterAttributes.None, "fieldName");
            ILGenerator      gen       = method.GetILGenerator();

            // Writing body
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, field1);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Ldarg_2);
            gen.Emit(OpCodes.Callvirt, method2);
            gen.Emit(OpCodes.Ret);
            // finished
            return(method);
        }
Exemple #8
0
        /// <summary>
        /// Overrides the get property.
        /// </summary>
        /// <param name="propertyAccessor">The property accessor.</param>
        /// <param name="baseType">Type of the base.</param>
        /// <param name="type">The type.</param>
        /// <param name="loadMeMethodBuilder">The load me method builder.</param>
        /// <returns></returns>
        protected virtual MethodBuilder OverrideGetProperty(PropertyInfo propertyAccessor, Type baseType, TypeBuilder type, MethodBuilder loadMeMethodBuilder)
        {
            System.Reflection.MethodAttributes methodAttributes = MethodAttributes.Public
                                                                  | MethodAttributes.Virtual
                                                                  | MethodAttributes.HideBySig;

            string        methodName = "get_" + propertyAccessor.Name;
            MethodBuilder method     = type.DefineMethod(methodName, methodAttributes);
            // Preparing Reflection instances

            MethodInfo baseMethod = baseType.GetMethod(
                methodName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                null,
                new Type[] { },
                null
                );

            // Setting return type
            method.SetReturnType(propertyAccessor.PropertyType);
            // Adding parameters
            ILGenerator gen = method.GetILGenerator();
            // Preparing locals
            LocalBuilder localBuilder = gen.DeclareLocal(propertyAccessor.PropertyType);
            // Preparing labels
            Label label17 = gen.DefineLabel();

            // Writing body
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Call, loadMeMethodBuilder);
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Call, baseMethod);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label17);
            gen.MarkLabel(label17);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);

            return(method);
        }
Exemple #9
0
 public InterpretedMethod(
     Module module,
     InterpretedType declaringType,
     string name,
     Type returnType,
     ParameterInfo[] parameters,
     Lazy <MethodInfo[]> explicitOverrides,
     MethodAttributes attributes,
     GenericDetails generic,
     MethodInvoker invoker,
     object invokableDefinition
     )
 {
     _module             = module;
     _declaringType      = declaringType;
     _name               = name;
     _returnType         = returnType;
     _parameters         = parameters;
     _explicitOverrides  = explicitOverrides;
     _attributes         = attributes;
     _generic            = generic;
     _invoker            = invoker;
     InvokableDefinition = invokableDefinition;
 }
Exemple #10
0
        public static MethodBuilder DefineMethodReturningString(this TypeBuilder typeBuilder, string methodName, string returnValue, MethodAttributes methodAttributes)
        {
            MethodBuilder getMethodBuilder =
                typeBuilder.DefineMethod(methodName, methodAttributes, typeof(string), Type.EmptyTypes);

            ILGenerator ilGenerator = getMethodBuilder.GetILGenerator();

            ilGenerator.DeclareLocal(returnValue.GetType());
            ilGenerator.Emit(OpCodes.Nop);
            ilGenerator.Emit(OpCodes.Ldstr, returnValue);
            ilGenerator.Emit(OpCodes.Stloc_0);
            ilGenerator.Emit(OpCodes.Br_S, 2);
            ilGenerator.Emit(OpCodes.Ldloc_0);
            ilGenerator.Emit(OpCodes.Ret);
            return(getMethodBuilder);
        }
Exemple #11
0
 public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes)
 {
     throw null;
 }
Exemple #12
0
 public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes)
 {
     throw null;
 }
Exemple #13
0
 public System.Reflection.Emit.ConstructorBuilder DefineDefaultConstructor(System.Reflection.MethodAttributes attributes)
 {
     throw null;
 }
Exemple #14
0
 public static MethodBuilder DefineMethodReturningInt(this TypeBuilder typeBuilder, string methodName, int returnValue, MethodAttributes methodAttributes)
 {
     return(typeBuilder.DefineMethodReturningValueType(methodName, returnValue, methodAttributes));
 }
Exemple #15
0
 public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes)
 {
     throw null;
 }
 public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Type owner, bool skipVisibility)
 {
 }
Exemple #17
0
 public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers)
 {
     throw null;
 }
Exemple #18
0
 public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention)
 {
     throw null;
 }
Exemple #19
0
 public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes)
 {
     throw null;
 }
Exemple #20
0
        public static MethodBuilder DefineMethodReturningEnum(this TypeBuilder typeBuilder, string methodName, Enum returnValue, MethodAttributes methodAttributes)
        {
            MethodBuilder getMethodBuilder =
                typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Virtual, returnValue.GetType(), Type.EmptyTypes);

            ILGenerator ilGenerator = getMethodBuilder.GetILGenerator();

            ilGenerator.DeclareLocal(returnValue.GetType());
            ilGenerator.Emit(OpCodes.Ldc_I4, (int)(object)returnValue);
            ilGenerator.Emit(OpCodes.Stloc_0);
            ilGenerator.Emit(OpCodes.Ldloc_0);
            ilGenerator.Emit(OpCodes.Ret);
            return(getMethodBuilder);
        }
Exemple #21
0
        //use this instead
        //https://github.com/ltrzesniewski/InlineIL.Fody


        public static void GenerateCil()
        {
            var aName = new AssemblyName("DynamicAssemblyExample");
            var ab    =
                AssemblyBuilder.DefineDynamicAssembly(
                    aName,
                    AssemblyBuilderAccess.RunAndCollect);

            // For a single-module assembly, the module name is usually
            // the assembly name plus an extension.
            var mb =
                ab.DefineDynamicModule(aName.Name);

            var tb = mb.DefineType(
                "MyDynamicType",
                TypeAttributes.Public);

            // Add a private field of type int (Int32).
            var fbNumber = tb.DefineField(
                "m_number",
                typeof(int),
                FieldAttributes.Private);

            // Define a constructor that takes an integer argument and
            // stores it in the private field.
            Type[] parameterTypes = { typeof(int) };
            var    ctor1          = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                parameterTypes);

            var ctor1IL = ctor1.GetILGenerator();

            // For a constructor, argument zero is a reference to the new
            // instance. Push it on the stack before calling the base
            // class constructor. Specify the default constructor of the
            // base class (System.Object) by passing an empty array of
            // types (Type.EmptyTypes) to GetConstructor.
            ctor1IL.Emit(OpCodes.Ldarg_0);
            ctor1IL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
            // Push the instance on the stack before pushing the argument
            // that is to be assigned to the private field m_number.
            ctor1IL.Emit(OpCodes.Ldarg_0);
            ctor1IL.Emit(OpCodes.Ldarg_1);
            ctor1IL.Emit(OpCodes.Stfld, fbNumber);
            ctor1IL.Emit(OpCodes.Ret);


            // Define a default constructor that supplies a default value
            // for the private field. For parameter types, pass the empty
            // array of types or pass null.
            var ctor0 = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                Type.EmptyTypes);

            var ctor0IL = ctor0.GetILGenerator();

            // For a constructor, argument zero is a reference to the new
            // instance. Push it on the stack before pushing the default
            // value on the stack, then call constructor ctor1.
            ctor0IL.Emit(OpCodes.Ldarg_0);
            ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
            ctor0IL.Emit(OpCodes.Call, ctor1);
            ctor0IL.Emit(OpCodes.Ret);

            // Define a property named Number that gets and sets the private
            // field.
            //
            // The last argument of DefineProperty is null, because the
            // property has no parameters. (If you don't specify null, you must
            // specify an array of Type objects. For a parameterless property,
            // use the built-in array with no elements: Type.EmptyTypes)
            var pbNumber = tb.DefineProperty(
                "Number",
                PropertyAttributes.HasDefault,
                typeof(int),
                null);

            // The property "set" and property "get" methods require a special
            // set of attributes.
            const System.Reflection.MethodAttributes getSetAttr = MethodAttributes.Public |
                                                                  MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            // Define the "get" accessor method for Number. The method returns
            // an integer and has no arguments. (Note that null could be
            // used instead of Types.EmptyTypes)
            var mbNumberGetAccessor = tb.DefineMethod(
                "get_Number",
                getSetAttr,
                typeof(int),
                Type.EmptyTypes);

            var numberGetIL = mbNumberGetAccessor.GetILGenerator();

            // For an instance property, argument zero is the instance. Load the
            // instance, then load the private field and return, leaving the
            // field value on the stack.
            numberGetIL.Emit(OpCodes.Ldarg_0);
            numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
            numberGetIL.Emit(OpCodes.Ret);

            // Define the "set" accessor method for Number, which has no return
            // type and takes one argument of type int (Int32).
            var mbNumberSetAccessor = tb.DefineMethod(
                "set_Number",
                getSetAttr,
                null,
                new Type[] { typeof(int) });

            var numberSetIL = mbNumberSetAccessor.GetILGenerator();

            // Load the instance and then the numeric argument, then store the
            // argument in the field.
            numberSetIL.Emit(OpCodes.Ldarg_0);
            numberSetIL.Emit(OpCodes.Ldarg_1);
            numberSetIL.Emit(OpCodes.Stfld, fbNumber);
            numberSetIL.Emit(OpCodes.Ret);

            // Last, map the "get" and "set" accessor methods to the
            // PropertyBuilder. The property is now complete.
            pbNumber.SetGetMethod(mbNumberGetAccessor);
            pbNumber.SetSetMethod(mbNumberSetAccessor);

            // Define a method that accepts an integer argument and returns
            // the product of that integer and the private field m_number. This
            // time, the array of parameter types is created on the fly.
            var meth = tb.DefineMethod(
                "MyMethod",
                MethodAttributes.Public,
                typeof(int),
                new Type[] { typeof(int) });

            var methIL = meth.GetILGenerator();

            // To retrieve the private instance field, load the instance it
            // belongs to (argument zero). After loading the field, load the
            // argument one and then multiply. Return from the method with
            // the return value (the product of the two numbers) on the
            // execution stack.
            methIL.Emit(OpCodes.Ldarg_0);
            methIL.Emit(OpCodes.Ldfld, fbNumber);
            methIL.Emit(OpCodes.Ldarg_1);
            methIL.Emit(OpCodes.Mul);
            methIL.Emit(OpCodes.Ret);

            // Finish the type.
            var t = tb.CreateType();

            // The following line saves the single-module assembly. This
            // requires AssemblyBuilderAccess to include Save. You can now
            // type "ildasm MyDynamicAsm.dll" at the command prompt, and
            // examine the assembly. You can also write a program that has
            // a reference to the assembly, and use the MyDynamicType type.
            //
            var assembly  = Assembly.GetAssembly(t);
            var generator = new Lokad.ILPack.AssemblyGenerator();

            generator.GenerateAssembly(assembly, aName.Name + "_1.dll");

            GetCil(aName.Name + "_1.dll");

            var mi = t.GetMethod("MyMethod");
            var pi = t.GetProperty("Number");

            // Create an instance of MyDynamicType using the default
            // constructor.
            var o1 = Activator.CreateInstance(t);

            // Display the value of the property, then change it to 127 and
            // display it again. Use null to indicate that the property
            // has no index.
            Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));
            pi.SetValue(o1, 127, null);
            Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));

            // Call MyMethod, passing 22, and display the return value, 22
            // times 127. Arguments must be passed as an array, even when
            // there is only one.
            object[] arguments = { 22 };
            Console.WriteLine("o1.MyMethod(22): {0}", mi.Invoke(o1, arguments));

            // Create an instance of MyDynamicType using the constructor
            // that specifies m_Number. The constructor is identified by
            // matching the types in the argument array. In this case,
            // the argument array is created on the fly. Display the
            // property value.
            var o2 = Activator.CreateInstance(t, new object[] { 5280 });

            Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, null));
        }
Exemple #22
0
        public static MethodBuilder DefineMethodReturningValueType <TValue>(this TypeBuilder typeBuilder, string methodName, TValue returnValue, MethodAttributes methodAttributes)
            where TValue : struct
        {
            MethodBuilder getMethodBuilder =
                typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), Type.EmptyTypes);
            ILGenerator ilGenerator = getMethodBuilder.GetILGenerator();

            ilGenerator.DeclareLocal(typeof(int));
            ilGenerator.Emit(OpCodes.Nop);
            var returnType = typeof(TValue);

            if (returnType == typeof(int) || typeof(Enum).IsAssignableFrom(returnType))
            {
                ilGenerator.Emit(OpCodes.Ldc_I4, (int)(object)returnValue);
            }
            ilGenerator.Emit(OpCodes.Stloc_0);
            ilGenerator.Emit(OpCodes.Br_S, 2);
            ilGenerator.Emit(OpCodes.Ldloc_0);
            ilGenerator.Emit(OpCodes.Ret);
            return(getMethodBuilder);
        }
        /// <summary>
        /// Generates code for the modifier.
        /// </summary>
        /// <param name="attr">The attribute.</param>
        /// <returns>System.String.</returns>
        public string Modifier(MethodAttributes attr)
        {
            // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#methods

            /*
             *      ReuseSlot = 0,
             *  Final = 32, // 0x00000020
             *      Virtual = 64, // 0x00000040
             *      HideBySig = 128, // 0x00000080
             *
             *      VtableLayoutMask = 256, // 0x00000100
             *      NewSlot = VtableLayoutMask, // 0x00000100
             *
             *      CheckAccessOnOverride = 512, // 0x00000200
             *      Abstract = 1024, // 0x00000400
             *      SpecialName = 2048, // 0x00000800
             *      PinvokeImpl = 8192, // 0x00002000
             *      UnmanagedExport = 8,
             *      RTSpecialName = 4096, // 0x00001000
             *      ReservedMask = 53248, // 0x0000D000
             *      HasSecurity = 16384, // 0x00004000
             *      RequireSecObject = 32768, // 0x00008000
             */

            // TODO 'partial'

            /*	 method_modifier
             *      : 'new'
             | 'public'		\
             | 'protected'   | access
             | 'internal'    |
             | 'private'     /
             | 'static'
             | 'virtual'
             | 'sealed'
             | 'override'
             | 'abstract'
             | 'extern'
             | 'async'			//TODO async
             | method_modifier_unsafe
             |      ;
             */

            var        sb       = new StringBuilder();
            const uint @virtual = (uint)MA.Virtual;
            const uint @newslot = (uint)MA.NewSlot;
            const MA   mask     = (MA)0x0000FFF0;

            if ((attr & mask) == (MA.HideBySig | MA.Static | MA.PinvokeImpl))
            {
                sb.Append("static extern ");
            }
            else if ((attr & MA.Static) > 0)
            {
                sb.Append("static ");
            }
            if ((attr & MA.Abstract) > 0U)
            {
                sb.Append("abstract ");
            }
            if ((attr & MA.Final) > 0U)
            {
                sb.Append("sealed ");
            }
            if (((uint)attr & @virtual + @newslot) == @virtual + @newslot)
            {
                sb.Append("virtual ");
            }
            if (((uint)attr & @virtual + @newslot) == @virtual)
            {
                sb.Append("override ");
            }
            if ((attr & MA.UnmanagedExport) > 0U)
            {
                sb.Append("extern ");                                               // TODO ??
            }
            return(sb.ToString());
        }
Exemple #24
0
        public static object CreateInstance()
        {
            AssemblyName    aName     = new AssemblyName("UploadSessionModelBinder");
            AppDomain       appDomain = System.Threading.Thread.GetDomain();
            AssemblyBuilder aBuilder  = appDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run);
            ModuleBuilder   module    = aBuilder.DefineDynamicModule("UploadSessionModelBinder");

            TypeBuilder type = module.DefineType(
                "Krystalware.SlickUpload.Web.Mvc.UploadSessionModelBinder",
                TypeAttributes.Public | TypeAttributes.Class,
                typeof(Object),
                new Type[] {
                typeof(IModelBinder)
            }
                );

            //return type;

            // Declaring method builder
            // Method attributes
            System.Reflection.MethodAttributes methodAttributes =
                System.Reflection.MethodAttributes.Public
                | System.Reflection.MethodAttributes.Virtual
                | System.Reflection.MethodAttributes.Final
                | System.Reflection.MethodAttributes.HideBySig
                | System.Reflection.MethodAttributes.NewSlot;
            MethodBuilder method = type.DefineMethod("BindModel", methodAttributes);
            // Preparing Reflection instances
            MethodInfo method1 = typeof(SlickUploadContext).GetMethod(
                "get_CurrentUploadSession",
                BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
                null,
                new Type[] {
            },
                null
                );

            // Setting return type
            method.SetReturnType(typeof(Object));
            // Adding parameters
            method.SetParameters(
                typeof(ControllerContext),
                typeof(ModelBindingContext)
                );
            // Parameter controllerContext
            ParameterBuilder controllerContext = method.DefineParameter(1, ParameterAttributes.None, "controllerContext");
            // Parameter bindingContext
            ParameterBuilder bindingContext = method.DefineParameter(2, ParameterAttributes.None, "bindingContext");
            ILGenerator      gen            = method.GetILGenerator();
            // Preparing locals
            LocalBuilder locals = gen.DeclareLocal(typeof(Object));
            // Preparing labels
            Label label9 = gen.DefineLabel();

            // Writing body
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Call, method1);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label9);
            gen.MarkLabel(label9);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
            // finished
            return(type.CreateType().InvokeMember(null, BindingFlags.CreateInstance, null, null, null));
        }
Exemple #25
0
 public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes, System.Type[][] requiredCustomModifiers, System.Type[][] optionalCustomModifiers)
 {
     throw null;
 }
        public Type CreateDelegate(MethodInfo targetMethod, TypeBuilder parent, List <ParameterWrapper> methodParams)
        {
            typeCounter++;
            var typeBuilder = myModuleBuilder.DefineType(string.Format("TempModule.Controllers.{0}{1}{2}Delegate{3}", targetMethod.DeclaringType.Name, targetMethod.Name, targetMethod.GetParameters().Length, typeCounter),
                                                         TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass,
                                                         typeof(object));
            //var typeBuilder = myModuleBuilder.DefineType(string.Format("{0}{1}{2}Delegate", targetMethod.DeclaringType.Name, targetMethod.Name, targetMethod.GetParameters().Length), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(object));
            var imp            = typeBuilder.DefineField("implementation", parent, FieldAttributes.Public);
            var baseController = typeof(ServiceWrapperBase <>).MakeGenericType(targetMethod.DeclaringType).GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            var param = typeBuilder.DefineField("parameters", typeof(ParameterWrapper[]), FieldAttributes.Public);

            CreateDelegateCtor(typeBuilder);

            // Declaring method builder
            // Method attributes
            System.Reflection.MethodAttributes methodAttributes =
                System.Reflection.MethodAttributes.Assembly
                | System.Reflection.MethodAttributes.HideBySig;
            MethodBuilder method = typeBuilder.DefineMethod(targetMethod.Name, methodAttributes);
            // Preparing Reflection instances
            //FieldInfo field1 = typeof(<> c__DisplayClass2_0).GetField("<>4__this", BindingFlags.Public | BindingFlags.NonPublic);
            //FieldInfo field2 = typeof(Stardust.Interstellar.Rest.Service.ServiceWrapperBase<>).MakeGenericType(typeof(ITestApi)).GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic);
            //FieldInfo field3 = typeof(<> c__DisplayClass2_0).GetField("serviceParameters", BindingFlags.Public | BindingFlags.NonPublic);
            MethodInfo method4 = typeof(ParameterWrapper).GetMethod(
                "get_value",
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                null,
                new Type[] {
            },
                null
                );
            MethodInfo method5 = targetMethod;

            // Setting return type
            method.SetReturnType(targetMethod.ReturnType);
            // Adding parameters
            ILGenerator gen = method.GetILGenerator();

            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, imp);
            gen.Emit(OpCodes.Ldfld, baseController);
            var iii = 0;

            foreach (var item in methodParams)
            {
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldfld, param);
                EmitHelpers.EmitInt32(gen, iii);
                gen.Emit(OpCodes.Ldelem_Ref);
                gen.Emit(OpCodes.Callvirt, method4);
                if (item.Type.IsValueType)
                {
                    gen.Emit(OpCodes.Unbox_Any, item.Type);
                }
                else
                {
                    gen.Emit(OpCodes.Castclass, item.Type);
                }
                iii++;
            }
            gen.Emit(OpCodes.Callvirt, method5);
            gen.Emit(OpCodes.Ret);
            // finished


            var t = typeBuilder.CreateType();

            return(t);
        }
Exemple #27
0
        /// <summary>
        /// Reflection utility that implements a shader around any user defined shader.
        /// Creating code for any uniform defined.
        /// </summary>
        /// <param name="type">The shader type to derive from</param>
        /// <returns>A constructor to the derived type</returns>
        private static ConstructorInfo GetConstructor(Type type)
        {
            var baseBegin = ReflectionMarkerAttribute.FindMethod(
                typeof(Shader), ReflectionToken.ShaderBegin);

            if (type.IsNotPublic)
            {
                throw new Exception("Type " + type.Name + " must be public");
            }

            ConstructorInfo ctor;

            if (_ctors.TryGetValue(type, out ctor))
            {
                try
                {
                    return(ctor);
                }
                catch (Exception e)
                {
                    throw e.InnerException;
                }
            }

            var assemblyName = new AssemblyName {
                Name = "tmp_" + type.Name
            };
            var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            var module          = assemblyBuilder.DefineDynamicModule("tmpModule");
            var typeBuilder     = module.DefineType(type.Name + "_impl", TypeAttributes.Public | TypeAttributes.Class, type);

            var beginFun = typeBuilder.DefineMethod(baseBegin.Name, MethodAttributes.Virtual | MethodAttributes.Public, typeof(void), Type.EmptyTypes);
            var ilBeg    = beginFun.GetILGenerator();

            var getName = ReflectionMarkerAttribute.FindProperty(
                typeof(Shader), ReflectionToken.ShaderName).GetGetMethod();

            var nameIndex = ilBeg.DeclareLocal(typeof(IProgram)).LocalIndex;

            var shaderActivate = ReflectionMarkerAttribute.FindMethod(
                typeof(Shader), ReflectionToken.ShaderActivate);

            ilBeg.Emit(OpCodes.Ldarg, 0);
            ilBeg.Emit(OpCodes.Call, shaderActivate);
            ilBeg.Emit(OpCodes.Ldarg, 0);
            ilBeg.Emit(OpCodes.Call, getName);
            ilBeg.Emit(OpCodes.Stloc, nameIndex);

            foreach (var prop in type.GetProperties(BindingFlagsAny))
            {
                var attr = prop.GetCustomAttributes(typeof(UniformAttribute), false);
                if (attr.Length == 0)
                {
                    continue;
                }

                var info = TypeMap[prop.PropertyType.MetadataToken];

                var uniformCall = Binding.Resolve(info.Token);


                var f = typeBuilder.DefineField("m_" + prop.Name, typeof(int), FieldAttributes.Private);
                //var visibility = prop.PropertyType.IsPublic ? MethodAttributes.Public : MethodAttributes.Family;
                const MethodAttributes visibility = MethodAttributes.Public;

                var getter = prop.GetSetMethod() != null?prop.GetGetMethod().Name : "get_" + prop.Name;

                var setter = prop.GetSetMethod() != null?prop.GetSetMethod().Name : "set_" + prop.Name;

                var m   = typeBuilder.DefineMethod(setter, MethodAttributes.Virtual | visibility, typeof(void), new[] { prop.PropertyType });
                var ilg = m.GetILGenerator();

                ilg.Emit(OpCodes.Ldarg, 0);
                ilg.Emit(OpCodes.Ldfld, f);

                if (uniformCall.GetParameters().Length == 2)
                {
                    ilg.Emit(OpCodes.Ldarg, 1);
                }

                ilg.Emit(OpCodes.Call, uniformCall);
                ilg.Emit(OpCodes.Ret);

                m   = typeBuilder.DefineMethod(getter, MethodAttributes.Virtual | visibility, prop.PropertyType, Type.EmptyTypes);
                ilg = m.GetILGenerator();

                ilg.Emit(OpCodes.Newobj, typeof(NotImplementedException));
                ilg.Emit(OpCodes.Throw);
            }

            ilBeg.Emit(OpCodes.Ldarg, 0);
            ilBeg.Emit(OpCodes.Call, type.GetMethod(baseBegin.Name, Type.EmptyTypes));
            ilBeg.Emit(OpCodes.Ret);

            // implement in accessors
            foreach (var prop in type.GetProperties(BindingFlagsAny))
            {
                var attr = prop.GetCustomAttributes(typeof(VertexInAttribute), false);
                if (attr.Length == 0)
                {
                    continue;
                }

                var getter = prop.GetSetMethod() != null?prop.GetGetMethod().Name : "get_" + prop.Name;

                var setter = prop.GetSetMethod() != null?prop.GetSetMethod().Name : "set_" + prop.Name;

                //var visibility = prop.PropertyType.IsPublic ? MethodAttributes.Public : MethodAttributes.Family;
                const MethodAttributes visibility = MethodAttributes.Public;

                var m   = typeBuilder.DefineMethod(setter, MethodAttributes.Virtual | visibility, typeof(void), new[] { prop.PropertyType });
                var ilg = m.GetILGenerator();
                ilg.Emit(OpCodes.Newobj, typeof(NotImplementedException));
                ilg.Emit(OpCodes.Throw);

                m   = typeBuilder.DefineMethod(getter, MethodAttributes.Virtual | visibility, prop.PropertyType, Type.EmptyTypes);
                ilg = m.GetILGenerator();
                ilg.Emit(OpCodes.Newobj, typeof(NotImplementedException));
                ilg.Emit(OpCodes.Throw);
            }

            var timpl = typeBuilder.CreateType();

            ctor         = timpl.GetConstructor(Type.EmptyTypes);
            _ctors[type] = ctor;

            return(ctor);
        }