- Posted by Ian Suttle on October 23, 2007
- Filed under Visual Studio
Download the sample code for this post.
I originally intended to write about customizing existing Visual Studio 2005 item templates such as the Class file to take the form of whatever you'd like, yet I decided that was the easy stuff. The real power is in creating your own item templates. You can likely discern how to customize an existing template based on this sample (email me if you have questions). There are a zillion reasons (literally!) why you may want to do this but a simple example that comes to mind is a custom exception. Granted the best practice of exceptions is to throw existing exception types but that would simply defeat the purpose of my example!
There are two important files included in this process:
1. Your custom file which is the template for the item
2. The .vstemplate file which provides some meta data about your custom item template
To spice up your custom template check out the available parameters to include in your file.
Here's a custom exception template which implements the four recommended constructors. I've called the file Exception.cs. Don't worry about naming conflicts with the base System.Exception type as the template specifies use of your project's root namespace. Additionally the user has the option to change the filename (seen here as $safeitemname$) or if the suggested name is kept a number is automatically appended to the filename such as Exception1.cs.
Exception.cs
Exception.vstemplate
Once you've created these files, zip them up into a file called, wait for it... Exception.zip. Drop that file in your "user item templates location" which you can find by going to Tools > Options > Projects and Solutions > General. So you have some general idea of where that might be on my system it's in C:\Documents and Settings\isuttle\My Documents\Visual Studio 2005\Templates\ItemTemplates\Visual C#.
Now for the feeling of accomplishment. Create or open a project and add a new item to it. You should see your "Exception Template" as an option under "My Templates."
If all goes well you'll have a file looking something like this:
Download the sample code for this post.