
Define Templates for Generating Code #50
Chapter 6, Speed Hacks
|
197
HACK
code again without losing your changes to the code. The CodeSmith cus-
tom tool performs what is called active code generation. Active code genera-
tion is when code is generated on the fly, usually during the build process of
your solution. Using active code generation, you almost never modify the
code generated, since it would simply be overwritten the next time you build
your solution. The CodeSmith custom tool is a little bit different in that it
generates the code when you save the file, as opposed to during the build
process, but the result is the same. (You could also create a custom build
step to execute the templates
[Hack #34].)
The first step in using CodeSmith is downloading and installing it. Code-
Smith can be downloaded from http://www.ericjsmith.NET/codesmith. Dur-
ing the installation process, you will be asked if you want to add support for
Visual Studio—be sure to answer yes.
Creating a Template
To make use of this tool, you first need to add a new CodeSmith template to
your Visual Studio Project by right-clicking on your project and choosing
Add New Item. From the Add New Item dialog, choose Text File and save
the file with a .cst extension. (You could also create a new template from the
CodeSmith Explorer window.)
Here is a simple CodeSmith template to generate a dictionary-based collec-
tion—you can put this ...