T4 is an engine built into Visual Studio for code generation. It has been around since VS 2005 and I have been playing with it for a while. In the past I used it to generate unit tests just after compile time that used the templates and reflection to automatically test a particularly nasty DB persistence layer for one of our company’s products. It ended up uncovering about 4000 inconsistencies and potential bugs.

More recently I have created a template that automatically creates the paths for the pages in your asp.net project. I hate to hard code values, but sometimes in asp.net it seems you cannot get around hard coding references. This will eliminate that dependency.

It works by iterating over the file structure of your project and finds classes that inherit from Page. It then generates a partial class for each page that has a static string with the full path to that page. It also generates a static class for each type of image resource with a static string with its path as well. In this way you can reference all of the other pages in your project like this <%=MyPage.Path %> or your resources <%=Images.JPG.MyPicture%>. If you ever decide to move the pages or resources around, for whatever reason you can freely do so without worrying about breaking hard coded references.

Here is the link to the file that does it.