T4 presentation

1,812 views

Published on

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,812
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
22
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • Also, C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\Extensions\\Microsoft\\Entity Framework Tools
  • <#@ template language="C#" #> <#@ parameter name="MyParameter" type="System.String" #> Parameter in expression block: <#= MyParameter #> Parameter in statement block: <# Write(MyParameter) #>Call Context Template:<#@ template language="C#" hostspecific="true" #> <#@ output extension=".txt" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Runtime.Remoting.Messaging" #> <#@ import namespace="Microsoft.VisualStudio.TextTemplating" #> <# string templateFile = this.Host.ResolvePath("MyTemplate.tt"); string templateContent = File.ReadAllText(templateFile); CallContext.LogicalSetData("MyParameter", "CallContextValue"); Engine engine = new Engine(); string generatedContent = engine.ProcessTemplate(templateContent, this.Host); CallContext.FreeNamedDataSlot("MyParameter"); this.Write(generatedContent); #>Session Template:<#@ template debug="true" hostspecific="true" language="C#" #> <#@ output extension=".txt" #> <#@ import namespace="System.IO" #> <#@ import namespace="Microsoft.VisualStudio.TextTemplating" #> <# string templateFile = this.Host.ResolvePath("MyTemplate.tt"); string templateContent = File.ReadAllText(templateFile); TextTemplatingSession session = new TextTemplatingSession(); session["MyParameter"] = "SessionValue"; varsessionHost = (ITextTemplatingSessionHost) this.Host; sessionHost.Session = session; Engine engine = new Engine(); string generatedContent = engine.ProcessTemplate(templateContent, this.Host); this.Write(generatedContent); #>
  • Finally, we'll develop a data-driven application that takes advantage of T4 generation, showing how to handle and extend generated code in a changing codebase and how to establish a workflow to use T4 over the lifecycle of an application.
  • T4 presentation

    1. 1. Using Microsoft’sT4 Across the Lifeof an ApplicationGary PedrettiGary.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.
    2. 2. About Centare Consulting Services Organization Primary 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
    3. 3. Gary PedrettiSolutions Manager, Agile PracticeOver 12 years in the software industry – DatabaseAdministrator, Developer, BusinessAnalyst, Application ArchitectScrum: Team member, ScrumMaster, Coach, Certified Scrum Trainer forScrum.orgMCPD 4.0 Web, MCTS 4.0 WCF/Web/Data Access, MCDBA MSSQL2000, PSM, PSD .NET, PSD Java, CSM, MCPD 3.5 ASP.NET, MCTS 3.5WCF/ASP.NET/ADO.NET, MCTS SharePoint 2003 Infrastructure, MCPD 2.0Enterprise, MCTS 2.0 Distributed/Web/Windows, MCSD 1.1, MCAD1.1, MOUS
    4. 4. Professional Scrum at Scrum.org Professional Professional Professional Scrum Scrum Master Scrum Product Owner Developer .NET or Java Architects Business Analysts Product Owners DB Specialists Scrum Masters Executives Designers Developers Testers Professional Scrum Foundations Everyone
    5. 5. What is T4? T4 Basics and T4 Tooling Using T4 Across the Life of an Application
    6. 6. 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
    7. 7. 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
    8. 8. Why? Automate repetitive, boilerplate code Data Access code Front-end scaffolding Produce templated text output to be used by applications Form letters Transformations between different text formats XML to C#
    9. 9. 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
    10. 10. 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)
    11. 11. T4 History Increasing importance and support as we’ve moved from Visual Studio 2005 to Visual Studio 2010 Including out-of-band frameworks
    12. 12. 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)
    13. 13. T4 History More of a first-class citizen in VS 2008 Built-in, but not available through File -> New No highlighting or Intellisense A lot of “dogfooding” started, especially with SP 1 – EF, MVC
    14. 14. T4 History Almost a first-class citizen in VS 2010 Still no highlighting or Intellisense Dogfooding all over the place – EF (all code generation items), MVC 2, Architecture Tools)
    15. 15. 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)
    16. 16. Microsoft Dogfooding – ASP.NET MVC Add Controller and Add View Templates found at [Visual Studio Install Directory]Common7IDEItemTemplates[CSharp | VisualBasic]WebMVC 2CodeTemplates
    17. 17. Microsoft Dogfooding – ASP.NET MVC
    18. 18. Microsoft Dogfooding – Entity Framework Default, EF-aware Entities Add 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
    19. 19. Microsoft Dogfooding – Entity Framework
    20. 20. 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]Common7IDEExtensionsMicrosoftVis ualization and Modeling Feature Pack2.0TemplatesText
    21. 21. Microsoft Dogfooding – Architecture Tools
    22. 22. Microsoft Dogfooding – Demo
    23. 23. What is T4?T4 Basics and T4 Tooling Using T4 Across the Life of an Application
    24. 24. T4 Text Transformation
    25. 25. Standard Templates Design-time templates Meant to be run within the context of Visual Studio
    26. 26. Precompiled Templates Runtime templates For text to be used by an application Form 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
    27. 27. T4 Syntax - Directives Template <#@ template #> Language Debug Inherits Hostspecific Output <#@ output #> Extension Import <#@ import #> Namespace Resolves to “using” in C# generation
    28. 28. 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)
    29. 29. T4 Syntax - Directives Include <#@ include #> File As if file contents were dropped directly into the template Parameter <#@ parameter #> Name Type
    30. 30. T4 Syntax – Text Blocks Standard block of text with no delimiters – will be placed in the output file wholesale
    31. 31. T4 Syntax – Control Blocks Statement or Standard Block <# #> For standard code not contained in a class
    32. 32. T4 Syntax – Control Blocks Expression Block <#= #> For any expression, evaluates and converts to string
    33. 33. 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 template Unless you’re including a file with a Class Block using the Include Directive This is noted because it should be common…
    34. 34. T4 Syntax – Utility Methods Write and WriteLine Essentially 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
    35. 35. T4 Syntax – Utility Methods Indent Methods and Properties CurrentIndent property returns the current indent level PushIndent indents PopIndent moves back one indention ClearIndent clears all indents Error and Warning Methods To write to the VS Error list Error(“some expression”)
    36. 36. T4 Syntax – Utility Methods Host Property If hostspecific is set to “true” in the template directive Provides some helpful methods ResolvePath Hooks into the VS API, if VS is the host Cast this.Host as an IServiceProvider Then GetService of the DTE type
    37. 37. 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 #>
    38. 38. T4 Syntax – Escape Sequences Use the for escaping any special characters <# ... #>
    39. 39. T4 ToolingUse an editor! Good “freemium” editors out there in the Visual Studio Gallery Tangible T4 Editor No need to install the Tangible architecture tools Latest version has a fix for use with ReSharper DevArt T4 Editor Clarius Visual T4
    40. 40. T4 Tooling Tangible T4 Editor Extras – Template Gallery Many excellent examples Many snippets that would typically be used for Includes Multi-file output VS automation Many out-of-the-box solutions HTML image gallery
    41. 41. T4 Tooling Still no editor support – syntax highlighting/Intellisense – in VS 11 Will this change? No indications…
    42. 42. What is T4? T4 Basics and T4 ToolingUsing T4 Across the Life of an Application
    43. 43. 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 lostif the code is regenerated.// </auto-generated>//---------------
    44. 44. Code Generation Issues are Universal Extending the code Inheritance Partial classes!!! Composition
    45. 45. Resources Oleg Sych’s Blog: http://www.olegsych.com/ T4 Team/Gareth Jones Old: 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
    46. 46. Resources Tangible’s tutorials: http://t4-editor.tangible- engineering.com/How-Do-I-With-T4-Editor-Text- Templates.htm Wikipedia code generation tool comparison: http://en.wikipedia.org/wiki/Comparison_of_code _generation_tools

    ×