Look At T4 Templates In Visual Studio 2015 - Part Two

In the previous article, we saw T4 templates in Visual Studio 2015 and understood its basics. Let’s drill down more and understand class feature blocks and utility methods. Class feature blocks (<#+ statements #>) can contain reusable code blocks with classes, methods, properties and can use in statement and expression blocks. It should be at the last\bottom of the template definition file.

Let’s create a sample class definition block and understand it:

code

Output:

output

Here, we defined a class Employee with a method GetEmpDetails that will return a string and used it in Expression block for displaying it in output text file.

We can format text output of a template by using utility methods like: PushIndent(string), PopIndent() and ClearIndent().

Let’s understand it by creating below template that will create a class with property names mentioned in a variable:

code

Output:

output

We defined properties variable and looped through it and generated a class with private and public members for it. We used formatting methods to format the output with proper indent.

We can even throw an error or warning using Error() and Warning() methods within a template as shown below:

code

If property name is Id, we are throwing an error and warning.

We can create custom utility methods like PopIndent() by extending Microsoft.VisualStudio.TextTemplating .

Let’s create a new class library MyUtility, add reference to Texttemplating assembly and add a class with below code, which will convert a string to Upper case:

ref

code
code

Output:

output

Here, we extended TextTransformation class part of Visual Studio’s TextTemplating assembly and added new method ToUpper(), which uses TextInfo class to read input and make it upper case. Then, we added a reference to class library in the template using assembly directive and called our custom utility method.

I am ending things here, in next article I will drill down more on T4 Templates and look into runtime (or) preprocessed templates and passing parameters to it. I hope this article will be helpful for all.

Read more articles on Visual Studio 2015:


Similar Articles