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:
- You get intellisense while typing the constant, helping you make sure you get it right.
- If you ever move, rename or delete the user control, you will get a compile time error instead of a runtime error, hence catching the issue much earlier.
Some limitations you should be aware of:
- It only supports Web Applications, not Web Sites. This is because T4 templates don’t get processed in Web Sites (at least I couldn’t get them to, maybe there is a way).
- You need to save the .tt file for the generation to occur. So whenever you add or rename aspx/ascx file that you’d like to point to using the generated constant, you should save it. In T4MVC, I implemented a workaround that causes the template to run whenever you build, and we could do this for AspPathGuru as well, but I wanted to keep it nice and simple to stat with.
- It’s probably obvious, but the generated constants are only usable is places where you can write code, like the LoadControl call above. So don’t try to use it as the ‘src’ in a <%@ Register %> directive; it will not work!
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.