Chapter 14Code Generation with T4

  • Using T4 templates to generate text and code
  • Troubleshooting T4 templates
  • Creating Runtime T4 template to include templating in your projects

Frequently, when writing software applications, you’ll have large areas of boilerplate code in which the same pattern is repeated over and over. Working on these areas of code can be time-consuming and tedious, which leads to inattention and easily avoidable errors. Writing this code is a task best suited to automation.

Code generation is a common software engineering practice where some mechanism, rather than a human engineer, is used to write program components automatically. The tool used to generate the code is known as a code generator. A number of commercial and free code generators are available in the market, from the general to those targeted toward a specific task.

Visual Studio 2013 includes a code generator that can generate files from simple template definitions. This code generator is the Text Template Transformation Toolkit, or more commonly, T4.

This chapter explores the creation, configuration, and execution of T4 templates. You’ll also see how to troubleshoot templates when they go wrong. Finally, you’ll create a Runtime Text Template that enables you to create reusable T4 templates that you can easily call from your own code.

CREATING A T4 TEMPLATE

In earlier versions of Visual Studio, creating a new T4 template was a hidden feature that involved creating ...

Get Professional Visual Studio 2013 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.