Tuesday, March 15, 2016

Creating T4 Templates using Visual Studio 2015

If you are not already familiar with T4 Templates, it is the syntax that Visual Studio internally uses for all of its code generation through Project Templates, Item Templates as well as tooling for ASP.NET MVC, Web API, Entity Framework etc.

Therefore, you may find it useful to leverage T4 Templates in your development team to reduce the amount of hand coding and manual effort that is required to develop your projects.

If you want to learn about writing T4 Templates using Visual Studio, you will definitely want to check out these MSDN articles first:

However, one of the best ways to learn how a T4 template is constructed is to open up an existing T4 template that Microsoft uses!

For Visual Studio 2015, the ProjectTemplates are located here:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates

and the ItemTemplates are located here:  
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ItemTemplates

Most developers will want to target the C# or the Web folders which are listed individually as:

  • CSharp
  • CSharp\Web
  • Web\CSharp
The folders you will want to examine are generally beneath the 1033 folder.

Below is an example class file which shows how to use some T4 syntax:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;
$if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
namespace $rootnamespace$
    class $safeitemrootname$

No comments:

Post a Comment