Part II – Creating and registering a code generator class

Since VS2008 add-ins are COM objects, our code generator needs to be prepared for COM interop first. To accomplish this, we need to make it com visible and to assign it a unique identifier.

First, open up the Guids.cs file. We will add there a new constant that keeps our generator’s GUID. You can use the GUID tool in Visual Studio (Tools->Create GUID). Make sure you are using the registry format and remove the brackets. I’m not a big fan of the default coding style found in the pre-generated classes, but for simplicity I’ve kept the same style in our demo project:

The code generator has to be also registered as a code generator with Visual Studio and must implement the BaseCodeGeneratorWithSite abstract base class. When you register the code generator you have two options:

Register it with a human-readable name and then set it explicitly for a certain file. This method is especially useful if you have more generators that get the same input or if you don’t want to use the generator by default for a certain file. Another situation is where you don’t define a special extension but use already existing file types (XML for example).

Register it as a generator for a certain file extension. This is my favorite since I can create different file extensions for different scenarios. I will go with this option in my example, but you only have to change the name from “.extension” to whatever name you want.

In the attached zip file you will see that we have a CodeGeneratorRegistrationAttribute class. This can be found in the Visual Studio SDK or you can copy it from the zip. This file is responsible with creating the necessary registry keys for our generator. To register the generator we need to decorate it using this attribute:

The attribute tells Visual Studio that it should automatically use the generator for all *.myfile files. The vsContextGuids.vsContextGuidVCSProject tells Visual Studio that this generator should be used when editing a C# project. There are other options for different supported languages. The other parameters are self-explaining.