views:

33

answers:

4

Recently I've been working with MSTest, and I noticed that the testframework generates accessor classes dynamically at compile time. How can one do this?

There's an xml file in a VS2010 C# project. I'd like to make an enum out of certain data in this xml file. Can this be done? And if so, how?

A: 

Method A) Read the xml file, parse it, generate C# code from it, write out the C# code to a temp file, compile that code; delete the temp file.

Method B) Read the xml file, parse it. Generate IL code directly from it using method in the System.Reflection.Emit namespace, or those in the System.CodeDom namespace.

James Curran
+1  A: 

MSTest achieves this in a couple of different ways. In short they essentially do the following IIRC

  1. Hook into the build system
  2. At the start of the build they generate their acessor's into hidden files in the project
  3. After the build completes they remove their files

You can achieve a similar effect via the same process. However hooking into the build system is a bit complicated. A much simpler approach is to build a custom tool / code generator and hook. This allows you to process a file at build time and spit out a corresponding code file to include in the build.

There are several examples on the web on how to achieve this. Here are a couple

JaredPar
A: 

The System.CodeDom Namespace is one option you have.

It allows you to automatically generate a class using C# Code and compile it as well.

You can maybe call this code as a postbuild during your build of your project.

This example shows how to create a class using this namespace

InSane
+1  A: 

I'd recommend T4 templates myself. Very easy to use and specifically designed to allow you to generate code during the build. http://msdn.microsoft.com/en-us/library/bb126445.aspx

Kirk Woll