Before reading this article, I would recommend reading the following previous parts:
- Look At T4 Templates In Visual Studio 2015 - Part One
- Look At T4 Templates In Visual Studio 2015 - Part Two
Let’s add a sample runtime template to our project and understand it:

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

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

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:

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:

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:

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

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:

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:


Debasis SahaTOP 100Posted May 3, 2016, 5:28 AM EDT
Good One..
Vignesh ManiTOP 100Posted May 3, 2016, 5:27 AM EDT
Good
Bhuvanesh MohankumarPosted May 3, 2016, 4:23 AM EDT
Nice...
Amit DavePosted May 3, 2016, 2:54 AM EDT
Nice article!
Muhammad Aqib ShehzadPosted May 3, 2016, 1:09 AM EDT
good share
Kuppurasu NagarajTOP 100Posted May 2, 2016, 9:09 PM EDT
Nice Sharing..