Creating and using Visual Studio templates

11 03 2008

We all use Visual Studio templates, day by day, even if not all of us know that they are actually called Visual Studio templates…. Just create a new project, and you’ll get to see a whole series of available Visual Studio templates that were installed along with VS itself… A C# console application project, a C# windows forms project, …, they are all Visual Studio templates…

New project dialogNew project dialog

In this post I’ll simply line out the way to create them, and how you can use them. You’ll be using this approach many times once you get going with Guidance Automation, since they are one of the key parts to defining the solutions and projects you want your package to unfold. This talk was inspired by GAT, but of course, you can use this knowledge for a lot of other scenario’s…

Why use Visual Studio templates?

Why would you use Visual Studio templates? Well, as I said, they are a key part to using Guidance Automation, but then again, what is Guidance Automation about? It’s about automating everyday tasks, it’s about reusability. Well, with templates, you can reuse structures, classes, and some concepts you already applied in previous projects. A template contains a lot of information and can create basic projects (such as a C# library containing some default folders you use) or more specialized projects (such as a C# domain layer that already implements some basics to using Domain-Driven-Design in your project)…

Let’s take off

Just imagine you have this great project, and you would like to get a template that contains all the stuff you have in this project… How do you get started? Well, it’s pretty simple, with some clicks Visual Studio does the job for you… Just open your project, click the menu “File”, “Export Template” and a new wizard appears.

Export template menu

You can then choose to create a project template or an item template. What’s the difference? Usage is…

When you create a project template, you will be able to use it from the “New Project” dialog once it is installed and all new projects based on this template will contain the features of your base-project. When you’re creating an item template, it will be available in the “Add new item” dialog, which appears when - for example – you right-click on a solution item.

You can give project templates a rightfully chosen name (remember that this name will be used in the “New project” dialog, so I suggest you make it meaningful yet simple), a custom icon and even a description that contains more information for the users. The same story for item templates: give them a sensible name, and if you want to, choose a custom icon to differentiate them rapidly.

For item templates, there’s more to choose. Once you have chosen the class you want to create a template of, VS will list all the namespace references this class has and ask you the ones you want to include in the template.

Export template reference selection

If the item template already contains some code, this is very necessary to have a buildable item in the first place.You’ll be thinking, this is easy, I could have figured that out myself… Well, it is! You just have to know it exists…

But now, let’s take it all a step further, let’s see what Visual Studio has generated for us…

The template file

Open a windows explorer and navigate to the path you save the template in. You’ll see that VS created a zip-file with the name you provided as template-name. When extracted, you’ll notice there’s a bunch of files in there… Let’s have a look.

Exported files

The most important file you want to have a look at, is “MyTemplate.vstemplate”. This is the actual template and contains the structure of the project. When you open it, you’ll see this is nothing but an XML-file, which can be divided in two major parts, the TemplateData and the TemplateContent.

The TemplateData-node contains a number of general properties for the template, such as it’s name, whether the template should create a new folder for the project, a default name, and so on… You can adjust every single one of these properties to your own preference.

<TemplateData>
 <Name>Domain</Name>
 <Description>Project for the Domain-layer of an application (DDD)</Description>
 <ProjectType>CSharp</ProjectType>
 ...
</TemplateData>

The other part, the information included in the TemplateContent-node, defines what the project consists of. First of all, it will reference a csproj-file, which the template uses to generate the project.

<TemplateContent>
 <Project TargetFileName="Goeleven.Web.RssAggregation.Domain.csproj" File="Goeleven.Web.RssAggregation.Domain.csproj" ReplaceParameters="true">
  <ProjectItem ReplaceParameters="true" TargetFileName="Model.cd">Model.cd</ProjectItem>
  <Folder Name="RssAggregate" TargetFolderName="RssAggregate">
   <Folder Name="Exceptions" TargetFolderName="Exceptions">
    <ProjectItem ReplaceParameters="true" TargetFileName="InvalidAggregateException.cs">InvalidAggregateException.cs</ProjectItem>
    <ProjectItem ReplaceParameters="true" TargetFileName="InvalidFeedException.cs">InvalidFeedException.cs</ProjectItem>
   </Folder>
  <ProjectItem ReplaceParameters="true" TargetFileName="RssFeedRepository.cs">RssFeedRepository.cs</ProjectItem>
  ...
  </Folder>
 </Project>
</TemplateContent>

You’ll notice an interesting parameter in the reference to the project-file, namely “ReplaceParameters”. What’s this for? Well, in the csproj-file, you can define some values that you will want to replace when the project is created, for example a namespace. Setting this property to true, will actually make the replacement occur. Within the Project-tag, you can only define two type of childnodes: ProjectItem-nodes and Folder-nodes. A ProjectItem-node can be used to add items to your projects. These items can be classes, documents, class diagrams, … and so on. A Folder-node will define a folder with the specified name, and inside each Folder-node, you can again add as many ProjectItem- and/or Folder-nodes as you want.

The project file

A csproj-file also contains of two key-nodes: PropertyGroup-nodes and ItemGroup-nodes.

PropertyGroup-nodes will typically contain general information such as the output type, default namespace, the target framework, whether to treat warnings as errors (which I suggest to always set to true!), … You’ll recognize all this information when you look at the project properties of some existing projects you have.

The ItemGroup-nodes, can contain another group of nodes. In here, you want to define the references the project must have by default, and the files you want to include in it. For each file, you can again specify it’s properties (compile, content, … ?).

<ItemGroup>
<Reference Include="Goeleven.Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a1fc815d91c11418, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\Dependencies\Goeleven.Framework.dll</HintPath>
</Reference>
...
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
...
</ItemGroup>

Now let’s get back to the “ReplaceParameters”-property I mentioned earlier… It’s in your project files and code files, that you will run into these parameters. You can simply recognize a parameter by the following format: $parameterName$. The dollar signs are just an indication that it’s a parameter, and that it will have to be replaced when used, the name you give it, will have to correspond with some value used later to fill it. The most common example is parameter $safeprojectname$. This one is used by Visual Studio itself in most of the templates. The “safeprojectname”-parameter will contain a name that won’t contain special characters and thus be safe. Another one, which is very important when using templates, is $guid1$. In the PropertyGroup-node, you’ll notice a property called “ProjectGuid”. This has to contain a unique Guid per project, but since it’s a template, we have to generate a new Guid per project. Well, we can just use “guid1”, “guid2”, “guid3”, until we have all the necessary Guid’s. VS will generate a new Guid for each new parameter and fill it in with the correct value.

<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
...
<ProjectGuid>$guid1$</ProjectGuid>
<ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
...
</PropertyGroup>

Note: You don’t want to adjust the ProjectTypeGuids-node, since these have to point to existing Guid’s. These point to a specific project type (which is again another template) on which this project is based, for example, a C# library. A feature that I also find very nice, is that you can define a PropertyGroup-node for each configuration you use in your project and thus adjust some properties according to the scenario. If you think it’s extreme to set the “TreatWarningsAsErrors” to true in a Debug-environment (which I don’t, but opinions differ ;) ), well, then you can activate it for Release-environments only.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
...
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
</PropertyGroup>

Well, I think I’ve covered the most important parts of Visual Studio templates and how to manage them. I hope you see the advantages of working with them.
Stay tuned!

Regards,
Laila Bougria


Actions

Information

2 responses to “Creating and using Visual Studio templates”

11 03 2008
Available Domain » Blog Archive » Creating and using Visual Studio templates (10:11:30) :

[...] Original post by IntoFactories.NET [...]

5 08 2008
ilmatte (16:10:05) :

Sorry if my comment is out of topic.
I would like to ask you how you were able to preserve the correct casing in the
xml samples.
I’m using the wordpress’s sourcecode tag as well but every tag name is turned to lowercase.
I will be thankful if you could help me.

Matteo

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>




Ignoring the Mommy Wars. Part 1
Rebecca Mark-Jusbasche is superwoman. A multimillionaire former executive, she was named one of Fortune magazine’s 50 Most Powerful Women in Business. She also raised twin boys while building her career, taking them as toddlers to Harvard Business School with her, then bringing them along on the corporate jet when she could. Granted, not everything went [..]

Hare of Howden
In Howdentown as I have heard ‘em tell Once there was a white hare, she used to there to dwell She’s been hunted by the greyhounds and the beagle-dogs did fare And there’s not a one amongst’em could keep up with that white hare She’s faster than the black, and she’s bonnier than the brown And there’s not a dog [..]

Online Pharmacy For Pain Relief Treatment
As a person gets older, having to put up with arthritis pain is one of the worst things to deal with. The elderly are not the only ones affected by arthritis pain; younger people can suffer from it as well. In this case a person would spend most of their life experiencing the pain of [..]

Muscle Relaxers Zanaflex without prescription. Pacient info.
If your doctor has prescribed the muscle relaxant Zanaflex (Tizanidine Hydrochloride) for you, and you are uncertain about what it is exactly or how you should take it, or if you merely wish to learn something about Zanaflex medication, this information may be helpful for you. You can purchase Zanaflex (Tizanidine Hydrochloride) in either tablet [..]


All News