Tuesday, September 4, 2012

Editing Visual Studio Templates the Easy Way

One of the double-edged swords of modern IDEs like MS Visual Studio and Eclipse is that they generate code. In Visual Studio, items (classes, web files, etc.) created within a project or solution, as well as project and solution files themselves, are based on templates which generate skeleton code using the filename and other metadata as parameters. Some of the most common generated elements are namespace imports (C# using statements), default namespace, and default constructors for classes. By changing the templates, we can change the generated code.

I won't delve into the reasons or technical aspects of changing the templates; if you're reading this you probably already have a use case and have found the basics at http://msdn.microsoft.com/en-us/library/6db0hwky%28v=vs.100%29 (for VS 2010). My purpose is to show how to make change testing easier and avoid the ridiculously long wait for the devenv /installvstemplates command.

The actual templates are stored as zip files in %DevEnvDir%ItemTemplates (from the VS command prompt). They are also cached, unzipped, in %DevEnvDir%ItemTemplatesCache. Generally, the procedure given for editing the templates is to unzip the files from ItemTemplates, edit the item, then either refresh the cache (the long-running command mentioned above) or copy the files, unzipped, to the cache directory. The important thing to understand is that the cache directory is actually what VS uses when it creates a new item, and changes made to files in that directory will take effect immediately. So why not edit directly from the cache? This way, changes made to the template can be tested without even restarting Visual Studio. Once the changes are tested and validated, the files can be zipped and backported to the ItemTemplates directory.

In short, by doing things backwards (editing the cache files and saving changes to the actual template directory), we eliminate the need to refresh the cache. Future installation changes or extensions to VS may perform this step automatically, so it is important to save the changes back to the zip file, but there is no need to run devenv /installvstemplates in this scenario.

No comments:

Post a Comment