Look At T4 Templates In Visual Studio 2015 - Part Three

Before reading this article, I would recommend reading the following previous parts:

In previous articles, we looked into class feature blocks and utility methods. Let’s drill down more and understand runtime\preprocessed templates and passing parameters to it. We can execute a preprocessed template via code, which will create a class and show the output of it. This can be executed outside of Visual Studio and no dependency on Microsoft.VisualStudio.Texttemplating.dll.

Let’s add a sample runtime template to our project and understand it:

template

Let’s add below code to output “runtime template” at execution:

code

Let’s look at generated code in Mytemplate.cs:

code

The code written in template will be called from TransformText() method and same will be executed at run-time via code. Here, our template inherited from MyTemplateBase and have a method TransformText() to process the template.

Let’s write below code in our console application to execute the template and see the results:

code

Output:

output

Here, we created an instance of our template and called TransformText() which will execute our template code and return the output.

Let’s extend our template by adding parameters to it:

code

We added two parameters to provide input to the template by using parameter directive,

(<#@ Parameter type=”System.Int32” Name=”Salary”) #>, for which values will be passed via code at run-time.

This will generate two read-only properties in MyTemplate.cs:

code

Let’s pass values to these parameters from console application by creating a session:

code

Here, we created a TextTemplating session to pass parameters than called Intialize() to transfer values and make it available in TransformText(). We need to add reference to Microsoft.VisualStudio.Textemplating.11.0.dll and Microsoft.VisualStudio.TextTemplating.Interface.11.0.dlls to create a session for parameter passing.

Output:

output

So, Runtime templates are helpful in generating code\documents on the fly, and can be executed outside of Visual Studio.

I am ending things here, in next article will drill down more on T4 Templates and look into reusing template and troubleshooting it. I hope this article will be helpful for all.
 
Read more articles on Visual Studio 2015:

Up Next
    Ebook Download
    View all
    Learn
    View all