T4 presentation

Preview:

DESCRIPTION

As given to the Dubuque .NET User Group, November 1st, 2011.

Citation preview

Using Microsoft’s T4 Across the Life of an Application

Gary Pedretti

Gary.Pedretti@Centare.com

Logo, Design, and Company Information:© 2011 Centare Group, Ltd.Slide Show and Notes Content: Creative Commons License, Gary Pedretti

Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

About Centare

Consulting Services OrganizationPrimary focus on Agile, Mobile and Cloud

Individual and team based development.NET & Java technology stacks

Microsoft Gold Partner in ALM

Training, coaching, mentoring & team building

Full Scrum.org course offering

Best practices training

Technical and business leadership strategies

Gary Pedretti

Solutions Manager, Agile Practice

Over 12 years in the software industry – Database Administrator, Developer, Business Analyst, Application Architect

Scrum: Team member, Scrum Master, Coach, Certified Scrum Trainer for Scrum.org

MCPD 4.0 Web, MCTS 4.0 WCF/Web/Data Access, MCDBA MSSQL 2000, PSM, PSD .NET, PSD Java, CSM, MCPD 3.5 ASP.NET, MCTS 3.5 WCF/ASP.NET/ADO.NET, MCTS SharePoint 2003 Infrastructure, MCPD 2.0 Enterprise, MCTS 2.0 Distributed/Web/Windows, MCSD 1.1, MCAD 1.1, MOUS

Professional Scrum at Scrum.org

Professional Scrum

Product Owner

Professional Scrum Foundations

Professional Scrum Master

Professional Scrum

Developer.NET or Java

Product OwnersExecutives Scrum Masters

ArchitectsBusiness Analysts

DB SpecialistsDesigners

DevelopersTesters

Everyone

What is T4?T4 Basics and T4 Tooling

Using T4 Across the Life of an Application

What is T4?

Text Template Transformation Toolkit

A way to Template desired output

Provide input to the template

Process the template together with the input to produce text output

Text Transformation

XSLT – XML input, ? output (often XHTML)

Razor (and any number of MVC view engines like NVelocity, etc.) – ? input (often a Model object), (X)HTML output

T4 – ? input, ? output Anything goes

Designed for generic cases

Why?

Automate repetitive, boilerplate codeData Access code

Front-end scaffolding

Produce templated text output to be used by applications

Form letters

Transformations between different text formats

XML to C#

T4 Pre-History

CodeSmith was/is the primary mover in the .NET space

Around for a long time, very mature

Provides an excellent set of ready-to-use templates

Better template editing and debugging experience

Very code-centric (not geared around general text or transformations)

$$ licensing, not free

T4 Pre-History

Many competitors still exist, free and paid

XY Studio (web-based)

Atom Weaver (MDD-based)

Code Generator 360 (ASP.NET DAL-centric)

Iron Speed Designer (RAD front-to-back)

T4 History

Increasing importance and support as we’ve moved from Visual Studio 2005 to Visual Studio 2010

Including out-of-band frameworks

T4 History

A second-class citizen in Visual Studio 2005

Available through the DSL tools download or through the Guidance Automation Toolkit (GAT – primarily used for software factories)

T4 History

More of a first-class citizen in VS 2008Built-in, but not available through File -> New

No highlighting or Intellisense

A lot of “dogfooding” started, especially with SP 1 – EF, MVC

T4 History

Almost a first-class citizen in VS 2010Still no highlighting or Intellisense

Dogfooding all over the place – EF (all code generation items), MVC 2, Architecture Tools)

Microsoft Dogfooding

ASP.NET MVC

ADO.NET Entity Framework

ASP.NET Dynamic Data

Lightswitch (cannot currently get at the templates used, though)

VS 2010 Architecture Tool Modeling Feature Pack (forward-engineering)

Microsoft Dogfooding – ASP.NET MVC

Add Controller and Add View

Templates found at [Visual Studio Install Directory]\Common7\IDE\ItemTemplates\[CSharp | VisualBasic]\Web\MVC 2\CodeTemplates\

Microsoft Dogfooding – ASP.NET MVC

Microsoft Dogfooding – Entity Framework

Default, EF-aware EntitiesAdd the EntityObject Generator as a code generation item to see what the default template does behind the scenes

POCO and Self-Tracking Entities Implemented through templates

Add code generation item to see the templates in your project

Microsoft Dogfooding – Entity Framework

Microsoft Dogfooding – Architecture Tools

Modeling Feature Pack (built in to VS 2010 Feature Pack 2) allows for forward-generation of code from diagrams

Templates found at [Visual Studio Install Directory]\Common7\IDE\Extensions\Microsoft\Visualization and Modeling Feature Pack\2.0\Templates\Text\

Microsoft Dogfooding – Architecture Tools

Microsoft Dogfooding – Demo

T4 Basics and T4 ToolingUsing T4 Across the Life of an Application

What is T4?

T4 Text Transformation

Standard Templates

Design-time templates

Meant to be run within the context of Visual Studio

Precompiled TemplatesRuntime templates

For text to be used by an applicationForm letters

For CodeDOM-like activities – dynamic compilation of code

Note T4 would be language-specific where raw CodeDOM would not

Also makes for easily composable and reusable blocks

Just call the TransformText method, it returns a string

T4 Syntax - Directives

Template <#@ template #>Language

Debug

Inherits

Hostspecific

Output <#@ output #>Extension

Import <#@ import #>Namespace

Resolves to “using” in C# generation

T4 Syntax - Directives

Assembly <#@ assembly #>Name

Equivalent of Add Reference…

Careful if you need to rebuild – locks the assembly because of the way the T4 engine handles AppDomains

T4 Toolbox has a VolatileAssembly custom directive

Fixed in VS 2010 SP1 via shadowing

You can use MSBuild-style references$(SolutionDir)

$(OutDir)

T4 Syntax - Directives

Include <#@ include #>File

As if file contents were dropped directly into the template

Parameter <#@ parameter #>Name

Type

T4 Syntax – Text Blocks

Standard block of text with no delimiters – will be placed in the output file wholesale

T4 Syntax – Control Blocks

Statement or Standard Block<# #>

For standard code not contained in a class

T4 Syntax – Control Blocks

Expression Block<#= #>

For any expression, evaluates and converts to string

T4 Syntax – Control Blocks

Class Block<#+ #>

For placing helper classes (or any other code not included in the main transform) inline in the template

Must be the last block in a templateUnless you’re including a file with a Class Block using the Include Directive

This is noted because it should be common…

T4 Syntax – Utility Methods

Write and WriteLineEssentially the same as an Expression block

Allows for text output inside Standard blocks

May be preferable over Expression blocks for readability, if a Standard block is long or contains nesting

Formatting overloads that take string params at the end

T4 Syntax – Utility Methods

Indent Methods and PropertiesCurrentIndent property returns the current indent level

PushIndent indents

PopIndent moves back one indention

ClearIndent clears all indents

Error and Warning MethodsTo write to the VS Error list

Error(“some expression”)

T4 Syntax – Utility Methods

Host PropertyIf hostspecific is set to “true” in the template directive

Provides some helpful methodsResolvePath

Hooks into the VS API, if VS is the hostCast this.Host as an IServiceProvider

Then GetService of the DTE type

T4 Syntax – Utility Methods

Host Property Example to access VS API:<#@ template hostspecific="true" language="C#" #> <#@ output extension=".txt" #> <#@ assembly name="EnvDTE" #> <#@ import namespace="EnvDTE" #> <# IServiceProvider serviceProvider = (IServiceProvider)this.Host; DTE dte = serviceProvider.GetService(typeof(DTE)) as DTE; #>

Number of projects in this solution: <#= dte.Solution.Projects.Count #>

T4 Syntax – Escape Sequences

Use the \ for escaping any special characters

\<# ... \#>

T4 Tooling

Use an editor!

Good “freemium” editors out there in the Visual Studio Gallery

Tangible T4 EditorNo need to install the Tangible architecture tools

Latest version has a fix for use with ReSharper

DevArt T4 Editor

Clarius Visual T4

T4 Tooling

Tangible T4 Editor Extras – Template GalleryMany excellent examples

Many snippets that would typically be used for Includes

Multi-file output

VS automation

Many out-of-the-box solutionsHTML image gallery

T4 Tooling

Still no editor support – syntax highlighting/Intellisense – in VS 11

Will this change? No indications…

Using T4 Across the Life of an Application

What is T4?

T4 Basics and T4 Tooling

Code Generation Issues are Universal

UI Designers in VS

You’ve seen this a lot://---------------// <auto-generated>// This code was generated by a tool.// Changes to this file will be lost if the code is regenerated.// </auto-generated>//---------------

Code Generation Issues are Universal

Extending the codeInheritance

Partial classes!!!

Composition

Resources

Oleg Sych’s Blog: http://www.olegsych.com/

T4 Team/Gareth JonesOld: http://blogs.msdn.com/b/garethj/

New: http://blogs.msdn.com/b/t4/

Kathleen Dollard: http://msmvps.com/blogs/kathleen/

MSDN: http://msdn.microsoft.com/en-us/library/bb126445.aspx

Recommended