T4 / Code GenerationPresented by Joubin Najmaie (@codekindler)February 23, 2011Kitchener .NET UG: @cttdnug
AgendaWho am I?Motivations Behind Using T4T4 SyntaxDebugging T4 TemplatesBreakCustom T4 Host using GAXCompiling Generated CodeT4 Item TemplatesVS 2010 Item/Project TemplatesResourcesQ&A
Who am I?Technical Architect at one of the largest IT solution companies in North AmericaProject: www.pagefragments.comBlog: www.codekindler.comTwitter: @codekindlerEmail: joubin.najmaie@gmail.comWho am I?
Motivations Behind Using T4What is T4?Text Template Transformation ToolkitTransformation engineVehicle to Generates code from described modelsModels could beVisualClass diagramsERDs, Entity FrameworkText-basedXSDMetadata
Motivations behind using T4Why T4 is important?Developer guidance + speedNot limited to code: any text-based assetDocumentation generationScaffolding applicationsORMsDomain Specific DevelopmentExtending Visual StudioItem TemplatesIncluding latest ASP.NET MVC Controller and View templatesProject Templates
Motivations Behind Using T4How I got to work with T4Consultancy work – worked on a PoC migration of a static site to a content managedwith 1000+ pagesWorked with a couple of CMSs – SharePoint, Sitecore and an in-house CMS at an agency firmPatterns started emergingCreate fragments of a site that are most needed to be managed more regularly than others by different ownersThe fragments in the system are compiled and included using T4Addressing shortcomings and pains of CMSs
T4 Syntax
T4 SyntaxAnatomy of T4 templates
T4 SyntaxText Templating ‘workflow’
T4 SyntaxProcessing Directives Similar to ASPX or ASCX <#@ and end with #> Directives template assembly import output include
T4 Syntaxtemplate directive <#@ template debug="true" language="C#" #> Parametersdebuglanguageinheritshostspecific
T4 Syntaxtemplate directive parametersdebug parameterSystem %TEMP% folderlanguage parameterValues: C#, VB, C#3.5inherits parameterTells which base class to usehostspecific parameterA reference to the object that the hosts the engine.e.g. Host.TemplateFileHost.StandardAssemblyReferences
T4 Syntaxassembly directive<#@ assembly #> Parameter name could be an assembly in the GAC<#@ assembly name=“System.Data” #> absolute path to the assembly<#@ assembly name=“c:\projects\proj1\bin\debug\proj1.dll” #>
T4 Syntaximport directive <#@ import #> ParameternamespaceE.g. <#@ import      namespace=“System.Collections.Generic” #>
T4 Syntaxinclude directive <#@ include #> Parameter file e.g. <#@ include file=“includedfile.tt” #>
Demodirectives
T4 SyntaxOn to T4 blocks
T4 SyntaxT4 Blocks Text blocks Code blocks Statement Expression Class feature
T4 SyntaxText BlocksNon-programmatic plain text
T4 SyntaxStatement Blocks Delineated using <# #>
T4 SyntaxExpression Blocks Delineated using <#= #>
T4 SyntaxClass Feature Blocks Delineated using <#+ #> Add any class level constructHelper functionsFieldsConstantsProperties
DemoT4 Blocks
Debugging T4 TemplatesDebuggingInsert System.Diagnostics.Debugger.Launch(); anywhere in the code blocks
DemoDebugging T4 Templates
Break ?
Custom T4 Host using GAXCustom T4 Host Guidance Automation Extensionshttp://bit.ly/fW99Zh Add references in VSMicrosoft.Practices.RecipeFramework.VisualStudio.LibraryMicrosoft.VisualStudio.TextTemplating
DemoCustom T4 Host
DemoCompile Generated Code
T4 Item TemplatesVS T4 Item Templates Text TemplateTextTemplatingFileGeneratorPreprocessed Text TemplateTextTemplatingFilePreprocessor Redistributing T4 engine with your app
DemoT4 Item Templates
VS 2010 Item/Project TemplatesVS Item TemplatesSingle file versus multi-file templatesAs .vsi/.zipVS 2010/{vs.net folder}/common7/ide/itemtemplates/{user folder}\Visual Studio 2010\Templates\ItemTemplatesTemplate parametersWhen the template wizard runs they are replaced
VS 2010 Item/Project TemplatesParameters to a VS template fileComplete list of all parameters: http://bit.ly/hJayFX
VS 2010 Item/Project TemplatesVS Template files Single File Template Multi-File Template
DemoVS 2010 Item/Project Templates
CTAsTry out the Text Template item templateStart thinking of scenarios where you can apply Domain Specific DevelopmentLook at other solutions that have used this development patternMany on Codeplex.com
ResourcesWhere to go for resources?Code Generation and Text Templates (T4)http://bit.ly/eJL91tT4 Templates: A Quick-Start Guide for ASP.NET MVC Developershttp://bit.ly/cVKYp5Language Oriented Programming: The Next Programming Paradigm:http://bit.ly/bVqYoGCodePlex: http://bit.ly/i0VnHKBookDomain-Specific Development with Visual Studio DSL ToolsISBN: 0321398203
Visual Studio Plug-insPlug-in by Tangible Engineeringhttp://bit.ly/dfFhEiT4 Editor by Clariushttp://bit.ly/cHfGRnResources
Resources will be postedBlog: http://www.codekindler.comEmail: joubin.najmaie@gmail.comResources
T4 / Code GenerationQ&A

T4 / Code Generation

  • 1.
    T4 / CodeGenerationPresented by Joubin Najmaie (@codekindler)February 23, 2011Kitchener .NET UG: @cttdnug
  • 2.
    AgendaWho am I?MotivationsBehind Using T4T4 SyntaxDebugging T4 TemplatesBreakCustom T4 Host using GAXCompiling Generated CodeT4 Item TemplatesVS 2010 Item/Project TemplatesResourcesQ&A
  • 3.
    Who am I?TechnicalArchitect at one of the largest IT solution companies in North AmericaProject: www.pagefragments.comBlog: www.codekindler.comTwitter: @codekindlerEmail: joubin.najmaie@gmail.comWho am I?
  • 4.
    Motivations Behind UsingT4What is T4?Text Template Transformation ToolkitTransformation engineVehicle to Generates code from described modelsModels could beVisualClass diagramsERDs, Entity FrameworkText-basedXSDMetadata
  • 5.
    Motivations behind usingT4Why T4 is important?Developer guidance + speedNot limited to code: any text-based assetDocumentation generationScaffolding applicationsORMsDomain Specific DevelopmentExtending Visual StudioItem TemplatesIncluding latest ASP.NET MVC Controller and View templatesProject Templates
  • 6.
    Motivations Behind UsingT4How I got to work with T4Consultancy work – worked on a PoC migration of a static site to a content managedwith 1000+ pagesWorked with a couple of CMSs – SharePoint, Sitecore and an in-house CMS at an agency firmPatterns started emergingCreate fragments of a site that are most needed to be managed more regularly than others by different ownersThe fragments in the system are compiled and included using T4Addressing shortcomings and pains of CMSs
  • 7.
  • 8.
  • 9.
  • 10.
    T4 SyntaxProcessing DirectivesSimilar to ASPX or ASCX <#@ and end with #> Directives template assembly import output include
  • 11.
    T4 Syntaxtemplate directive<#@ template debug="true" language="C#" #> Parametersdebuglanguageinheritshostspecific
  • 12.
    T4 Syntaxtemplate directiveparametersdebug parameterSystem %TEMP% folderlanguage parameterValues: C#, VB, C#3.5inherits parameterTells which base class to usehostspecific parameterA reference to the object that the hosts the engine.e.g. Host.TemplateFileHost.StandardAssemblyReferences
  • 13.
    T4 Syntaxassembly directive<#@assembly #> Parameter name could be an assembly in the GAC<#@ assembly name=“System.Data” #> absolute path to the assembly<#@ assembly name=“c:\projects\proj1\bin\debug\proj1.dll” #>
  • 14.
    T4 Syntaximport directive<#@ import #> ParameternamespaceE.g. <#@ import namespace=“System.Collections.Generic” #>
  • 15.
    T4 Syntaxinclude directive<#@ include #> Parameter file e.g. <#@ include file=“includedfile.tt” #>
  • 16.
  • 17.
  • 18.
    T4 SyntaxT4 BlocksText blocks Code blocks Statement Expression Class feature
  • 19.
  • 20.
    T4 SyntaxStatement BlocksDelineated using <# #>
  • 21.
    T4 SyntaxExpression BlocksDelineated using <#= #>
  • 22.
    T4 SyntaxClass FeatureBlocks Delineated using <#+ #> Add any class level constructHelper functionsFieldsConstantsProperties
  • 23.
  • 24.
    Debugging T4 TemplatesDebuggingInsertSystem.Diagnostics.Debugger.Launch(); anywhere in the code blocks
  • 25.
  • 26.
  • 27.
    Custom T4 Hostusing GAXCustom T4 Host Guidance Automation Extensionshttp://bit.ly/fW99Zh Add references in VSMicrosoft.Practices.RecipeFramework.VisualStudio.LibraryMicrosoft.VisualStudio.TextTemplating
  • 28.
  • 29.
  • 30.
    T4 Item TemplatesVST4 Item Templates Text TemplateTextTemplatingFileGeneratorPreprocessed Text TemplateTextTemplatingFilePreprocessor Redistributing T4 engine with your app
  • 31.
  • 32.
    VS 2010 Item/ProjectTemplatesVS Item TemplatesSingle file versus multi-file templatesAs .vsi/.zipVS 2010/{vs.net folder}/common7/ide/itemtemplates/{user folder}\Visual Studio 2010\Templates\ItemTemplatesTemplate parametersWhen the template wizard runs they are replaced
  • 33.
    VS 2010 Item/ProjectTemplatesParameters to a VS template fileComplete list of all parameters: http://bit.ly/hJayFX
  • 34.
    VS 2010 Item/ProjectTemplatesVS Template files Single File Template Multi-File Template
  • 35.
  • 36.
    CTAsTry out theText Template item templateStart thinking of scenarios where you can apply Domain Specific DevelopmentLook at other solutions that have used this development patternMany on Codeplex.com
  • 37.
    ResourcesWhere to gofor resources?Code Generation and Text Templates (T4)http://bit.ly/eJL91tT4 Templates: A Quick-Start Guide for ASP.NET MVC Developershttp://bit.ly/cVKYp5Language Oriented Programming: The Next Programming Paradigm:http://bit.ly/bVqYoGCodePlex: http://bit.ly/i0VnHKBookDomain-Specific Development with Visual Studio DSL ToolsISBN: 0321398203
  • 38.
    Visual Studio Plug-insPlug-inby Tangible Engineeringhttp://bit.ly/dfFhEiT4 Editor by Clariushttp://bit.ly/cHfGRnResources
  • 39.
    Resources will bepostedBlog: http://www.codekindler.comEmail: joubin.najmaie@gmail.comResources
  • 40.
    T4 / CodeGenerationQ&A

Editor's Notes

  • #12 Characteristics of the transformed outputDebug --- true/falseTrue – you can take a look files in system %TEMP% folderLanguage: Values: C#, VB, C#3.5InheritsBase class: Microsoft.VisualStudio.TextTemplating.TextTransformationTells which base class to useHostspecific --- true/falseMostly used to output template file name to the transformed fileHost.TemplateFileHost.StandardAssemblyReferenes
  • #14 “Add reference” in VSOne parameternamecould be an assembly in the GAC&lt;#@ assembly name=“System.Data” #&gt;or absolute path to the assembly&lt;#@ assembly name=“c:\\projects\\proj1\\bin\\debug\\proj1.dll” #&gt;
  • #15 Equivalent to: C# using VB.NET importOne parameternamespace
  • #16 File to be included verbatim in templateOne parameterFileCan contain any of the valid T4 constructsRelative paths -- to the main template
  • #20 Just type directly into the .tt file Copied directly to TransformText method%TEMP%Show generated file
  • #21 Control the flow of processing in TransformText methodExample usage:To conditionally output Text blocksIterate over data and output things conditionally
  • #22 Use to add strings to the output fileAdded, in sequenceTo the “TransformText” method with calls to the ToString() methodUsed in cases to change some aspect of the generated output text file to useCalculated valuesExternal data e.g. database column valuessome other calculated value in a Statement block somewhere else in the .TT file. C# – could be multiple linesVB.NET – single lines only