T4 templates ~ AKA Scaffolding---a powerful tool for improving the speed of ASP.

Source: Internet
Author: User
Tags new set

Read a very good article, but the scaffolding is not too understanding, the great God saw, hope pointing twos, can tell point learning resources is better!

This article is not from my hand, reproduced completely in worship and learning!

Welcome to add me: jkxx123321 Notes blog add on it!

Recently due to the need to provide some custom templates in the framework of the function, found a blog, unfortunately seems to be a translation tool directly, read not fluent, try to translate, I will not fully translate the original sentence, may be a small range of the original text I think more appropriate sentence and add some comments, the original address is as follows:

Http://blogs.msdn.com/b/webdev/archive/2009/01/29/t4-templates-a-quick-start-guide-for-asp-net-mvc-developers.aspx

In the ASP. NET MVC Release candidate mentioned in our recent blog, we used the T4 (Text template transformation Toolkit) template to implement the Add controller and add The Code auto-generation feature for view. We want to be able to use T4 to bring the development speed up, because users can customize these templates to a great extent.

Location and overrides of templates

Both the Add controller and the Add view implement the code to be automatically generated by executing the T4 template in the background. Some tools allow you to modify the template to customize the code you want to generate. Default template location in: [Visual Studio Install Directory]\common7\ide\itemtemplates\[csharp | Visualbasic]\web\mvc\codetemplates\

You can also copy the "Codetemplates" directory to the root of the project to rewrite and customize the template in the above location as the basis for each project (you only need to create a directory named "Codetemplates" and create "Addcontroller" and " AddView "subdirectory). Overrides that require some templates under the default directory may not work because the code that is automatically generated will take precedence over the matching templates in the project directory. Another important point to note is that you can add your own. tt file for the Add View feature, either in a public directory or in a standalone project, and can be automatically displayed in the drop-down box of the view selection in the Add View window.

In addition, when you copy the above folders (Add. tt files) to the project, there are warning prompts, such as:

(Running these text templates can be harmful to your computer.) If the template source is not trusted, do not run it. )

Clicking "Cancel" will not be able to use the T4 template (if you copy the "Codetemplates" directory and add multiple. tt files, you have selected "Cancel"). Because once the project discovers a. tt file, the file's custom tool (Customtool①) property is set to "Texttemplatingfilegeneraror", which notifies Visual Studio to use the default T4 host (Host②) Go to execute this template and create a new file based on the content of this template (in the same directory as the template).

①: The custom tool is a special component that implements the Ivssinglefilegenerator interface defined by Visual Studio. The T4 custom tool is implemented by the Microsoft.VisualStudio.TextTemplating.VSHost.TemplatedCodeGenerator class and registered in the Registry in the visual Under Studio name is TextTemplatingFileGenerator. Visual Studio will use this name to find the custom tool, create a COM object, and call its ivssinglefilegenerator.generate method

②:microsoft.visualstudio.texttemplating.vshost.10.0.dll's Texttemplatingservice service implementation The Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost interface, which provides the host (host) for the code generation engine. During the template conversion process: The Engine is responsible for code generation, and host is responsible for providing all the external resources needed for the implementation of the behavior during the conversion process. ITextTemplatingEngineHost and template content are passed together into the Engine.processtempalte method for code generation

  

For template-based one-time file generation or simple use of T4, the generator can be used as a good implementation---however, because the Add View and add controller templates that depend on the custom template's host contain code (which is mentioned later), Using the default Builder to execute the template will generate an error. You need to copy the template into the project and then empty the custom tool property values.

Note: If you want to remove the copy . TT file automatically sets the mapping value of the custom tool, which you can implement through the registry --- Note If you want to restore the registry to the default value, you can perform Visual Studio Restore the installation, or manually change back. Start the Registry Editor and locate the specified directory (based on whether your machine chooses to have a level or a bit):

+ bit : hkey_local_machine\software\microsoft\visualstudio\9.0\generators

- bit: hkey_local_machine\software\wow6432node\microsoft\visualstudio\9.0\generators

Expand the Generators "next to each node in the first layer and find" . TT ". Setthe value of the "(Default)" entry to be empty.

if you want to rewrite the global template and do not want to copy the " codetemplates "Catalog to your project ( probably you already have a directory of the same name ) , you can modify it through the registry ADD Controller and the ADD View the default directory name. Start the Registry Editor and locate the specified directory (based on whether your machine chooses to have a level or a bit):

32-bit:hkey_local_machine\software\microsoft\visualstudio\9.0\mvc\codetemplates

64-bit:hkey_local_machine\software\wow6432node\microsoft\visualstudio\9.0\mvc\codetemplates

Change " Overridedir "The value of the item is what you want to T4 the directory name that the tool retrieves. It is important to note that the new set of directories still need to ensure that the same directory structure, that is, contains "addcontroller" and "addview" directory.

Edit T4 Templates

If you use Visual Studio to open a. tt file, you may find that its contents are not layered---tiled on top. We strongly recommend that you use the T4 editor, a Visual Studio plugin developed by Clarius Consulting, which provides syntax highlighting and some basic T4 statement completion when you edit a template. There are free "Community Edition", as well as more powerful "Professional Edition"---if you are interested can compare different features. As you will see below, this plugin really makes the template making a lot different.

Deep Anatomy T4 Templates

The simplest way to learn to edit a custom template is to start by looking at how the default template works. To do this, we use some of the Add view templates to learn about "create" (creating a. tt file). Now start from the beginning:

These four lines of code are directives.

1. The first line is the template directive, and its main function is to inform the T4 engine which language the template is written in. The language used here is not a template that will output this language, which controls the output of the template (for example, a if-else statement in a template may be used to control which text is output). When using the Add view or add controller, the "hostspecific" property needs to be set to "True", otherwise the template will not be able to access the information provided by the Add view and the Add controller function (such as a strongly typed type that binds types to View) , etc.).

2. The following is the output instruction, which simply notifies the template host to set the template output file extension---this is not an MVC-specific tool, because the default extension may be ignored depending on the situation (for example, if we rely on partial view, the extension should be. ascx).

3. The next two lines are reference directives, and C # often uses "using", and "Imports" is used in VB. If you use the code that you write in your template, you need to refer to it in that location.

Here you can find more documentation on the T4 directive: http://msdn.microsoft.com/en-us/library/bb126421.aspx

Next, note the following line:

In this line we have created a new variable "mvchost" to convert the "Host" type and assign it to it. Because the "hostspecific" attribute is set to "True" in our directive, "Host" is automatically supplied to the template. The MVC tool provides a custom host so that information can be passed to templates that are accessible only within the tool. In order to access these properties provided in our host class, "host" must be converted to our custom host type "Mvctexttemplatehost".

The use of this variable is actually very simple:

The first thing to note is that the ' <# ' and ' #> ' tags contain some code. These two tags are used to invoke the statement block and contain the control code. Your template may want to have conditional output text blocks in the output file, while maintaining the normal output of other blocks of text. Above, we have an if statement (using C #, because the language of the template is set to C # using the template directive), and "{" is used. The "}" of this if statement appears in the 17th row in the following rows, in a different block of statements. Note that this if statement accesses the host's "Isviewusercontrol" property, which is the function of notifying the template user whether the partial view is selected.

Blocks of text outside all of these tags in the template are exported directly to the actual file. In the above, the text of line 14th is outside the markup block, so it will be output directly---however, it will only output to a file if the value of the IF statement of the 12 row is judged to be "true".

Here you can find more information about the T4 statement block: http://msdn.microsoft.com/en-us/library/bb126509.aspx

The simplest way to understand the control code in a T4 template is to connect it as a complete program in the brain. The variables we declared earlier in line 6th can be used after the T4 control code---each if-else branching condition can use this variable and add some text (gray) to the output file. The If-else statement above selects some of the properties provided by the template host to be passed to the Add view template.

There is a strange block of statements in some of the following rows:

We have declared a variable of type "list<string>". How can we use the list type in the T4 code? Because you can see our reference directives at the top of the template:

Line 56th calls a method "filterproperties"---but where is the method? The definition of this method is actually at the bottom of the template:

If you look closely, this block of statements is a bit different, starting with "<#+". This is a block used to represent classes that work: The T4 template has the characteristics of all classes and adds those features to the class that is compiled in the background of the template. This is not limited to methods, but also attributes (usually included in the class). Like a class member in a regular code file, they can be accessed by other code in the template.

More information about class feature blocks:http://msdn.microsoft.com/en-us/library/bb126541.aspx

Our default template uses the "Filterproperties" method above in the default output of the type contained in the tag filter to get some properties, these tags must be public and like Girdview can be displayed in the designer. This is associated with calling the GridView. The result of the Isbindabletype method is logically the same.

(This translation is very awkward, so attach the original, please help me correct)

Our default templates with the ' filterproperties ' method from the above screenshot-to-default output markup only for SOM e properties in the type–namely ones that is public and would also is displayed in the designer by things like GridView  . This logic is identical-to-what-would get from calling the Gridview.isbindabletype method.

The "Isbindabletype" that is called in line 136 is defined at a point in the back of the template:

If you want to change one of the properties that our template filters out, you can modify any of the methods as you prefer.

Finally, take a look at line 65th:

Here is a new tag at the beginning of "<#=". It is called by an expression block and is used to insert the value of the T4 code into the output text. As you can see above, we have a foreach loop that iterates through the properties and defines a local variable to iterate over the "PropertyName". We use an expression block to refer to the variable because we want to output a <th> tag for each property name.

More about expression blocks: http://msdn.microsoft.com/en-us/library/bb126508.aspx

As you can see, the various methods of using the T4 template through selective output text make T4 a powerful tool to help us get flexible and custom automated code generation.

MVC T4 of Tools Host Properties

Both the Add Controller and the Add View feature provide different properties to the template through the template host, which runs through the process of creating the template. Here is a complete list of the valid properties of the template host for use by your template (note: The actual names of these properties may vary depending on the version).

ADD Controller:

Property Name

Type

Description

ItemName

System.String

Name of the controller class with the "controller" suffix

NameSpace

System.String

Namespace of the generated controller class

Extraactionmethods

System.Boolean

Indicates whether the user chooses to extend the action method in the Add Controller window

Controllerrootname

System.String

Name of the controller class without "controller" suffix

ADD View:

Property Name

Type

Description

ItemName

System.String

View name without an extension, for example, displayed in the Add View window

NameSpace

System.String

Default to the directory where the view is located as the namespace

Isviewusercontrol

System.Boolean

Whether the user has selected partial view in the Add View window

Isviewcontentpage

System.Boolean

Whether the user creates a view with the master page

Isviewpage

System.Boolean

Whether user-created view pages that conform to specifications

MasterPage

System.String

The master page path that the user selects in the window (only used when Isviewcontentpage is true)

ContentPlaceHolder

System.String

The placeholder name where the content is generated. is the content placeholder ID that the user enters into the Add View window

ContentPlaceHolders

System.collections.generic.list<system.string>

A list of all content placeholder IDs in the master page, if view selects the master page

Languageextension

System.String

The extension of the output file (contains ".")

Viewdatatypegenericstring

System.String

The string used in the view directive to output the generic "Inherits" property (strongly-typed view). For example: "<MyType>" or "(of MyType)"

Viewdatatype

System.Type

The type object of the strongly-typed view being bound. You can get property information for a type, etc.

In addition, you will find some of the used properties provided to the host, such as the template path being executed. More about these properties: http://msdn.microsoft.com/en-us/library/ Microsoft.visualstudio.texttemplating.itexttemplatingenginehost_properties.aspx

Summary

We hope that this article gives you enough information about the T4 template to help you effectively combine the visual Web Developer provides for ASP. If you want to know more about this blog post, you can look at the information (Scott Hanselman's blog is good) and see what you can get. Please reply to your comments, suggestions or questions. Thank you for reading!

T4 templates ~ AKA Scaffolding---a powerful tool for improving the speed of ASP.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.