Click here to Skip to main content
6,822,613 members and growing! (20,784 online)
Email Password   helpLost your password?
Development Lifecycle » Code Generation » General     Beginner License: The Code Project Open License (CPOL)

Visual Studio 2005 Project And Item Templates

By Abhishek Sur

All about Project and Item Templates. You can use Custom Templates to make your development process faster than you ever think. Create your own Template for Visual Studio and distribute with all others. You can also learn how to create an installer to install a template.
C# (C#2.0), VB (VB8.0), .NET (.NET2.0), ASP.NET, WinForms, WebForms, CEO, Architect, DBA, Dev, QA, Design, SysAdmin
Revision:6 (See All)
Posted:26 Oct 2008
Updated:27 Mar 2009
Views:22,157
Bookmarked:75 times
Unedited contribution
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
25 votes for this article.
Popularity: 5.80 Rating: 4.15 out of 5
1 vote, 4.0%
1

2
4 votes, 16.0%
3
7 votes, 28.0%
4
13 votes, 52.0%
5

Introduction 

As my previous article got me First Prize, I must write something new to my bag. Lets write how to manually create Project and Item templates for Visual Studio IDE.   

To know about creating templates for Visual Studio IDE, you must know what the templates are actually is, and what are these templates capable of. Lets talk about them one by one.

 Templates

Templates are the easy way to make custom project structure, associate parameters with them, so that you development teams doesn't have to write similar codes whenever the start a new project or add a new item on their projects, and thus it will increase productivity.
Generally while making our projects, we generally do waste so much of our valuable time just creating project items, files, writing Legal Notices on the beginning of each files, Specifying File creation dates, Configuring applications, Adding namespaces etc. These work eats up lots of essential time. So making a common templates on the project structure and sharing this with all the other developers in the company comes very handy. In this article we are going to learn how to make 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 the Figure Below) when a New project is created from File -> New Project option is selected from 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 to %ProgramFiles%\[MicrosoftVisualStudio8]\Common7\IDE\ProjectTemplates\ And for Custom Templates it searches to  %UserProfile%\MyDocuments\Visual Studio 2005\Templates\ProjectTemplates\. Under these folders the templates you will find lots of Zipped Archive. These files will be extracted  and added to your project based on one metadata file associated with each Archive. The Metadata file is of extension .vstemplate (Filename does not matters).
ProjectPopup.JPG

 2. Item Template  

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

addnewitem.png

In 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 \CSharp folder if you want your item or project template is to be displayed in the Csharp topic of the popup window, if you want Visual Basic, you should store it inside VisualBasic Folder.

Thus you can easily categorize templates during installation. Now I am going to show you how you can make templates using Wizard, and later on I will use manual approach to build a custom template and hence install it also.

Make a Template Using Wizard   

To make a template using Wizard, let us take follow the simple steps.

  1. Open an Existing Project with that much code within it, which is required by you when you open the Template for a new Project.
  2. You can Add some Parameters to the Files which will be replaced whenever new project is made from the template. Parameters are of two types,

USE OF PARAMETER

a. Template Parameter : As for the use of templates, Microsoft already defined some    custom parameters which you can use in your code. The Parameter list is given below: 

Parameter Name    Description  
clrversion     Replaces the current version of CLR.
GUID [1-10]  You can generated 10 Guid for a single project. It will be replaced with the unique GUIDs in the files
itemname   Name that User provides in Add Item popup dialog
machinename   Name of the Computer 
projectname    Replaces the Project name that user feeds into the Project Popup dialog
registeredorganization    Organization Name, for which the computer is registered. It takes the value from "HKLM\Software\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization"
rootnamespace   Namespace that you may use to add project files into. It returns the current Root Namespace Info.
safeitemname   Returns the current File name
safeprojectname  Returns the poject name that is choosen by the user during initial Project Dialog Popup
time   Returns time of File creation
userdomain   User domain registered.
username   Fetches current user name
year   Year of creation of files. 



You need to add $ to both ends when you use this parameters into the code files. Ex. $time$ will be replaced with the actually date/time of the project creation. More description of actual use of Parameters can be found here.

Now, take a look at the picture below:
CoolSnap1.JPG

The code for 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
    } 
} 


In the above code, I have used some parameters for the template which will be replaced when template is instantiated. The parameters will be replaced in the actual project. The actual class will look like this:


Coolsnap4.JPG

b. Custom Parameters: You can also make use of Custom Parameter made by you to replace into the files. Custom parameters can be added by directly editing the metadata file(.vstemplate). Just you need to add <customParameter> inside <TemplateContent> of the file like this, 

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

You can take a look at MSDN Help for adding custom Parameters from here.

3. Now after creating the whole application, that you need for templates, add the DLLS needed by the project, add namespaces to the desired files, as shown in the snapshot above, where I have added one dll into my project and also added one custom namespace to the project,Click on File -> Export as Template. A wizard will start, brings the following screen,
Snap2.JPG

From here, you can choose either Project Template or Item Template. For now we are chosing project Template. In the list below, you can select the project which you want to use as template, if you are having multiple number of projects into your solution.

4. After you click next. the wizard will  present you the following screen,
Snap3.JPG

In this screen, you will have to 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.
From this screen you can rename the Template name, give description and also if you wish you can automatically import the template to your visual studio. If you have selected the automatic import checkbox, it will place the same zipped archive into your Local userprofile Template Directory.

Now if you click on Finish, you are ready to go.
You can also move the zip files to different folders to categorize into that popup. Like if you wish the template will appear to the C# section, place the zip into the CSharp Folder and likewise.
You can get the template I have created from the link:
Download OrganizedClassLibrary.zip - 8.38 KB

In case of Item Templates, we need to choose the file that is to be used as template. The Item template will be stored inside ItemTemplate Folder of the Template Directory of Userprofile.

Note: In case of Exporting, you can add as many of your custom DLLs to the template, but it is preferable to use DLL registered in GAC, or rather you can also place the DLL into the ZIP archive for the template.

Understanding the MetaData

If you like to manually create the Template without using the IDE, you need to manually create all the files, associated with the template, place a solution file into it. Understanding Solution file is not our motto here. You also need to place one ICON file and name it as __TemplateIcon.ico, and manually place the metadata (.vstemplate) file within the zipped archive and finally have to place it into Template directory.

Now let us look at the Schema of .vsTemplate file:

<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>
		

Now try to delve more into the schema definition of the metadata file. The structure of vstemplate file consists of three elements:  


1. VSTemplate : This element wraps up the whole metadata elements into it. VsTemplate tag has two Attributes. One for the Version of .NET for which template is made. Secondly, Type attribute indicates if the template is Project or 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 that associates the Template
ProjectType Type of the Project, either Item or Project
ProjectSubType  Categorises so that it comes under a specific sub categories. 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 either enabled, disabled, or hidden for the project template. 
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. Lets look into its ChildElements:

ElementName Description
ProjectCollection Specifies the organization and contents of multi-project templates.  You can use this element when you require multiple project to be created for 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 

 You can create vsTemplate files using these elements. To find more try MSDN

Create Installer for Templates 

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

  1. First you need to create the Template File.
  2. Please 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 and Choose Global Assembly Cache, and add the Dll there. It will automatically install the dll into GAC and reference from that.


snapInstaller.JPG

    4. Run that Setup and see how it works. You can try my installer also to get sample template installed.

 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


Member
The guy is doing programming since 2001. Started his career with C, then C++ and so on. He completed his Masters in Computers from JIS, Kolkata. He likes to know the unknown. Now he is doing job as .NET Developer in a MNC. If you want to add him as buddy... Just click here... Or Directly Send Messages

To email abhi2434@yahoo.com
He is now working in a US Based Company in Kolkata.

His WebSite
Home page

Technical Blog
Programming Help and Tricks
Hidden Tips on Windows
.NET Ideas(My Previous Blog)

Most Importantly, He uses Orkut very often add him if you want

If you like this, Try reading some more:
Articles Listing
Description never ends, lots of secret with him. Make him your friend to learn more.

Dont forget to vote or share your comments about his Writing

Thanks in advance.
Occupation: Web Developer
Company: Buildfusion Inc
Location: India India

Other popular Code Generation articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralVERY NICE.. Pinmembermk.developer23:20 29 Dec '09  
GeneralVery nice and useful PinmemberAnurag Gandhi18:59 1 Dec '09  
GeneralRe: Very nice and useful PinassociateAbhishek Sur21:36 1 Dec '09  
GeneralGreat !! PinmemberAbhijit Jana4:07 24 Nov '08  
GeneralRe: Great !! PinmemberAbhishek Sur21:43 9 Dec '08  
GeneralRe: Great !! PinmemberJon_Boy7:13 27 Mar '09  
GeneralRe: Great !! PinmemberAbhishek Sur23:20 30 Mar '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 27 Mar 2009
Editor: Chris Maunder
Copyright 2008 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2010
Web10 | Advertise on the Code Project