This is the third part of a series covering code generators in Visual Studio 2008. Part I and part II of this series cover how to create the project and all the necessary steps for writing a code generator.

First we need to modify the GetDefaultExtension() method and make it return a file extension. I like the idea of making it clear when the code is auto generated by a designer, so we’ll return “.designer.cs” as the extension.

Second we need to parse the input file. To make this blog post shorter, I will skip over the parsing details, but you can check the source zip for how we parse the file.

To generate the code we will use CodeDom which makes things easier. Right now the class should look like this:

Although CodeDom makes it rather easy to generate code, there is a library called LinqToCodedom on CodePlex that provides a whole set of extension methods and classes that help creating dynamic code.

The GenerateCode method needs to create a namespace, add a class definition to it and then add definitions for each of the defined constants. As you can see below, the code is really easy to make and to understand, but a bit verbose if the classes are complex:

Debugging the code

Fortunately debugging code generators is very easy due to a feature of Visual Studio called the “experimental hive”. Basically there is a copy of the related registry keys which can be used by VisualStudio when debugging instead of the main registry (to prevent hard to diagnose and fix problems). The Visual Studio SDK comes with a command line tool called ‘Reset the Microsoft Visual Studio 2008 Experimental hive’ which, as its name implies, resets this copy of the registry. So if something goes wrong, you can easily go back to the initial state of the experimental hive registry.

If you compile and run the code, a new Visual Studio window will appear. Create a new C# project (a ClassLibrary or Console project) and add a new text file to it. Name the file test.myfile and paste the definition into it. The moment you are saving the file, an automated file is created. If you’ve used the definition above, the generated file should look like this: