A basic example of using the ExpandoObject for dynamic types in .NET C#

The ExpandoObject in the System.Dynamic namespace is an interesting option if you ever need to write dynamic objects in C#. Dynamic objects are ones that are not statically typed and whose properties and methods can be defined during runtime. I’ve come across this object while I was discovering the dynamic language runtime (DLR) features in .NET. We’ve seen an example of that in this post with the “dynamic” keyword.

Read more of this post

Advertisement

An example of using the dynamic keyword in C# .NET

The dynamic keyword in C# is similar to Reflection. It helps you deal with cases where you’re not sure of the concrete type of an object. However, you may expect the object to have a certain method that you can invoke at runtime. E.g. you have a framework that external users can write plugins for. You may set up a list of rules for the plugin to be valid, e.g. it must have a method called “Execute” and a property called “Visible”.

There are various ways you can solve this problem and one of them is dynamic objects. Using the dynamic keyword will turn off the automatic type checking when C# code is compiled. The validity of the code will only be checked at runtime.

Read more of this post

An example of using the dynamic keyword in C# .NET

The dynamic keyword in C# is similar to Reflection. It helps you deal with cases where you’re not sure of the concrete type of an object. However, you may expect the object to have a certain method that you can invoke at runtime. E.g. you have a framework that external users can write plugins for. You may set up a list of rules for the plugin to be valid, e.g. it must have a method called “Execute” and a property called “Visible”.

There are various ways you can solve this problem and one of them is dynamic objects. Using the dynamic keyword will turn off the automatic type checking when C# code is compiled. The validity of the code will only be checked at runtime.

Read more of this post

Create code at runtime with Reflection in .NET C#: Properties

In the previous post of this short series we saw how to add a field to our custom type using Reflection. In this finishing post we’ll look at properties and how to save our dynamic assembly.

Properties can be created in two ways. First we can use the PropertyBuilder class:

PropertyBuilder priceProperty = simpleType.DefineProperty("Price", PropertyAttributes.None, typeof(int), Type.EmptyTypes);

This will create a standard property called Price which returns an integer and has no input parameters. You’d write it like this in Visual Studio:

public int Price { get; set; }

For some reason the PropertyAttributes enumeration doesn’t let you refine the characteristics of the property as much as e.g. MethodAttributes or FieldAttributes do. In case you’d like to define the visibility of the property you need to turn to the MethodBuilder object and use it in a special way. The methods will perform the get/set methods separately. The following code example creates a get and set method:

MethodAttributes pricePropertyAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
MethodBuilder getPriceBuilder = simpleType.DefineMethod("get_Price", pricePropertyAttributes, typeof(int), Type.EmptyTypes);
MethodBuilder setPriceBuilder = simpleType.DefineMethod("set_Price", pricePropertyAttributes, null, new Type[] { typeof(int) });
priceProperty.SetGetMethod(getPriceBuilder);
priceProperty.SetSetMethod(setPriceBuilder);

The SpecialName and HideBySig values indicate that these methods are special and will not be part of the public interface. The name of the get/set methods must follow a convention: “get_XXX” and “set_XXX” where ‘XXX’ is the name of the property like get_Price.

The special methods can be associated with the property using the SetGetMethod and SetSetMethod methods of the PropertyBuilder object.

Once you’re done with your custom assembly then it can be persisted on disk using the Save method of AssemblyBuilder:

assemblyBuilder.Save(assemblyFileName);

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Fields

In the previous post of this short series we saw how to create a method using Reflection.

We can also create fields in our custom type. Here’s how to create a standard private field:

FieldBuilder fieldBuilder = simpleType.DefineField("_price", typeof(int), FieldAttributes.Private);

You can use the FieldAttributes enumeration to modify the properties of the field. E.g. here’s how to declare the field public and readonly – which is not a very clever combination, but there you have it:

FieldBuilder fieldBuilder = simpleType.DefineField("_price", typeof(int), FieldAttributes.InitOnly | FieldAttributes.Public);

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Methods

The previous post in this miniseries got us as far as defining a default and an overloaded constructor for our custom type:

ConstructorBuilder defaultConstructorBuilder = simpleType.DefineDefaultConstructor(MethodAttributes.Public);
ConstructorBuilder constructorBuilder = simpleType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });

We can add methods to the type in the following ways. Here’s how to create a void method called Calculate which accepts two integers as parameters:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public, null, new Type[] { typeof(int), typeof(int) });

Note the ‘null’ parameter which defines that there’s no return type. Consequently here’s how to add a return type of int:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public, typeof(int), new Type[] { typeof(int), typeof(int) });

If there are no parameters to the method then leave the last item as null:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public, typeof(int), null);

…and here’s how to define a static method:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public | MethodAttributes.Static, typeof(int), null);

We’ll of course need a method body as well and just like we saw in the case of constructors this operation can be quite complex. Check the post on creating constructors programmatically for my notes and links regarding the .NET intermediate language instructions, the ILGenerator and OpCodes objects for further information.

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Constructor

The previous post in this miniseries got us as far as defining a type using the TypeBuilder object:

TypeBuilder simpleType = moduleBuilder.DefineType("PluginSimpleType", TypeAttributes.Class | TypeAttributes.Public);
TypeBuilder extendedType = moduleBuilder.DefineType("PluginExtendedType", TypeAttributes.Class | TypeAttributes.Public, typeof(Customer), new Type[] {typeof(IEqualityComparer), typeof(IEquatable<int>) });

The TypeBuilder object is the entry point to creating the members of the Type such as constructors and methods. Here’s how you can create a public constructor with a string parameter:

ConstructorBuilder constructorBuilder = simpleType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });

If there’s no constructor for the Type then a default parameterless constructor is automatically created for you. If you declare an overloaded constructor like above then there will be no default constructor – this should be familiar to you from everyday OOP in .NET and Java. If you’d like to have a default empty constructor like this…

public Customer()
{
}

…besides the overloaded constructor then you can call the DefineDefaultConstructor method:

ConstructorBuilder defaultConstructorBuilder = simpleType.DefineDefaultConstructor(MethodAttributes.Public);

Otherwise if you’d like to have a parameterless constructor which has a body, i.e. does more than call the default constructor of the base class then you need to use the DefineConstructor method again:

ConstructorBuilder constructorBuilder = simpleType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);

Note the ‘null’ to denote 0 parameters.

This is not the end of the story. We need to attach a method body to the constructors(s) defined by the DefineConstructor method. We can leave the parameterless default constructor as it is, we don’t need any method body implementation for it.

This is where creating assemblies in code can become quite challenging.

Creating your method body requires intimate knowledge of the Microsoft Intermediate Language instructions that all .NET languages are translated into when compiled. I won’t even pretend that I know much about these instructions. The ILGenerator object can somewhat help you out so that you don’t need to write the actual byte code.

The OpCodes class stores more than 1000 instructions such as Ret for return, Call to call another method or Neg for negating a value.

You can get the ILGenerator object from the builder and call its Emit method to emit IL instructions. This is how you’d add a return statement:

ILGenerator msilGenerator = constructorBuilder.GetILGenerator();
msilGenerator.Emit(OpCodes.Ret);

More information about dynamic methods is available on MSDN here and here.

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Type

In the previous post we looked at how to create an Assembly and a Module in code. We ended up with a ModuleBuilder object as follows:

ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyPluginModule", assemblyFileName);

We can use the ModuleBuilder to define a Type. Example:

TypeBuilder simpleType = moduleBuilder.DefineType("PluginSimpleType", TypeAttributes.Class | TypeAttributes.Public);

“PluginSimpleType” will be the name of the type. We also declare that it will be a public class. The TypeAttributes enumeration allows you to define the properties of the Type such as abstract, interface, sealed, private etc.

It is also possible to indicate that the Type derives from a base class and/or it implements one or more interfaces:

TypeBuilder extendedType = moduleBuilder.DefineType("PluginExtendedType", TypeAttributes.Class | TypeAttributes.Public, typeof(Customer), new Type[] {typeof(IEqualityComparer), typeof(IEquatable<int>) });

extendedType derives from a class called Customer and implements IEqualityComparer and IEquatable of int.

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Assembly

We’ve looked at how to inspect assemblies, types and similar elements in other posts on Reflection – see link below. With Reflection you cannot only inspect assemblies but create new ones on the fly.

Why would you create a new .NET assembly programmatically? A typical scenario is when you have an application which allows users to create their plugins that your application can use in some way. Normally programmers can create such plugins and compile them into libraries based on some instructions on your website. However, what to do if you want to allow non-programmers to create their plugins? Or if the rules for creating the plugin are so complex that you don’t even trust programmers with the task? Then you can have a GUI where people can make their choices and you create the plugin for them based on the options they have selected.

The entry point to creating assemblies in code is found in the System.Reflection.Emit namespace. It contains Builder classes to build the elements of an assembly: AssemblyBuilder, EnumBuilder, EventBuilder, MethodBuilder etc. Most builders are quite descriptive of their function where the string before ‘Builder’ shows what can be built with it:

  • AssemblyBuilder
  • ConstructorBuilder
  • EnumBuilder
  • EventBuilder
  • FieldBuilder
  • LocalBuilder: to build local variables for methods and constructors
  • MethodBuilder
  • ModuleBuilder
  • ParameterBuilder: to build method parameters
  • PropertyBuilder
  • TypeBuilder

The first step towards creating an assembly with types and methods is creating an assembly and a module:

string assemblySimpleName = "MyGreatPlugin";
string assemblyFileName = string.Concat(assemblySimpleName, ".dll");
AssemblyName assemblyName = new AssemblyName(assemblySimpleName);			
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);

ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyPluginModule", assemblyFileName);

We first set up some basic information about the assembly simple name and the library name. We use the simple assembly name to construct an AssemblyName object. This is in turn used to create an AssemblyBuilder with the DefineDynamicAssembly method of the AppDomain class. The AssemblyBuilderAccess enumeration defines what the users can do with the assembly. Possible values:

  • RunAndSave: to save and execute an assembly which is probably what you want in a plugin scenario
  • Run: can be executed but not saved
  • RunAndCollect: can be executed and reclaimed from memory, read more here
  • Save: can be saved but not executed
  • ReflectionOnly: can be loaded into memory to inspect its element with Reflection but cannot be executed

Next we use the assembly builder to get a ModuleBuilder. The parameters into the DefineDynamicModule are the module name and the DLL file name where the module will be stored.

We’ll create a Type in the module in the next part.

View all posts on Reflection here.

Dynamically finding the value of a static field with Reflection in .NET C#

Say you do not have access to a .NET assembly at compile time but you want to execute code in it or read programmatic data from it.

One such scenario is when you’d like to extract some important field information from a class. Why would you ever need that?

Imagine that you have an application where people can upload their own plugins in the form of DLL’s. However, users do not programmatically build their own libraries in Visual Studio but rather use a GUI which will dynamically build a class file and compile it into a DLL based on the user’s selections on the GUI. This is possible if your users are not programmers or if the rules for the plugins are so complex that you wouldn’t want people to write their own solutions.

In such a scenario the class builder could write some important metadata in the form of static fields in the class, such as Version. E.g. if your app has multiple versions then the code generator would put the current version into the class so that your app can verify it. Then you can disallow plugins that were created with an older version of the app if the current version is not backward compatible.

Open Visual Studio 2012/2013 and create a new C# class library project called Domain. Add the following Customer class to it:

public class Customer
{
	private string _name;

	public Customer() : this("N/A")
	{}

	public Customer(string name)
	{
		_name = name;
	}

        public static readonly int VERSION = 2;
}

Build the solution and locate the compiled Domain.dll library. It should be located in either the Debug or Release folder within the bin folder depending on the compilation configuration in VS. Copy the .dll and put it somewhere else on your main drive where you can easily find it. We’re pretending that you got the library from another source but you for whatever reason cannot reference it at compile time.

Let’s see how we can dynamically extract the version number:

string pathToDomain = @"C:\Studies\Reflection\Domain.dll";
Assembly domainAssembly = Assembly.LoadFrom(pathToDomain);
Type customerType = domainAssembly.GetType("Domain.Customer");
FieldInfo versionInfo = customerType.GetField("VERSION");
int version = Convert.ToInt32(versionInfo.GetValue(null));

You should obviously adjust the path to Domain.dll.

Most of this code looks familiar from the posts on Reflection. We load the DLL and find the field called VERSION on the Customer type. We then extract the value of the field and pass in null as the instance parameter on which the field value should be found. It is null since the field is static, i.e. there’s no need for an instance. This is very similar to what we saw when calling a static method here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: