Create user customizable functions in your application using CodeDom.

If a user wants the ability to customize buttons on a form, or a trader needs to develop custom formulas to execute his trading strategies then use CodeDom. These types of requirements can be easily accomplished using the CodeDom namespace. The System.CodeDom namespace is very powerful because it lets you compile source code at run time. The output is an assembly that can exist in memory or saved on your disk. We can use this feature of .NET to create customizable functions in our applicationswithout the need to compile and release new version.

Lets say a user creates a C# file called Formual1.cs to perform some calculations and need to use it in our program. In order to accomplish this we should have an interface the user must implement. This will make it easier for us to execute his or her code.

Here is the sample interface:

	public interface IFormula
	{
		double Calculate();
	}

The user creates his custom formula in a file Formula1.cs and it looks something like this:

	public class Formula1 : IFormula
	{
		public double Calculate()
		{
			return 1 / 5;  //Replace with actual formula
		}
	}

The interface, IFormula, must be compiled into our assembly, MyApp.exe. The idea is to invoke the custom formula using our interface and it must to exist in our assembly. We will use CodeDom to compile the new Formula1 class that will reference MyApp.exe.

To complie our file Formula1.cs we do the following:

	CompilerParameters compilerParams = new CompilerParameters(); 
	compilerParams.GenerateExecutable = false;
	compilerParams.GenerateInMemory = true;
	compilerParams.ReferencedAssemblies.Add("MyApp.exe");
	CSharpCodeProvider cscp = new CSharpCodeProvider();
	ICodeCompiler compiler = cscp.CreateCompiler(); 
	CompilerResults results = 
		compiler.CompileAssemblyFromFile(compilerParams, 
		"Formula1.cs");

The Formla1 source code has now been compiled and saved in the CompiledResults variable. To access the assembly we use the CompliedResults.ComiledAssembly property. The next step is to create an instance of our class so we can call the Calculate method.

The following will call the Formula1.Calculate method:

	Assembly assembly = results.CompiledAssembly;
	Type type = assembly.GetType("Formula1");
	IFormula formula = (IFormula) Activator.CreateInstance(type);
	formula.Calculate();

CodeDom can be very useful some developers, because it allows users to customize application without the need to compile and release new versions. I would suggest you spend a few minutes to become familiar with CodeDom. Then the next time a user asks Can I customize the formula myself? your answer would be Yes.