Gant Software Systems

T4

Managing Large T4-Based Code Generation Projects

This past weekend, I spent a great deal of time reworking some parts of our data access layer for Agulus that have been problematic in the past, mostly by trying to get rid of places where we are using ExecuteScalar and places where we are are working with DataTables, as both places are very sensitive to changes in the underlying database schema and the errors don’t surface until runtime, which really stinks. I managed to figure out how to get all the metadata I needed to replace this functionality (some things could be easier….) and proceeded to start editing my templates to achieve this goal. As I did so, I started reflecting on how much I’ve learned, mostly the hard way, about how to manage larger sets of T4 templates while keeping things maintainable. I’ve not seen a lot of guidance floating around on how to deal well with this stuff, so here’s a list of a few things I’ve figured out (so far). Most of the guidance below sounds very much like the guidance you’d expect to see when building something using ASP.NET MVC, which if you think about it, makes a lot of sense since both share many similar concerns. None of these are earth-shattering, but people tend to forget that code that generates code should be maintained at the same quality level as code that is actually being shipped.

T4 Templates: Multi-File Outputs Considered Harmful

I’ve been working on a side project with a good friend and it uses T4 templates fairly heavily for wrapping database code (no, we couldn’t use EF for this when we started – we might look at it again later though) and for building up a nice wrapper for templated email. It worked like a champ, until I decided to do a bit of code cleanup to make it more aesthetically pleasing to myself. I was getting concerned because the code generated by the templates was somewhere north of 20,000 lines, declared well north of 100 separate classes with dozens of interfaces and lots of logic for interacting with the database (and with caching). It was all beautiful, clean, eloquent code (ok, I’m lying, but it wasn’t ugly enough that I hated it) and did its job remarkably well. I heartily recommend the Tangible T4 Text editor plugin for Visual Studio, as it makes a lot of this code work quite smoothly and pretty much never gave me a problem (I had to look up which tool I was using – I promise you I could remember off the top of my head if it broke regularly).