Click here to Skip to main content
Click here to Skip to main content

Visual Studio 2005 Project And Item Templates

By , 11 Jun 2010
Rate this:
Please Sign up or sign in to vote.

Introduction 

Since my previous article won a First Prize, I felt that I must write about something new. In this article I will describe how to manually create Project and Item templates for the Visual Studio IDE.

To know understand how to create these templates for Visual Studio, you must first understand what the templates actually are and what they are capable of doing. Lets talk about them one at a time.

Templates

Templates are an easy way to make custom project structures and associate parameters with them so that development teams do not have to write similar codes whenever they start a new project or add a new item on their existing projects. For this reason, templates will usually increase productivity.

Generally while building our projects, we waste much of our valuable time just creating project items, files, writing legal notices on the beginning of each file, specifying file creation dates, configuring applications, adding namespaces, etc. This work eats up lots of valuable time, so making a common set of templates for the project structure and sharing this with all the developers in the company comes very handy. In this article we will construct custom templates to make this happen.

There are two types of Templates:

1. Project Templates

Project templates are used when we create a new project and add them to our solution. The project template window pops up (as shown the figure below) when a new project is created from the File | New Project menu in the IDE. While opening the Dialog Box, Visual Studio searches some specific paths to get the Installed Templates and Custom Templates. For Installed Templates it searches %ProgramFiles%\[MicrosoftVisualStudio8]\Common7\IDE\ProjectTemplates\, while for Custom Templates it searches in %UserProfile%\MyDocuments\Visual Studio 2005\Templates\ProjectTemplates\. Inside these folders you will find lots of Zipped files. These files will be extracted and added to your project based on one metadata file associated with each zip file. The Metadata file has the extension .vstemplate (The filename does not matter.)

ProjectPopup.JPG

2. Item Templates

On the other hand, item templates are used whenever one adds a new item to the project. Item templates can be handy whenever we want to add some custom file types to a project. You can customize files to include legal notices, custom import/using statements, the default Namespace, the name, file creation date, etc. Similar to Project templates, installed item templates are stored in the %ProgramFiles%\[MicrosoftVisualStudio8]\Common7\IDE\ItemTemplates\#1033\ folder and custom item templates are stored in %UserProfile%\MyDocuments\Visual Studio 2005\Templates\ItemTemplates\.

addnewitem.png

In the case of both the Project templates and the Item templates, there is a specific folder structure, which enables you to pick the appropriate location of your item. You can choose the CSharp folder if you want your item or project template is to be displayed in the C# topic of the popup window or VisualBasic folder for Visual Basic. Thus you can easily categorize templates during installation.

In the follow section I will show you how to make templates using a Wizard, and later I will use a manual approach to build a custom template and also to install it.

Make a Template Using Wizard

To make a template using a Wizard, follow these simple steps:

1. Open an existing project containing most of the code required when you open the Template for a new Project.

2. Add Parameters to the files which will be replaced whenever a new project is made from the template. Parameters are of two types:

a. Template Parameter: Microsoft has already defined some parameters which you can use in your code. The list of parameters is given below:

Parameter Name Description
clrversion Replaces the current version of CLR.
GUID [1-10] You can generated 10 GUIDs for a single project. The parameter will be replaced with the unique GUIDs in the files
itemname Name that the user provides in Add Item popup dialog
machinename Name of the computer
projectname Replaces the Project name that user enters into the Project Popup dialog
registeredorganization Organization Name to which the computer is registered. It takes the value from the HKLM\Software\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization registry key
rootnamespace Namespace to add project files into. It returns the current root Namespace information
safeitemname Returns the current File name
safeprojectname Returns the project name chosen by the user in the Project Dialog
time Returns time of file creation
userdomain User domain name
username Fetches current user name
year Year of file creation

You need to add $ to the start end end of the parameter names in the code files, for example $time$ will be replaced with the actually date/time of the project creation. A complete description of these parameters can be found on the Microsoft web site.

An example using these parameters is shown here

The template code to create the file is:

// Legal Notice goes here
// File Created :  $time$
// Created By :    $username$

using System; 
using System.Collections; 
using System.IO;
using System.Text;
using MyOrganization.$safeprojectname$;

namespace MyOrganization.$safeprojectname$
{
    public class $safeitemname$
    {
        #region Variables
        //Declare Variables
        #endregion
       
        # region Properties
        // Declare Properties
        #endregion

        # region Events
        //Declare Events
        # endregion

        #region Constructors
        //Declare Constructors
        public $safeitemname$()
        {
        } 
        #endregion

        #region Methods
        //Declare Methods 
        #endregion
     } 
} 

The above code uses several parameters in the template which will be replaced in the actual project. The actual class will look like this:

Coolsnap4.JPG

b. Custom Parameters: You can also define your own custom parameters by directly editing the metadata file (.vstemplate). Simply add <CustomParameter> inside the <TemplateContent> elements of the metadata file like this:

<TemplateContent>
<CustomParameters>
        <CustomParameter Name="$CustomParameter1$" Value="Param1"/>
        <CustomParameter Name="$CustomParameter2$" Value="Param2">
</CustomParameters> 
</TemplateContent>  

Additional information on adding custom Parameters is available from MSDN Help.

3. After creating the application that will be used for templates, add the dlls and namespaces to the desired files. For example, as shown in the snapshot above, I have added one dll into my project and also a custom namespace to the project. When complete, click on File | Export as Template from the menu. A wizard will start, displaying the following screen:

Snap2.JPG

Here, you can choose either Project Template or Item Template. For now we choose Project Template. In the list, you can also select the project which you want to use as the template, if there are multiple projects in your solution.

4. After you click Next, the wizard will display the following screen:

Snap3.JPG

On this screen, choose the template icon which will be placed within the archive as __TemplateIcon.ico and which will later be used by the New Project Dialog box. On this screen you can also specify the Template name, enter a description and also automatically import the template into Visual Studio.

Clicking on Finish will generate the template. If you selected the automatic import checkbox, the zipped archive will be placed into your local userprofile template directory. You can also move the zip files into different folders to categorize the templates. For example, if you want the template to appear in the C# section, place the zip into the CSharp folder. The sample template I have created can be downloaded here: Download OrganizedClassLibrary.zip - 8.38 KB

In case of Item Templates, we choose the file that is to be used as the template and the Item template will be stored inside the ItemTemplate folder of the Template Directory for the user.

Note: When exporting, you can add as many custom dlls to the template as you like, but it is preferable to either use dlls registered in the GAC rather than place the DLL into the zip archive for the template.

Understanding the MetaData File

To manually create a template without using the IDE, it's necessary to manually create all the files associated with the template and place a solution file into it, but an explanation of the solution file will not be covered here. You also need to place one icon file named __TemplateIcon.ico and metadata (.vstemplate) file in the zipped archive and save it in the Template directory.

Let's take look at the schema of the .vsTemplate file shown below:

<VSTemplate Version="2.0.0" 
	xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>OrganizedClassLibrary</Name>
    <Description>Custom Class Library For My Orgarnization</Description>
    <ProjectType>CSharp</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>OrganizedClassLibrary</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <Project TargetFileName="TemplateLibrary.csproj" 
	File="TemplateLibrary.csproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="true" 
		TargetFileName="App.config">App.config</ProjectItem>
      <ProjectItem ReplaceParameters="true" 
		TargetFileName="BaseClassAll.cs">BaseClassAll.cs</ProjectItem>
      <Folder Name="Properties" TargetFolderName="Properties">
        <ProjectItem ReplaceParameters="true" 
		TargetFileName="AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
      </Folder>
    </Project>
    <References>
        <Reference>
            <Assembly>
                System, Version=2.0.0.0, 
			Culture=neutral, PublicKeyToken=b77a5c561934e089
            </Assembly>
        </Reference>
        <Reference>
            <Assembly>
                System.Data, Version=2.0.0.0, 
			Culture=neutral, PublicKeyToken=b77a5c561934e089
            </Assembly>
        </Reference>
    </References>    
   <CustomParameters>
        <CustomParameter Name="$CustomParameter1$" Value="Param1"/>
        <CustomParameter Name="$CustomParameter2$" Value="Param2">
    </CustomParameters>   
  </TemplateContent>
</VSTemplate>

The structure of the .vstemplate file consists of three elements:

1. VSTemplate: This element wraps the metadata elements. The VsTemplate tag has several attributes. The version attribute specifies the version of .NET for which template is made and the Type attribute indicates if the template is a Project or an Item template.

2. TemplateData: Defines how the template will be displayed in the New Project Dialog Box or New Item Dialog Box.

Child Elements:

Element Description
Name Specifies the name of the template as it appears in either the New Project or the Add New Item dialog box. It is required.
Description Specifies the description that comes with the template. It is required
Icon Icon file associated with the Template
ProjectType Type of Project, either Item or Project
ProjectSubType Specifies a specific sub-category. This is optional.Example :
<ProjectSubType>SmartDevice-NETCFv2</ProjectSubType>
Template ID Specifies the Template Id.
SortOrder Specifies the arrangement of Templates
CreateNewFolder Specifies if the folder is created when project is instantiated. This is optional
DefaultName The Default Generated Project Name
ProvideDefaultName Sets the default name of the Project or Item
EnableLocationBrowseButton Value specifying if browse button will be available or not
Hidden Specifies whether template will be listed or not
NumberofParentCategoriesToRollUp Specifies the number of parent categories that will display the template in the New Project dialog box.
LocationFieldMRUPrefix Optional
LocationField Specifies whether or not the Location text box in the New Project dialog box is enabled, disabled, or hidden.
SupportsMasterPage Whether template supports masterpage for web site
SupportsCodeSeparation Specifies whether the template supports code separation, or the code-behind page model, for web projects.
SupportsLanguageDropDown Specifies whether the template is identical for multiple languages, and whether the Language option is available from the New Project dialog box.

3. TemplateContent: Defines the file structure that the project will be making. Defines Custom Parameters, adds References to the project etc. Its ChildElements are as follows:

ElementName Description
ProjectCollection Specifies the organization and contents of multi-project templates. You can use this element when you require multiple projects to be created by your template. For Example:
<ProjectCollection>
  <ProjectTemplateLink 
         ProjectName="My Windows Application">
      WindowsApp\MyTemplate.vstemplate
    </ProjectTemplateLink>
 <ProjectTemplateLink 
             ProjectName="My Class Library">
    ClassLib\MyTemplate.vstemplate
   </ProjectTemplateLink>
 </ProjectCollection>
Project Specifies files or directories to add to the project. This is optional.
References Specifies the assembly references required for an item template
ProjectItem Specifies a file contained in the template
CustomParameters Specifies any custom parameters that are to be used when a project or item is created from the template

These elements can be used to manually create .vstemplate files. More information is available from MSDN

Create an Installer for Templates

To make an installer which installs your templates directly, you need to follow these steps:

  1. Create the Template File.
  2. Place the file into the desired folder i.e, %USERPROFILE%\My Documents\Visual Studio 2005\Templates directory.
  3. Install dlls that will be referenced from the templates into GAC. To do this, just right click on the File System Tab of Setup, Add Special Folders, choose Global Assembly Cache and add the dll there. The dll will be automatically installed into the GAC and referenced from it.

snapInstaller.JPG

4. Run Setup and see how it works. You can also try my sample installer which can be downloaded from the following URL:
Download InstallerApplication.zip - 355.26 KB

History

  • 1st Version of the Article Released as on 29th October, 2009
  • 2nd Version : Fixed the issue with layouts.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhishek Sur
Architect
India India
Did you like his post?
 
Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.
 
Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook
 
Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.
 
Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
Have any problem? Write to him in his Forum.
 
You can also mail him directly to abhi2434@yahoo.com
 
Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com
 
Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralGreat !! PinmemberAbhijit Jana24-Nov-08 3:07 
GeneralRe: Great !! PinmemberAbhishek Sur9-Dec-08 20:43 
GeneralRe: Great !! PinmemberJon_Boy27-Mar-09 6:13 
GeneralRe: Great !! PinmemberAbhishek Sur30-Mar-09 22:20 
GeneralRe: Great !! Pinmemberjoegarochoa12-Jun-10 1:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 11 Jun 2010
Article Copyright 2008 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid