You can create your own Windows Forms, Web Forms, or class templates to reuse code and maximize your productivity in Visual Studio 2003.

Code reuse has been a mantra of software development for decades. .NET provides for code reuse in many ways including inheritance, components, and of course the indispensable function. Visual Studio 2003 expands the concept of reuse by providing a set of editable built-in templates for any project items, such as Windows Forms, Web Forms, or classes. Or to fully gain productivity benefits, you can create your own templates and tailor them to your specific needs.

Editing a Built-In Template

A template is a pattern with a custom format that is used as a starting point for building applications. Visual Studio provides a set of built-in templates for forms, classes, and other project items. When you add a class to a project, for example, Visual Studio uses a class template to provide you with the starting point for the class.

You may find that each of the code files for your business objects contains a standard comment header, a common list of imports, a usual definition of regions, and a predefined set of interfaces or method signatures.

But often the built-in templates don't provide all of the functionality that you want. In Visual Studio, you can edit the built-in templates or create custom templates.

You can find the majority of the built-in templates in your \Program Files\Microsoft Visual Studio .NET 2003 directory. The VB templates are in the Vb7\VBWizards subdirectory and the C# templates are in the VC#\VC#Wizards subdirectory.

Each type of item, such as Windows Forms, Web Forms, and classes, has its own folder under the appropriate VBWizards or VC#Wizards subdirectory. You can navigate down to an existing template file to edit any of the built-in templates.

For example, to edit the standard class template for VB, navigate to \Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBWizards\Class\Templates\ 1033\Class.vb. Open this file and add any code or comments that you wish to include in the built-in template. A common change is to include Option Explicit On in the standard VB class template as follows:

Option Strict On

Public Class [!output SAFE_ITEM_NAME]
    
End Class

For C#, navigate to \Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\ CSharpAddClassWiz\Templates\1033\NewCSharpFile.cs. Open this file and add any code or comments that you wish to include in the template. A common change is to include additional type imports in the standard C# class template as follows:

using System;
using System.Diagnostics;

namespace [!output SAFE_NAMESPACE_NAME]
{
   /// <summary>
   /// Summary description for [!output 
   /// SAFE_CLASS_NAME].
   /// </summary>
   public class [!output SAFE_CLASS_NAME]
   {
      public [!output SAFE_CLASS_NAME]()
      {
         //
         // TODO: Add constructor logic here
         //
      }
   }
}

Notice the [!output SAFE_ITEM_NAME] syntax in both of these examples. The Visual Studio wizard uses these directives to substitute the name you provide when you add a project item using the Add New Item dialog box.

Once you have updated a template file, save it and give it a try. Open any exiting project or create a new project. Right-click on the project and select Add then choose Add Class from the context menu. Give the class a name and click OK. Visual Studio create the class file using your revised template. Notice that Visual Studio substitutes the class name you specified into the appropriate locations in the template as defined by the template directives.

Creating a Project Item Template

As you develop or enhance applications, you will find that there are common elements in most of the Windows Forms, Web Forms, or business objects that you create. For example, you may find that each of the code files for your business objects contains a standard comment header, a common list of imports, a usual definition of regions, and a predefined set of interfaces or method signatures.

Templates are also great for team development efforts because they promote consistency in how the code is structured.

Each time you add a business object to your application, you could create all of the common elements again or go looking for a similar class and use the copy and paste method of reuse?but that is not very efficient. It is better to build a template that contains all of the reusable code and comments and then use it as a starting point each time you need a new business object.

The ability to edit the built-in templates is cool? and you could edit a built-in template to incorporate all of your custom needs. But you may want to keep your existing built-in templates simple and create new, special-purpose templates for more advanced requirements.

Creating your own templates for Windows Forms, Web Forms, classes, or other project items involves five basic steps:

After you finish this process, your template will appear in the Add New Item dialog box as shown in Figure 1. When you select your template from the Add New Item dialog box, Visual Studio will use the associated wizard file to execute the wizard and add a project item to your project using your template. All of code and comments that you put into your template will automatically be included in the new project item, giving you all of the common code you need before you even begin.

Figure 1: The template appears in the Add New Item dialog box.
Figure 1: The template appears in the Add New Item dialog box.

Let's go through this process in more detail by creating a class project item template for a custom business object (BO) both in VB and in C#.

Step 1: Creating a Wizard Directory

Following with the general reuse theme of this article, instead of creating a template and associated directories from scratch, use an existing template as a starting point. Start by locating the wizard subdirectory containing the template closest to the template you wish to create and copy the entire subdirectory.

It is important to copy the entire subdirectory because you will need all of the associated supporting files in order for your new template to work correctly within Visual Studio.

For this example, copy either the VB or C# class template. In VB, copy the entire \Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBWizards\Class directory. In C#, copy the entire \Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CsharpAddClassWiz directory. Rename the copied directory to any name you choose for your template wizard, such as BOTemplateWiz.

Step 2: Creating the Template

Since the wizard directory for the new template is a copy of an existing wizard directory, it already contains a template file. In the Templates\1033 subdirectory under the newly renamed BOTemplateWiz directory, change the name of the template file to any desired name. In this example, the VB file is changed to BOTemplate.vb and change the C# file to BOTemplate.cs.

For now, don't bother adding any code or comments to the template. Let's continue with the remaining steps to make this template work within Visual Studio?then we will add all of our custom code.

Step 3: Updating the Support Files

When you select a template from the Add New Item dialog box, Visual Studio executes a JavaScript script to copy the template, perform the name substitutions, and add the resulting item to your project. This script is located in the wizard directory that you copied in Step 1.

For VB, you need to manually update that script to provide it with the name of your template file. The script is located in \Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBWizards\BOTemplateWiz\Scripts\1033\default.js. You need to edit the line defining the template file name as follows:

var strTemplateFile = strTemplatePath + 
"\\BOTemplate.vb";

In C#, the script looks in an information file for the template file name so instead of updating the script directly, you need to update the information file. Open the information file in \Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\BOTemplateWiz\Templates\1033\Templates.inf. Edit this file to define your template file name as follows:

BOTemplate.cs

Your wizard directory is then ready. It contains your template and the script file that will process your template. Next you need to create a wizard file that points to your wizard directory so Visual Studio can find your wizard directory.

Step 4: Creating a Wizard File

Each wizard directory (defined in Step 1) needs an associated wizard file that defines the name of the wizard directory and other parameters needed by Visual Studio to find and process your template. Again, to make this step easy, simply copy a similar wizard file as a starting point.

For VB, copy the Class.vsz file in \Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBProjectItems to BOTemplateWiz.vsz. Then edit the wizard directory name in the file as follows:

VSWIZARD 6.0
Wizard=VsWizard.VsWizardEngine.7.1
Param="WIZARD_NAME = BOTemplateWiz"
Param="WIZARD_UI = FALSE"
Param="PROJECT_TYPE = VBPROJ"

For C#, copy the CSharpAddClassWiz.vsz file in \Program Files\Microsoft Visual Studio .NET 2003\VC#\CSharpProjectItems to BOTemplateWiz.vsz. Then edit the wizard directory name in the file as follows:

VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine.7.1
Param="WIZARD_NAME = BOTemplateWiz"
Param="WIZARD_UI = FALSE"
Param="PROJECT_TYPE = CSPROJ"

Your wizard file then has the information it needs to find and process your template. Now you just need to provide the name of the wizard file to the Add New Item dialog box. When you select the template from the Add New Item dialog box, it will use the wizard file to locate your template, execute the associated script, and add the project item to your project.

Step 5: Updating the VSDir File

The Add New Item dialog box uses a set of Visual Studio directory (VSDir) files to determine how each project item is to appear in the dialog and how to process an item when the user selects it.

After you have defined all of the required template, script, and wizard files for your new template, you need to create an entry for your template in the appropriate VSDir file so it appears as a project item in the Add New Item dialog box.

The Add New Item dialog box uses several different VSDir files, including one for the basic project items and one for each folder as shown in Figure 1. You can add your template to any number of these files, depending on how you want your template to appear in the Add New Item dialog box.

For this example, the item will only be added to the basic project items list. Edit the LocalProjectItems.vsdir file located in \Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBProjectItems\Local Project Items for VB and in \Program Files\Microsoft Visual Studio .NET 2003\VC#\CSharpProjectItems\LocalProjectItems for C#. Add a new line to the file that defines the information regarding your template.

For VB:

..\BOTemplateWiz.vsz|0|Deb's BO 
Template|15|Standard BO Template|{164B10B9-B200-
11D0-8C61-00A0C91E29D5}|4510|0|BOTemplate.vb

For C#:

..\BOTemplateWiz.vsz|0|Deb's C# BO 
Template|15|Standard BO Template|{FAE04EC1-301F-
11d3-BF4B-00C04F79EFBC}|4515|0|BOTemplate.cs

Each line contains the data elements needed by Visual Studio to define how the template is to appear in the Add Items dialog box and how the template should be processed when the user selects it. Each of the data elements are delimited by the pipe character (|) and described in Table 1.

At this point, try your template and ensure that it appears appropriately in the Add New Item dialog box. Open any exiting project or create a new project, right-click on the project, and select Add then choose Add Class from the context menu. Give the class a name and click OK. If all is well, Visual Studio will create a class file using your template.

If your template does not appear in the Add New Item dialog box, or if you receive an error when selecting the template from the Add New Item dialog box, recheck your files as described below.

In VB:

In C#:

Take special care in ensuring that you have the correct names in all of the correct places.

Customizing the Template File

At this point, your template should appear in the Add New Item dialog box?but the template is not yet customized. Go back and edit the BOTemplate.vb or BOTemplate.cs file and add any of the common elements that you want in your template. (You will not need to re-edit any of the other files.)

For this example, enter a standard comment header block. In C#, use the provided XML commenting feature. For VB, you can use a classic header comment style or manually enter XML-style comments (<summary>your comments go here...</summary>) for future compatibility with VB 2005. In both languages, define any common regions that you use in your classes.

Add any commonly used imports to the template using the Imports statement in VB or the using directive in C#. For example, in a C# business object your template may include:

using System.Diagnostics;
using System.Data;
using System.Configuration;

In VB, many of the common imports are already predefined as project properties. Right-click on the project, select Properties from the context menu, and click on Imports under the Common Properties folder to see the list of predefined project imports.

The most important step in defining a truly useful template is to create the standard set of interfaces or methods that are common to your business object. Most business objects have a method that obtains and populates the business object and a method that serializes or stores the business object. For this simplistic example, name the methods Retrieve and Save, respectively.

In VB:

''' &lt;summary&gt;
''' Retrieves the business object data.
''' &lt;/summary&gt;
''' &lt;param name="iID"&gt;Primary key for the business
''' object.&lt;/param&gt;
''' &lt;returns&gt;DataSet containing the business
''' object data.&lt;/returns&gt;
Public Function Retrieve(ByVal iID As Integer) _
   As DataSet
   As DataSet
   Dim ds As DataSet
   Dim sConn As String

   ' Obtain the connection string
   sConn = Configuration.ConfigurationSettings.
    AppSettings("CONNECTION").ToString()

   ' Retrieve the dataset
   'TODO: Add the name of the stored procedure 
   'as the third parameter
   ds = SqlHelper.ExecuteDataset(sConn, _
      CommandType.StoredProcedure, _
      "", _
      New SqlClient.SqlParameter("@ID", iID))

   'TODO: Set the table name
   ds.Tables(0).TableName = ""

   Return ds
End Function

In C#:

/// &lt;summary&gt;
/// Retrieves the business object data.
/// &lt;/summary&gt;
/// &lt;param name="iID"&gt;Primary key for the 
/// business object.&lt;/param&gt;
/// &lt;returns&gt;DataSet containing the business
/// object data.&lt;/returns&gt;
public DataSet Retrieve(integer iID)
{
   DataSet ds=null;
   string sConn=null;

   // Obtain the connection string
   sConn = ConfigurationSettings.
     AppSettings["CONNECTION"].ToString();

   // Retrieve the dataset
   //TODO: Add the name of the stored procedure as
   // the third parameter
   ds = SqlHelper.ExecuteDataset(sConn,
      CommandType.Text,
      "", 
      new SqlClient.SqlParameter("@ID", iID));

   //TODO: Set the table name
   ds.Tables[0].TableName = "";
   return ds;
}

Add any other methods such as validation, authentication, or any other common functionality that you use in your business objects. Include as much commenting and code in these methods as you can while still keeping the method general enough to be reused as a template. Make liberal use of the Task List features of Visual Studio and add “ToDo” notes to aid in using the template.

At any point, you can test your template. Just open any exiting project or create a new project, right-click on the project and select Add and then choose Add Class from the context menu, give the class a name, and click OK. If the class file is created with your new template, all is well.

Conclusion

You can use the technique described in this article to create templates for Windows Forms, Web Forms, classes, or any other type of project item.

Though, there are quite a few steps to this process, creating a template is not difficult and is really worth the effort, if you use the template frequently. Templates are also great for team development efforts because they promote consistency in how the code is structured. To share your template with another developer, copy the wizard subdirectory, the wizard file (.vsz), and the updated VSDir (.vsdir) file to the equivalent directories on the other developer's system.

Table 1: The fields in a VSDir file provide information to the Add New Item dialog box.

FieldDescription
..\BOTemplateWiz.vszDirectory location and name of the wizard file used to locate the project item template and add the item to the project.
0Optional GUID representing the product that has a DLL containing the resources needed by the wizard.
Deb's BO TemplateOptional name used within the Add New Item dialog box to define the template as shown in Figure 1. This can be a string or a resource ID.
15Integer representing the sort order for where the template should appear in the Add New Item dialog box.
Standard BO TemplateDescription of the template as it will appear in the Add New Item dialog box when the item is selected. (See the status bar area of Figure 1.) This can be a string or a resource ID.
{GUID}Full path to a DLL or EXE file or a GUID of a product that has a DLL file that contains an icon to load for the wizard. In this example, the value was copied from the line for the standard class template.
4510Optional resource ID of the icon to display. If not defined, the default icon for the DLL file (see the prior table entry) will be used. In this example, the value was copied from the line for the standard class template.
0Flags identifying specialized user interface behavior. (See the online help system under "VSDir Files" for more information.)
BOTemplate.vbThe default name for the template displayed in the Name field in the Add New Item dialog box, as shown in Figure 1.