Nov 14 2008

T4 Templates For The .NET Compact Framework

Category: Software DevelopmentJeff @ 22:48

I first learned about the Text Template Transformation Toolkit (T4) about a month ago when reading some blog posts from Rob Conery and Scott Hanselman. T4 is a code generation tool that comes with Visual Studio 2008 (there's also an add-in for VS 2005).  Rob likes T4 so much, that he's rewriting his SubSonic data access layer builder to use T4 template generation (check out his second preview of SubSonic 3.0).

As I wrote about a few days ago (Dependency Injection for the Compact Framework), I've recently returned to the world of building Smart Device applications using the .NET Compact Framework.  I've been working on building the basic foundations of the domain model and I started running into some situations where code generation could make my team more productive.  So, I tried adding a T4 template to my Compact Framework project (a file with a ".tt" file extension) and *boom*!  Three errors crop up:

  1. Compiling transformation: The type or namespace name 'CompilerError' does not exist in the namespace 'System.CodeDom.Compiler' (are you missing an assembly reference?)
  2. Compiling transformation: The type 'System.CodeDom.Compiler.CompilerErrorCollection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
  3. Compiling transformation: 'System.CodeDom.Compiler.CompilerErrorCollection' does not contain a definition for 'Add'

Why doesn't this work?  Because Visual Studio is attempting to use the Compact Framework assemblies in order to process the T4 template file.  But the Compact Framework assemblies don't include the System.CodeDom namespace. 

I don't think Microsoft is ever going to add the CodeDom namespace to the Compact Framework.  But there is a way to get T4 templates working in a Compact Framework project.  You basically start off by creating two separate projects, one targeting the full .NET Framework, and another targeting the Compact Framework.  Then, combine these projects into the same folder so they can share files between them.  Finally, you can add .tt files to the full .NET Framework project and include the generated .cs files in your Compact Framework project.  Voila!  Templates for the Compact Framework.

I've created a quick-start document to walk you through the process: T4 Templates for the .NET Compact Framework

Happy code generating!

Tags: , ,


Comments are closed