Last month, I wrote a number of posts on using T4 templates to get strong typing in ASP.NET MVC applications. The result is the T4MVC template available on CodePlex. This template has been pretty popular with many MVC users, and I received a huge amount of feedback on improving it. Most of it has been integrated into the CodePlex version (see the extensive History section in the TT file!).
While T4MVC is only useful to MVC applications, someone suggested that ASP.NET WebForms applications could also benefit from some strong typing, so I put together a little T4 template that does some of that.
Unlike T4MVC which tries to cover a whole range of MVC scenarios (relating to Controllers, Actions and Views), this template just does one thing: it generates strongly typed constants that points to the path to all aspx/ascx/master files. Since it only deals with path, I called it AspPathGuru.tt.
To use it, just drop AspPathGuru.tt (attached to this post) to the root of your Web Application.
You’ll then be able to change code that looks like:
Control uc = LoadControl("~/UserControls/MyUserControl.ascx");
Control uc = LoadControl(Paths.UserControls.MyUserControl_ascx);
The benefits are clear:
Some limitations you should be aware of:
Anyway, at this point this is just a simple template that covers this one scenario, and is certainly much less ambitious than T4MVC. Generally, I think that there just aren’t as many areas in WebForms that can benefit from code generation compared to MVC, but at least this is one!
Let me know if you find this useful, or if you can think of other areas where a T4 template could benefit WebForms applications.