Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Code that Codes For You

Code that Codes For You

Using T4 Templates to improve your code's maintainability, and editing the default Entity Framework T4 templates
Demo Code at http://goforth.codeplex.com/SourceControl/latest

RCGoforth

June 16, 2012
Tweet

More Decks by RCGoforth

Other Decks in Programming

Transcript

  1. Code that Codes For You (T4 Templates) A basic intro

    to T4 templates and how you can use them in your projects now to save you time. Richard Goforth [email protected] Contact Magenic 1600 Utica Avenue South, Suite 800 St. Louis Park, MN 55416 1 (877)-277-1044 [email protected]
  2. What Are T4 Templates » Text Template Transformation Toolkit »

    Text blocks with control logic (similar to programming for the web) » Regular code, a small isolated program with a very specific purpose » Any input and any output (you can do anything you want, though it is not necessarily wise).
  3. Why Use T4 Templates » DRY – Don’t Repeat Yourself

    » The ability to repeat yourself less often then before » More places with single location maintenance than you were able to do without T4 » Reduce manual mistakes and omissions in syncing code changes across different types of files and databases
  4. Some Usage Scenarios Field Level Sync •Config Files External System

    Continuity •DB Enumeration Classes and Enums in Code •ASPX Navigation with Intellisense and compiler support Highly Repeatable Code •Data Entity Classes •WiX File Creation •CRUD Stored Procedures
  5. Using T4 in Visual Studio Tools -> Extension Manager ->

    Online Templates -> Search » Tangible T4 Editor » Syntax highlighting » IntelliSense in code blocks » T4 Toolbox » Includes several basic templates to get you started on a number of different tasks
  6. Basic Structure Basic Control Structure Usually Surround Text blocks (use

    {}) Loops and Decision Trees <# Inline Evaluation Used for a substituting a single field or value Use anything in the current scope <#= Class Function Location doesn’t matter Class blocks that sit next to the generating class <#+ Directive Statement Define output, imports, and include statements New in VS2010: template parameters <#@
  7. Basic Structure <#@ template debug="true" hostSpecific="true" language="C#" #> <#@ output

    extension=".cs" #> <#= System.DateTime.Now.ToString() #> //Comment at the top of the file <# foreach(var prop in getProperties()) { WriteLine(prop.key); } #> <#+ public Dictionary<Type, string> getProperties() { … } #>
  8. Built in Functions All of these are methods on the

    TextTransformation class » Write / WriteLine » Text blocks are converted to “Write” statements on preprocessing » PushIndent / PopIndent /ClearIndent » Use these with a string argument to set the indent to that string. » Warning » Will output a Visual Studio warning upon compiling the template » Error » Catch Exceptions in your template and use the error method to output for a better debugging experience
  9. Common Inputs XML UML Diagrams WSDL Anything else you can

    think of Edmx Model First EF Uses Microsoft Libraries to deal with the edmx file SQL Database Enums in a DB First Environment CRUD Stored Proc Generation Linq To Sql Code from an existing DB
  10. Template Include Files » Directive » <#@ include file=“filename.ttinclude” #>

    » Helper Function Libraries » Surrounded with <#+ #>, the class indicator
  11. Creating Multiple Files » Two similar file management classes »

    T4 Template Manager class by Damien Guard » http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4- made-easy-revisited » The EF Way » EntityFrameworkTemplateFileManager in EF.Utility.CS.ttinclude
  12. Modifying EF DB Generation Code » Example – Having the

    defaults defined in the Model output as part of the db script. » SSDLToSQL10.tt » Add a call to a new method (WriteDefault()) to output the default value for a property in the edmx file to the sql output » GenerateTSQL.Utility.ttinclude » Create the write default method that takes the EDMProperty and extracts the appropriate sql text for a default value
  13. Modifying EF Class Generation Code » Model.tt example – an

    extra method on each class » I wanted to take the dictionary created from Telerik controls and populate values on my generated classes directly from them. » I wanted to set associated navigation properties as well » SetPropertiesFromDictionary()
  14. Simple Debugging » <#@ template debug="true" language="C#" #> » <#@

    import namespace="System.Diagnostics" #> » <# Debugger.Launch(); #> » Added at the beginning of your code, this will prompt you to open a new instance of VS and debug the template generation » <# Debugger.Break(); #> » re-enter the debugger later in the code
  15. T4 Toolbox Script File Generator Run code whenever a file

    in the project is changed Update dependent files Validate an xml file against a schema
  16. Preprocessed (Design-Time) Templates » TextTemplatingFilePreprocessor » TextTemplatingFileGenerator » Outputs a

    cs file that can be run with Template.Transform, so that templates can be created within another program, or with runtime context
  17. Newness » In 2012 » Improvements in debugging, the templates

    don’t have to run in the devenv process, and thus can be debugged directly. » “PreProcessed” is now “Design-Time” » In 2010 » Template inheritance » Parameters » In Tangible T4 Editor 2.0 » Transform on Build
  18. Places to Visit » http://www.olegsych.com/ » MSDN T4 Pages »

    http://www.youtube.com/playlist?list=PL6D51E9F1B9C955BB » http://t4-editor.tangible-engineering.com/t4_editor_Videos.html » [email protected]
  19. Q