46
Using Microsoft’s T4 Across the Life of an Application Gary Pedretti [email protected] 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 .

T4 presentation

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: T4 presentation

Using Microsoft’s T4 Across the Life of an Application

Gary Pedretti

[email protected]

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.

Page 2: T4 presentation

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

Page 3: T4 presentation

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

Page 4: T4 presentation

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

Page 5: T4 presentation

What is T4?T4 Basics and T4 Tooling

Using T4 Across the Life of an Application

Page 6: T4 presentation

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

Page 7: T4 presentation

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

Page 8: T4 presentation

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#

Page 9: T4 presentation

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

Page 10: T4 presentation

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)

Page 11: T4 presentation

T4 History

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

Including out-of-band frameworks

Page 12: T4 presentation

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)

Page 13: T4 presentation

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

Page 14: T4 presentation

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)

Page 15: T4 presentation

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)

Page 16: T4 presentation

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\

Page 17: T4 presentation

Microsoft Dogfooding – ASP.NET MVC

Page 18: T4 presentation

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

Page 19: T4 presentation

Microsoft Dogfooding – Entity Framework

Page 20: T4 presentation

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\

Page 21: T4 presentation

Microsoft Dogfooding – Architecture Tools

Page 22: T4 presentation

Microsoft Dogfooding – Demo

Page 23: T4 presentation

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

What is T4?

Page 24: T4 presentation

T4 Text Transformation

Page 25: T4 presentation

Standard Templates

Design-time templates

Meant to be run within the context of Visual Studio

Page 26: T4 presentation

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

Page 27: T4 presentation

T4 Syntax - Directives

Template <#@ template #>Language

Debug

Inherits

Hostspecific

Output <#@ output #>Extension

Import <#@ import #>Namespace

Resolves to “using” in C# generation

Page 28: T4 presentation

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)

Page 29: T4 presentation

T4 Syntax - Directives

Include <#@ include #>File

As if file contents were dropped directly into the template

Parameter <#@ parameter #>Name

Type

Page 30: T4 presentation

T4 Syntax – Text Blocks

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

Page 31: T4 presentation

T4 Syntax – Control Blocks

Statement or Standard Block<# #>

For standard code not contained in a class

Page 32: T4 presentation

T4 Syntax – Control Blocks

Expression Block<#= #>

For any expression, evaluates and converts to string

Page 33: T4 presentation

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…

Page 34: T4 presentation

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

Page 35: T4 presentation

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”)

Page 36: T4 presentation

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

Page 37: T4 presentation

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 #>

Page 38: T4 presentation

T4 Syntax – Escape Sequences

Use the \ for escaping any special characters

\<# ... \#>

Page 39: T4 presentation

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

Page 40: T4 presentation

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

Page 41: T4 presentation

T4 Tooling

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

Will this change? No indications…

Page 42: T4 presentation

Using T4 Across the Life of an Application

What is T4?

T4 Basics and T4 Tooling

Page 43: T4 presentation

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>//---------------

Page 44: T4 presentation

Code Generation Issues are Universal

Extending the codeInheritance

Partial classes!!!

Composition

Page 45: T4 presentation

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