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...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

ASP.NET Working With Data-Bound Web Server Controls

Suppose we have: List<Car> vCars = new List<Car>(); There are three types of databound controls: Simple databound controls(List, AdRotater), Composite data bound controls(GridView, DetailsView, FormView that inherit from CompositeDataBoundControl), and Hierarchal data bound controls (TreeView, Menu).   DataBoundControl has a DataBind method that can be used when data is ready. It calls DataBind for child controls as well. Page.DataBind() will call DataBind for all child controls. Using DataSource Objects:                                       BaseDataBound control exposes DataSource property that accepts objects that implement IEnumerable , IListSource , IDataSource , or IHierarchalDataSource . DataSourceID accepts ID of SqlDataSource . If both specified Data...