left-icon

T4 Succinctly®
by Nick Harrison

Previous
Chapter

of
A
A
A

CHAPTER 1

Introduction

Introduction


Introducing T4

T4 has been available as a part of Visual Studio since Visual Studio 2005. Incremental improvements have been made with each subsequent release of Visual Studio, so it keeps getting better.

Note: It is possible to use T4 outside of Visual Studio hosted in your own application, but this book will focus on using the toolkit with Visual Studio.

T4 is a code generator. Actually, it’s more than that. T4 stands for:

  • Text
  • Templating
  • Transformation
  • Toolkit

Notice that neither code nor generator shows up in the name. T4 is based on text in templates and how those templates get transformed into something useful. In many cases, this involves applying metadata to a template to transform it into source code in a variety of languages.

Some possible outputs from a T4 template:

  • C#
  • VB.Net
  • SQL
  • HTML
  • JavaScript
  • Text
  • CSS

The template also has code to drive the transformation. This code can be in C# or VB.NET—depending on which language you are most comfortable with—regardless of what type of text is output.

In this book, we will use C# to drive the transformation, and when generating code, we will generate C#, but this is not the only option.

Why Generate Code?

Familiarity with code generation tools is key for modern software engineers. Much of the code that we need to write can be handed over to a trusted code generator to handle for us, and frankly, much of our time would be better spent designing software than dealing with the subtle nuances of repetitive code that the computer could write with minimal input from us.

Generating code is particularly useful in places where we have lots of repetitive steps that can easily be described with metadata, or where best practices have not yet fully gelled. Humans get bored and sloppy with repetitive, tedious tasks. Computers do not, and when the best practices are still being worked out, it makes sense to generate the code so that as the best practices change, you only have to change the generator to have all of the code built from the generator conforming to the evolving best practice.

We can also leverage code generation to kick-start a project. Instead of generating code that should never be changed and is expected to compile and run successfully without developer intervention, this type of code generation lays out the broad strokes and expects a developer to fill in the rest. This type of code generation is often referred to as scaffolding.

Scaffolding is great for providing developer guidance and making sure that you don’t have to face an empty project and wonder where to start, but it does nothing to help with evolving best practices or changes to the metadata. Scaffolding generators are expected to run only once, with the developer handling everything from there. They provide a catalyst from which to start.

Actual Applications

Whether you know it or not, you’re probably already using a code generator. Many tools and frameworks use them behind the scenes to make life easier for the developer.

Increasingly, T4 is becoming the tool of choice for generating this code. The template developers have control over the code that is being generated while still allowing the developer, as a user of the template, the ability to modify the generated output by customizing the templates.

MVC and Entity Framework are possibly the two biggest examples of using T4 behind the scenes. Entity Framework expects the output of its templates to be complete and usable without any developer intervention. These templates generate partial classes, so if you need to add anything, add it in a partial class in a separate file. This will protect your changes whenever the code is regenerated, and may potentially be regenerated fairly often.

MVC takes the scaffolding approach to code generation. The generator is expected to run once for any artifact that you generate. This generation is intended to help you hit the ground running, but after that, you are on your own. You can make any changes that you need to the generated code, but there is no way to re-run the generator unless you delete the outputted file and start over.

Both approaches have their strengths and weaknesses, as we shall see.

Practical Applications

As a toolkit, T4 allows you to do pretty much whatever you need to do, but there are some guidelines that can help us hone in on areas that lend themselves more easily to reaping the benefits of code generation:

  • You must have a source of metadata that is easy to get to, easy to maintain, and easy to keep clean.
  • The generated code must conform to a pattern that is easily defined by the available metadata.
  • A generation template should be able to create a collection of artifacts based on the available metadata.

With these guidelines in mind, we can identify several possible templates, depending on the nature of your project. If you are using Entity Framework, you are already using T4, but if you are not, there are many opportunities to introduce T4 to a project without necessarily having to completely change your data access logic.

Some applications include:

  • Automate binding parameters to a command object.
  • Automate writing stored procedures to encapsulate access to a table.
  • Automate extracting data from a data table into a POCO.

If you are already using MVC, you are already using T4 for the scaffolding—but it can do even more for you, inlcuding:

  • Generate models and views (with a little extra metadata).
  • Generate JavaScript to automate calling Web API methods.
  • Generate the skeleton of a style sheet.

If you are not using MVC, you can get inspiration from all the ways that MVC uses T4.

Minimal Requirements

T4 has been integrated into Visual Studio since 2008, and was even available as a separate download to be added to Visual Studio 2005. As long as you are using Visual Studio 2008 or later, you have almost everything you will need. I say almost, because while T4 is built into Visual Studio, and Visual Studio understands how to run these templates, support for editing the templates is marginal without a good extension to provide some much-needed syntax highlighting and IntelliSense. I recommend starting with the community edition provided by Tangible. The community edition is free and will provide basic syntax highlighting, as well as limited IntelliSense support. This is more than enough to get you started, but as your templates get more complex, you can upgrade to a professional version that will give you full IntelliSense support, as well as the ability to debug your templates.

Note: While this is my favorite extension, it is not the only one available. A quick search through the extension manager will turn up several more.

Summary

In this chapter we have covered a lot of introductory material needed to provide context for where code generation and T4 specifically can fit into your projects. We have outlined some basic qualities that any successful application of code generation should have. We have reviewed the two different approaches to code generation: an all-inclusive approach where the generator produces code that should never be modified by the developer, and a simpler, scaffolding approach where the goal is to simply jumpstart a development effort, but rely on the developer to fill in the gaps.

We have reviewed some current, active examples where you might see T4 in action without realizing it: Entity Framework and MVC. We have also touched briefly on some example applications that we will explore more thoroughly in upcoming chapters.

Finally, we have seen the first hints at just how important metadata is to generating code. The second half of this book will focus on tracking down this metadata.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.