Visual Studio 2010 uses T4 text templates for code generation and within this blog post we’ll examine the anatomy of a text template and see how easily code and other text can be generated.Let’s take a look at an example in Visual Studio, we’ll create a new Visual C# empty project and add two new text templates files, one named AdventureWorks.tt and the other named SqlServerSmo.tt. You can find text templates within the Add New Item dialog by searching for “text template” within the search control. We’ll use the Text Template rather than Preprocessed Text Template within this example. Open the file properties for the SqlServerSmo.tt template and delete the value from the Custom Tool option, then ensure that the value of the Custom Tool option for the AdventureWorks.tt template is TextTemplatingFileGenerator. When writing the text templates we compose the templates using directives, text blocks, and control blocks.Directives allow instructions to be passed to the text templating engine and there are six standard directives, although you also can create your own custom text template directive processors too! We’ll begin by replacing the text within the SqlServerSmo.tt template with the template directive shown below.<#@ template debug="true" hostspecific="true" language="C#" #> In the above example we’re setting debug=”true”, which will allow us to use the Visual Studio debugger to step through the template. We’re also setting hostspecific=”true”, which allows us to specify that the template is dependent upon features within a particular host, such as Visual Studio. Given that text templates can use programming language constructs within control blocks, it is necessary to specify the language to be used by the templating engine. At the time of writing the only two supported languages are C# and VB. Read more: Doug Holland - An Architects Perspective
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment