Monday, February 15, 2010

Customizing Visual Studio code templates to fit your needs

Did you ever get rid of that the default template on project context menu > add > class misses you prefered regions, default method overrides, properties or constructors?

Here is a guide how do you extend this template.

First you have to locate the class template that is used to provide code for the new class.

The template is stored at the templates directory located at
%VSINSTALLDIR%\Common7\IDE\ItemTemplates\[Language]\
for C# on Windows Vista and Windows 7 with Visual Studio 2008 this is usually
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\
There you have to locate the Code directory and then the directory for the installed locale. On my system the full path is
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1031\
The Template is stored within the Class.zip at this directory. Extract this archive to a temporary location for editing containing files.

Now you can customize the Class.cs file to fit your needs. The default Class.cs file looks something like this:
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
 
namespace $rootnamespace$
{
   class $safeitemrootname$
   {
   }
}

I extended my template with some default regions like the following:
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
 
namespace $rootnamespace$
{
   class $safeitemrootname$
   {
      #region Fields
      #endregion
    
      #region Properties         
      #endregion
 
      #region Constructors
 
      public $safeitemrootname$()
      {
         //
         // TODO: Add code here
         //
      }
 
      #endregion
 
      #region Methods
      #endregion
   }
}


Save the file and zip back all files to Class.zip. Now Close all instances of Visual Studio, go to command line and navigate to %VSINSTALLDIR%\Common7\IDE\. Type devenv.exe /setup and wait for finish, start Visual Studio and you're done.

Conclusion:
  1. locate class template
    usually at C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\[Locale]\
  2. extract files from Class.zip
  3. customize template file Class.cs
  4. zip back files to and exchange Class.zip
  5. run devenv.exe /setup
  6. run Visual Studio as usual
Guidance found on
How to: Locate and Organize Project and Item Templates
Customize Visual Studio 2005 Templates for Coding Productivity
Editing your Class Templates in Visual Studio .NET

No comments:

Post a Comment