Skip to main content

Creating Code at Runtime using .NET



Namespace: System.Reflection

Building Your Own Code:

System.Reflection.Emit namespace provide builder classes against each of the info classes i.e. ConstructorBuilder for ConstructorInfo etc.

Builder classes include: AssemblyBuilder, ConstructorBuilder, EnumBuilder, EventBuilder, FieldBuilder, LocalBuilder, MethodBuilder, ModuleBuilder, ParameterBuilder, PropertyBuilder, TypeBuilder.

Usage:
AssemblyName newAssemblyName = new AssemblyName();
newAssemblyName.Name = “MyTempAssembly”;

AssemblyBuilder asmBuilder =
                                AppDomain.CurrentDomain.DefineDynamicAssembly(newAssemblyName,
                  AssemblyBuilderAccess.RunAndSave);

ModuleBuilder dynamicModule = asmBuilder.DefinedynamicModule(“DynamicModule”,
           “MyTempAssembly”);

Defining types:

TypeBuilder myNewDynamicClass = dynamicModule.DefineType(“MNDClass”, TypeAttributes.Public | TypeAttributes.Class);

TypeBuilder myNewHashTable = dynamicModule.DefineType(“MyHashTable”,
TypeAttributes.Public | TypeAttributes.Class ,
typeof(HashTable),
new Type[] { typeof(IDisposable) } );

Creating Members:

Name
Description
DefineConstructor
Overloaded. Adds a new constructor to the dynamic type.
DefineDefaultConstructor
Defines the default constructor. The constructor defined here will simply call the default constructor of the parent.
DefineEvent
Adds a new event to the type, with the given name, attributes and event type.
DefineField
Overloaded. Adds a new field to the dynamic type.
DefineGenericParameters
Defines the generic type parameters for the current type, specifying their number and their names, and returns an array of GenericTypeParameterBuilder objects that can be used to set their constraints.
DefineInitializedData
Defines initialized data field in the .sdata section of the portable executable (PE) file.
DefineMethod
Overloaded. Adds a method to the type.
DefineMethodOverride
Specifies a given method body that implements a given method declaration, potentially with a different name.
DefineNestedType
Overloaded. Defines a nested type.
DefinePInvokeMethod
Overloaded. Defines a PInvoke method.
DefineProperty
Overloaded. Adds a new property to the type.
DefineTypeInitializer
Defines the initializer for this type.
DefineUninitializedData
Defines an uninitialized data field in the .sdata section of the portable executable (PE) file.

Creating  Constructor and Method:
 
ConstructorBuilder MyDynamicClassConstructor =
myNewDynamicClass.DefineDefaultConstructor(MethodAttributes.Public);

ILGenrator ConstructorCode = MyDynamicConstructor.GetILGenrator();
ConstructorCode.Emit(OpCodes.Ret); // Specifies the return statement.

MethodBuilder addMethod = myNewDynamicClass.DefineMethod(“Add”,
                                                                MethodAttributes.Public, null, new Type[] {typeof(string)});

To define static methods just add the MethodAttributes.Static.

FiledBuilder TotalElementsField = myNewDynamicClass.DefineField( “mTotalElements”,
                                                                                                                typeof(int), FieldAttributes.Private);

To define property that will return total elements from mTotalElements variable.

PropertyBuilder TotalElementsProperty = myNewDynamicClass.DefienProperty(“ToalElements”,
                                                                        PropertyAttributes.None, typeof(int), Type.EmptyTypes);

Now Define the Get method for Property.

MethodBuilder TotalElementsGetMethod = myNewDynamicClass.DefineMethod(“get_TotalElements”,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig);


MethodAttributes.SpecialName and MethodAttributes.HideBySig must be in-placed to ensure that it’s treated as get/set method of a property. Method name should be get_<PropertyName> or set_<PropertyName>.

TotalElementsProperty.SetGetMethod(TotalElementsGetMethod);

asmBuilder.Save(“MyTempAssembly.dll”);

DynamicMethod
You can use the DynamicMethod class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the DynamicMethod object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code.

Comments

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Using ADO.NET Transaction Object, Saving CLR Objects and SqlNotificationRequest

Serializable allows one transaction to complete before the other start. SqlConnectoin support named savpoint to roll back to; that’s an equaliant to save transaction command in MS SQL Server. Using TransactionScope Object : A transaction can’t span multiple connections.   Local and distributed transaction ares supported in 1.x you have to Enterpeise seveices library to regiser multiple connections and then call EnlistDistributedTransaction. Distributed Transaction Coordinator is required for Distributed transaction that’s available on windows 2000 & +. In 2.X and later use TransactionScope object. Serializable allows one transaction to complete before the other start. SqlConnectoin support named savpoint to roll back to; that’s an equaliant to save transaction command in MS SQL Server. Using TransactionScope Object : Dispoase of the transaction must be called to complete the transaction. Distributed Transaction : ...

Code Access Security in .Net

Namespace: System.Security What is Code Access Security? Code Access Security is a mechanism through which Developers and administrators can restrict code from accessing different resources , without caring about the users’ access level. You can also control resource that can’t be controlled through traditional RBS (Role Based Security), e.g. Web Requests and DNS requests etc. It can be only applied to Managed Applications. These restriction are applied not to the user instead to the Application, thus it does not require username or password. Evidence: It is the information that runtime gather about the assembly to determine which Code Groups the assembly belongs to. The following table shows the common types of evidence that a host can present to the runtime. Evidence Description Application directory The application's installation directory. Hash Cryptographic hash such as SHA1. Publisher Soft...