P3.NET

Creating Item Templates in Visual Studio 2017

Many times when you are adding a new item to a project you probably find yourself changing the generated item to line up with your coding or company styles. Often this includes a copyright, perhaps the ordering of members in a type or even completely replacing the item with something else, like an enum. Visual Studio is designed to be extensible. Item templates allow you to create your own templates and have them available in VS so you don’t have to keep making the same changes over and over again. In VS 2017 templates are even easier to create than before. I will discuss how easy it is to add new templates in this article.

Item Templates

Before creating an item template you need to understand what it is. Open any projects in VS and then right click the project and select Add and then any item under there (eg. New Item). What pops up is Add New Item dialog. Each of these is an item template. Item templates can come from anywhere including the core VS installation, extensions you install later and from the file system. Under your Documents folder where VS stores your information is a folder where it looks for your custom item templates (default for VS 2017 is Visual Studio 2017\Templates\ItemTemplates.

Templates are designed to quickly allow you to add new files to your projects without having to redo the same changes each time. While you can edit the provided templates I would not recommend it for several reasons. Firstly the changes may get lost on the next update. Secondly reinstalling VS would wipe the templates and templates between versions may change. Thirdly, sometimes you really do want the original templates available so replacing them is not a good idea.

Creating a new template really just involves creating the skeleton file(s) with the content you want and adding some metadata so VS knows what to display. Unfortunately templates are very limited in what they can do. Any sort of programmatic changes will require using a wizard instead.

Extension Class Template

Extension classes are pretty common in code these days so we’ll create a template that handles this for us. The easiest way to get started is to take an existing extension class and make it generic.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    /// <summary>Provides extension methods for SomeType.</summary>
    public static class SomeTypeExtensions
    {
        public static void DoSomething ( this SomeType source )
        {
        }
    }
}

Now to make it reusable. Firstly the user will provide a name for the new item when they create it so we want to use that as the class name. In a template you can use the $safeitemname$ value. Find all places in the file that use the class name and replace them. Notice the parameter is called –safe. VS will remove characters from the name that are not valid as identifiers.

The namespace should follow the default project namespace. Additionally the folder in which the item is dropped into should be included to follow convention. Fortunately there is a parameter for that as well $rootnamespace$. Replace the namespace name with this as well. Sidenote that MSDN mentions that you can use $safeprojectname$ for the namespace but this does not appear accurate. When used in an item template it does nothing. The documentation for the parameter mentions it is for the New Project dialog and therefore isn’t valid for item templates.

Finally, just for fun we’ll add a copyright notice. This time we’ll use the $year$ parameter which puts the current year in the file. The full list of available template parameters is defined here. Here’s the final template.

/*
 * Copyright © $year$ My Company
 * All Rights Reserved
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace $rootnamespace$
{
    /// <summary>Provides extension methods for SomeType.</summary>
    public static class $safeitemname$
    {
        public static void DoSomething ( this SomeType source )
        {
        }
    }
}

VSTemplate File

Now that the item skeleton is complete we need to let VS know about it. To do that we need to create a vstemplate file. A vstemplate file is an XML file that describes the template, where it should be placed and what file(s) make it up. Here’s a standard example.

<?xml version="1.0"?>
<VSTemplate Type="Item" Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Extension Class</Name>
    <Description>Creates an extension class.</Description>
    <Icon></Icon>
    <ProjectType>CSharp</ProjectType>
    <DefaultName>MyExtension</DefaultName>    
  </TemplateData>
  <TemplateContent>
    <ProjectItem ReplaceParameters="true" TargetFileName="$fileinputname$.cs">ExtensionClass.cs</ProjectItem>
  </TemplateContent>
</VSTemplate>

Let’s take this file apart. The VSTemplate element identifies whether this is a project or item template. Within this element is the template metadata and content. The TemplateData element defines the metadata for the template. The TemplateContent element defines the file(s) that make up the template.

Name (required)
The name of the template as shown to the user
Description (required)
The description of the template as shown to the user
Icon (required)
The icon file of the template
ProjectType (required)
The type of project the template works with (CSharp, VisualBasic, VC or Web)
ProjectSubtype
The subtype of project the template works with

The documentation for vstemplate files is defined here but be aware that this file is used for both item and project templates. Some elements are only meaningful for one or the other. Read the documentation carefully to ensure you can use an element.

Note that previous versions of VS supported using a resource DLL for some of the values. For performance reasons it is recommended that you do not do this going forward.

The project type and subtype values are tied together. For a C# project you can specify a type of CSharp and leave subtype off. But for a web project you need to specify the type as Web and the subtype as CSharp. A full discussion is available in MSDN.

Template Content

Under the TemplateContent is a ProjectItem element for each file that is part of the template. Yes you can have multiple files in a template. The value of the element is the name of the file inside the template. All attributes are optional.

TargetFileName
The filename to use in the project (generally set to $fileinputname$.cs or similar)
ReplaceParameters
Indicates whether the file contains template parameters that should be replace (generally set to true)
Subtype
The optional editor to use for the file (generally only used for nested files)
CustomTool
The optional custom tool to associate with the file

While not needed here, you can also have a References element which child Reference elements. You can use this to add assembly references to a project when the item is added. You can read more about them here.

The last thing you’ll want to do is create an icon file (or copy one) for the template. Ensure the filename matches what is in the template. Note that if you leave the icon element empty then a generic icon is used instead.

Installing the Template

Prior to VS 2017 you would need to zip up the vstemplate and content files and put them into one of the searched template paths. With VS 2017 not only do you not need to zip them up anymore but you are encouraged not to for performance reasons. Instead all you need to do is drop the files into a folder in one of the search paths and VS will find them.

For local templates you can put them in the documents folder as mentioned earlier. For shared templates place them someplace everyone on the template has access to and ensure VS is updated to use the shared template location. When looking at the template structure that is generated by VS you’ll notice it is broken up by language. For a C# template you’ll want to put your templates in the Visual C# folder. The same goes for the other languages.

Create a folder for your template (e.g. ExtensionClass). Now copy your content files, icon file and vstemplate file into the folder. In my experience VS will only look for templates once so restart VS after dropping the template into the folder and then open a project and select Add\New Item again. You will probably need to scroll but you should find your template. Select it, enter an item name and verify the item is added properly.

Now that you have one template working, it becomes easy to simply copy/paste the folder structure, change the template contents and update the vstemplate file to create new ones. Using your own custom templates should greatly speed up your development.

A final note on the folder structure. The documentation mentions that you can create template categories to group your templates together by creating a category folder in the root of the language template folder and then create your template folders under that. It indeed does work for extensions but custom templates don’t appear to work. If you put an intermediate category folder under the language folder then VS will ignore your template. Whether this is a bug or not I cannot say.

Template Wizards

The templating engine built into VS is pretty limiting. If you want to make more complex templates then you will have to define a template wizard. Creating a wizard is beyond the scope of this post but I created one a while back in my series on creating environmental config transforms using T4. The vstemplate file needs to be updated to point to the wizard if you go this route.

Exporting Templates

The approach I talked about here is a completely manual process for creating templates. If you already have a file defined in a project that you want to reuse elsewhere then you can export the file (or even the project) using the Project\Export Template option. Note that this generates a template but does so following the older rules. You can read more about exported templates in MSDN.

Writing a Context Provider for CodeRush for Roslyn

Several years ago I wrote an article about creating a custom context provider for CodeRush. In that time CodeRush Classic, as it is called, has been replaced by CodeRush for Roslyn which relies on Roslyn. Now seems like a good time to update the provider. Rather than having to read both articles I’m going to repost the old article with updated changes for Roslyn. The code is semantically similar but had to be rewritten to use Roslyn.

Read More

Updated Visual Studio Templates for VS 2017

Now that VS 2017 is ready it is time to update the template extensions I provided for previous Visual Studio versions. However this time the templates themselves don’t really need to change. Instead the VS extension that I wrote to wrap them needs to be updated to take advantage of the newer VS extension features.

Read More

Custom Naming Styles in Visual Studio 2017

One of the great new features in Visual Studio 2017 is the ability to define naming rules for code and then let the IDE notify you when they are violated. Depending upon what options you choose the IDE can suggestion, warn or flat out fail compilation because of violations. In this release the options are limited but since the rules are using Roslyn, the options can only improve in later releases.

Read More

Identifying Slowdown in Visual Studio 15 Preview 5

As Visual Studio has become more extensible there are more and more extensions that developers like to install. Unfortunately not all of them are well behaved. The more extensions you install the more likely VS will crash or slow down. When this happens most people tend to go to the forums and complain about VS bugs and/or performance. Yet the culprit is likely an extension. Up until VS 15 preview 5 there has been no easy way to diagnose this. Generally, when responding to a forum post, a user is recommended to run in safe mode to eliminate the chance that it is an extension. But doing this doesn’t really help narrow down the problem that much because: 1) the problem may not occur very often and 2) many extensions are critical to doing real development. In VS 15 Microsoft has finally added some performance monitoring to VS. VS has had perf monitoring for a while but none of that was visible to the average user. In VS 15 you can now go to Help\Manage Visual Studio Performance and get a window that provides some basic information about extensions and tool windows, the two most likely causes of a slowdown. This window allows you to see if an extension or window is slowing things down. If so then you can disable it and report the issue to the author. Hopefully this will cut down on forum posts but we’ll have to see how this feature evolves until release.

VSHost Bug is Squashed

Way back in Visual Studio 2005 Microsoft added a new debugger host, VSHost. The purpose, as advertised, was to speed up debugging by taking the hit for starting a debug session. The idea was that the host was started when you first began debugging and continued to run until you closed VS. This allowed VS to keep debugging information cached which sped up repeated runs of the debugging session. It only worked for managed applications but, for the time, greatly increased debugging startup. But there were problems with this approach. Firstly was that some apps simply didn’t work correctly with it. Microsoft provided a project debug setting that allowed you to disable the host in this case. Secondly it mucked with the whole debug process because VS started the host which emulated your process (it even had a config that matched your config). Thirdly, since it was a separate process, it would occasionally stop responding or crash which caused issues with the debugger. Starting with VS 15 preview 5, the VS host process is gone. Microsoft has wisely optimized debugging startup times making the need for this process mute. So now running your app in the debugger is going to behave more naturally and, in theory, VS shouldn’t run into any more issues of disconnected processes. You can read more about this decision here.here

Light Switch Is Off (Deprecated)

As part of the Visual Studio 15 preview 5 release, Microsoft has announced that Lightswitch is officially deprecated. VS 15 will not ship with it. Microsoft is recommending that everyone switch to PowerApp or equivalent. Note however that Microsoft will continue to provide security fixes and support existing Lightswitch apps for the foreseeable future. However Microsoft does not recommend any new development use Lightswitch. Read the full announcement here.here

.NET Core 1.0.0 VS 2015 Tooling Preview 1 Uninstall

With the recent announcement that .NET Core 1.0.0 is officially released, Microsoft also announced that Preview 2 for .NET Core 1.0.0 is available. However to install it you must first uninstall Preview 1 if you have it installed. The issue is that to uninstall you have to have the original setup program. If you go to any current links they will take you to the Preview 2 installer so you are in a catch-22. Fortunately Barry Dorrans tweeted a link to the Preview 1 installer here. So if you need to uninstall Preview 1 first then use that link to get the installer. I also recommend that you keep the Preview 2 installer around for the inevitable uninstall later.

T4 Templates Update for Visual Studio 2015

A while back I posted a series of articles on how to use T4 and a custom VS extension to simplify some common code like application settings, WCF clients and environmental transforms. With the release of Visual Studio 2015 I had to update my own extension and templates so I wanted to posted a follow up article on the changes that need to be made to allow the extension to work with Visual Studio 2015. As part of the update I added some functionality to the app settings template. Before continuing be sure to download the previous version of the series (or simply download the final version below).

Read More

Visual Studio 2015 RC NuGet Package Bug

UPDATE: NuGet Package Manager 3.1 has been released to Visual Studio Gallery. It resolves the issue mentioned here.

For those of you using the Visual Studio 2015 RC/RTM release you should be aware of a bug in the version of NuGet that ships with it. The bug manifests itself when building or debugging a project. When you first start VS the package is fine and you can go to ToolsOptionsNuGet Package Manager and adjust settings. Clearly the package has been successfully loaded. But when you start to build the project (or start to debug which triggers a build check) then VS may report that the package failed to load.

The problem is that NuGet is attempting to update the nuget.config file to a new version and the file is read only causing the package to fail. The file can be read only for a number of reasons but the most likely case is when you are using source control (like TFS) and the file is checked in. The bug has been reported to NuGet and appears to be resolved in future versions.  For now the workaround, if you encounter this issue, is to simply modify the nuget.config file to not be read only (or check the file out of source control) so that the update can succeed.