T4 (Text Template transformation Toolkit) is the code generation engine that Microsoft officially started using in VisualStudio 2008. In Visual Studio, the T4 text template is a hybrid template that consists of a number of text blocks and control logic that can generate a text file. In Visual C # or Visual Basic, the control logic is written as a fragment of program code. The resulting file can be any type of text, such as a Web page, resource file, or program source code in any language. In the current VS, as long as the scene related to code generation can basically find T4 figure, such as MVC view template, Entity framwork DataContext template and so on.
Before learning the boring concept, let's take a look at the example of quickly generating POCO entity classes with the T4 template
Open VS2010 to build a project, then right-click the project file, select New item, locate the file template in the file list,
Modify the contents of the Texttemplate1.tt file as follows
<#@ template debug= "false" hostspecific= "false" language= "C #" #><#@ output extension= ". cs" #>using System; Using system.collections.generic;using system.linq;using system.text;namespace consoleapplication1{public Class User {///<summary>/// User ID//</summary> public int UserID {get; set;} <summary>///user name/// </summary> public string UserName {get; set;} <summary>//password//// </summary> public string Password {get; set;} <summary>///e-mail// </summary> Public string Email {get; set;} <summary>///Phone number/// </summary> public string Mobile {get; set; }}
Click Ctrl+s and you can see that a TextTemplate1.cs file is automatically generated.
Using system;using system.collections.generic;using system.linq;using system.text;namespace ConsoleApplication1{ Public class User {//<summary>/// User ID//</summary> public int UserID {get; set;} <summary>///user name/// </summary> public string UserName {get; set;} <summary>//password//// </summary> public string Password {get; set;} <summary>///e-mail// </summary> Public string Email {get; set;} <summary>///Phone number/// </summary> public string Mobile {get; set; }}
is not very magical, T4 template engine will be based on the content you define in the template automatically generate the corresponding file, of course, this example is too simple, completely can not show the powerful T4, when you really understand T4, will find God Horse code generator is all clouds, T4 is king, With T4 you can easily generate your own style of any type of code, in the next article there will be an example of how to automatically generate Poco classes through the T4 connection database , basically this is our greatest intention to use T4, hehe, Before that, let's take a look at the basics of boring T4.
There are two types of T4 text templates:
Design-time T4 text TemplatesAnd
run-time T4 text template("Pre-processed" template)
Run-time T4 text templates ("preprocessed" templates) can be executed in the application to generate text strings (usually as part of their output).
preprocessed text template file to your project. " > To create a run-time template, add a custom Tool property to TextTemplatingFilePreprocessor. " In addition, you can add a plain text file and set its
For more information, see Generating run-time text using preprocessed T4 text templates. For more information about template syntax, see Writing T4 text templates.
you perform design-time T4 text templates in Visual Studio to define part of your application's source code and other resources.
.cs, .vb, or other source files. " In general, you can use multiple templates that read a single input file or data in a database and generate some .cs, .vb or other source files. Each template generates a file. execute them within Visual Studio or MSBuild.
writing a T4 Text Template. " >text Template file to your project. " > To create a design-time template, add the custom Tool property to TextTemplatingFileGenerator. " In addition, you can add a plain text file and set its
For more information, see Generating design-time code using T4 text templates. For more information about template syntax, see Writing T4 text templates.
A text template consists of the following parts:
directives -elements that control how templates are processed.
Text block -copy directly to the output content.
control block -Program code that inserts a variable value into the text and controls the condition or repeating part of the text.
T4 text Template directives
- All features in the template directives are optional
- Langeuage: Output language, valid value C #, VB, default C #
- Debug: Whether debugging is enabled, valid value True, False, default is False. Special instructions under this debugging really not well, it is easy to let vs crash, very chicken features,
- hostspecific: Valid value True, False, default is False. true, a property named host are added to the class G enerated by your text template. " > If you set the value of this attribute to true, the property named host is added to the class generated by the text template. microso Ft. VisualStudio.TextTemplating.ITextTemplatingEngineHost. " This property is a reference to the host of the transformation engine and is declared as
- microsoft . VisualStudio.TextTemplating.ITextTemplatingEngineHost. " >microsoft . VisualStudio.TextTemplating.ITextTemplatingEngineHost. " >inherits: Program code that can specify a template can inherit from another class, which can also be generated from a text template. At present, the wood has been used, can basically ignore
- CompilerOptions: Valid value is any valid compiler option. Can basically ignore
- T4 parameter directives
<#@ parameter type= "Full.typename" name= "ParameterName" #>
As the name implies, is used to pass the parameter, should be used in the runtime template (preprocessing template)
- T4 Output Instructions
<#@ output extension= ". Filenameextension" [encoding= "encoding"] #>
More important instructions for setting the suffix name and file encoding of the output file
Extension: Output file name extension, default to ". cs"
Encoding: File encoding, default value is Utf-8 (here is not OK, I test is utf-8)
- The assembly directive is equivalent to the function in which we add an assembly reference, which has only one parameter name, which specifies the assembly name, and if the assembly is already registered in the GAC, simply write the assembly name, such as <#@ assembly Name= " System.Data.dll "#> otherwise you need to specify the physical path of the assembly.
- The assembly references of the T4 template are completely independent, that is, we reference some assemblies in the project, and then add a T4 template to the project, and all the assembly references required by the T4 template must be explicitly referenced in the template using the assembly.
- The T4 template automatically loads the following assemblies Microsoft.visualstudio.texttemplating.1*.dll, System.dll, WindowsBase.dll, if the other assembly needs to be displayed using an assembly to add a reference
- You can use the $ (variableName) syntax to refer to Visual Studio or MSBuild variables (such as $ (SolutionDir)), and to use%variablename% to reference environment variables. Describes several commonly used $ (variableName) variables:
$ (SolutionDir): The current project is in the solution directory
$ (ProjectDir): directory where the current project is located
$ (TargetPath): current project compilation output file absolute path
$ (TargetDir): The current project compiles the output directory, that is, the bin directory of the Web project, the debug or release directory under the bin directory of the console, Class Library project (depending on the current compilation mode)
For example, we set up a console project TestConsole in the D packing directory, the solution directory is D:\LzrabbitRabbit, the project directory is
D:\LzrabbitRabbit\TestConsole, at this point in debug compilation mode
The value of $ (solutiondir) is D:\LzrabbitRabbit
The value of $ (ProjectDir) is D:\LzrabbitRabbit\TestConsole
$ (TargetPath) value is D:\LzrabbitRabbit\TestConsole\bin\Debug\TestConsole.exe
$ (TargetDir) value is D:\LzrabbitRabbit\TestConsole\bin\Debug\
- T4 Import Directives
<#@ Import namespace= "namespace" #>
In the code block of the Visual Studio T4 text template, the import directive allows you to reference elements in another namespace without providing a fully qualified name. It is equivalent to the using in C # or the imports in Visual Basic. A reference to the System namespace has been imported by default.
- FilePath can be absolute, or relative to the current template file.
- FilePath can include environment variables separated by "%". Example: <#@ include file= "%homepath%\myincludefile.t4" #>
- The name of the contained file does not have to use the extension ". tt". You may need to use a different extension for the included file, for example, ". T4". This is because when you add a. tt file to your project, Visual Studio automatically sets its custom tool property to TextTemplatingFileGenerator. You typically do not want to convert the contained files separately.
- When processed, the content is included as if it were part of a text template. However, even if the include directive is a plain text block and a standard control block, you can include a file containing the class function block <#+...#>.
- Include directives can increase the code reuse rate, for example, we can put some common assembly, namespace reference to a file, use only need to refer to the next, save every time to re-reference the trouble, If we build the Reference.ttinclude file, it contains the assembly references we usually use
<#@ Assembly Name= "System.Core.dll" #><#@ Assembly name= "System.Data.dll" #><#@ Assembly Name= " System.Data.DataSetExtensions.dll "#><#@ Assembly name=" System.Xml.dll "#><#@ import namespace=" System "# ><#@ import namespace= "System.Xml" #><#@ import namespace= "System.Linq" #><#@ import namespace= " System.Data "#><#@ import namespace=" System.Data.SqlClient "#><#@ import namespace=" System.Collections.Generic "#><#@ Import namespace=" System.IO "#>
Use only if you want to use the include directive reference
<#@ include file= "$ (ProjectDir) reference.ttinclude" #>
Text block
Text blocks insert text directly into the output file. The text block has no special formatting. For example, the following text template will generate a containing word "Hello world!" The text file:
<#@ output extension= ". txt" #>hello world!
Control block
A control block is a section of the program code used to transform a template. The default language is C #, but to use Visual Basic, you can write the following directives at the beginning of the file:
<#@ template language= "VB" #>
The language used to write control block code is independent of the language of the generated text.
Standard control block
The standard control block is the program code section that generates the output file part.
In a template file, you can mix any number of text blocks and standard control blocks. However, you cannot nest control blocks within a control block. Each standard control block is delimited with the <#. #> symbol.
For example, if you use the following control block and text block, the output file contains lines "0, 1, 2, 3, 4 hello!" :
<# for (int i = 0; i < 4; i++) { Write (i + ","); } Write ("4");#> hello!
You can interleave text and code without having to use an explicit Write () statement. The following example outputs "hello!" Four times:
<# for (int i = 0; i < 4; i++) {#>hello!<# } #>
In the code, you can use Write (); The position of the statement can be inserted into a text block.
Expression control block
An expression control block evaluates an expression and converts it to a string. The string is inserted into the output file.
The expression control block is delimited with the <#=. #> symbol.
For example, if you use the following control block, the output file contains "5":
<#= 2 + 3 #>
Note that the start symbol has a three character "<#=".
An expression can contain any variable in the scope. For example, the following block outputs a numeric line:
<#@ output extension= ". txt" #><# for (int i = 0; i < 4; i++) {#>this is Hello number <#= i+1 #> ;: hello!<# } #>
class function control block
The class feature control block defines properties, methods, or all other code that should not be included in the primary transformation. class function blocks are commonly used to write helper functions. Typically, class function blocks reside in separate files so that they can be included in multiple text templates.
class function control blocks are delimited with <#+ ... #> symbols, which can be simply considered <#+ ...#> defined content as our class file
For example, the following template file declares and uses a method:
<#@ output extension= ". txt" #>squares:<# for (int i = 0; i < 4; i++) {#> the square of <#= I #> is <#= Square (i+1) #>.<# } #>that is the end of the list.<#+ //Start of class feature Blockp rivate int Square (int i) { return i*i;} #>
Class functionality must be written at the end of the file. However, even if the include directive is followed by standard blocks and text, you can <# @include #> files containing class functionality.
class function blocks can contain text blocks
You can write methods that generate text. For example:
List of Squares:
<# for (int i = 0; i < 4; i++) { writesquareline (i);} #>end of list.<#+ //Class feature blockprivate void writesquareline (int i) {#> the square of <#= I # > is <#= i*i #>.<# }#>
It is useful to place the text generation method in a separate file that can be included with multiple templates.
Well, probably the base point should be this, more of their own to msdnhttp://msdn.microsoft.com/zh-cn/library/bb126445 learn more about it
Here to explain the point is easy to confuse, we in the T4 template referenced in the assembly and those namespaces are used to generate code using T4 to use, that is, T4 template to use, and we want to generate the target of the hair relationship is not, the original to find out this is a cost of energy. T4 looks very complex at first, in fact, a little bit of research, the main seems to be MSDN to understand or easy to learn, once mastered the infinite
T4 Template engine