Archive for the ‘CodeDom’ Category

Debugging ASP.NET generated code

This post applies to any ASP.NET app that uses .aspx files, whether WebForms or MVC.

When you write an aspx/ascx/master file (I’ll just say aspx for here on, but it applies to all), it gets compiled dynamically by the ASP.NET runtime.  Note that this is true whether you use a Web Site or a Web Application Project (WAP).  While in a WAP, most of the code is built by Visual Studio, the aspx pages themselves are always built dynamically.

Normally, when you work with aspx files, you only need to worry about what you write in there, and the specifics of what ASP.NET generates under the cover are somewhat of an implementation details.  However, in some cases it’s pretty useful to look at the generated code, either to learn exactly what it does, or to make sense of tricky issues.

Note: one case where it’s particularly useful is if you’re implementing ProcessGeneratedCode in a ControlBuilder to generate custom code.  In that case, you really need to debug into the generated code if anything goes wrong.

For illustration, let’s take a really simple example page, and go through both how we can view the generated code, and then actually debug it.

Here is our lame little test page:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e) {
        Label1.Text = Server.HtmlEncode(TextBox1.Text);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text="Label" />
    </div>
    </form>
</body>
</html>

So you click on the button, and it puts the textbox’s text into the label.  I know, exciting stuff!  Now run the page and enjoy its rich feature set, then read on…

 

Looking at the generated code

Before we get into how to debug the generated code, let’s first discuss how we can simply look at it.  First, it’s a good idea to turn on the debug flag and turn off the batch flag when debugging issue.  This is done in web.config:

<compilation debug="true" batch="false">

Once you have that, there is a simple well known trick to see the generated code: deliberately add a compile error to the code.  e.g. change void to void2, or something like that.  Then when you run the page, you’ll get the familiar ASP.NET yellow error screen.  Near the bottom, you should see:

image

The first link can be useful on occasions to see what was passed to the compiler, but the real gold is in the second link, which displays the full generated code for the page.

e.g. here is an extract from it:

Line 293:          [System.Diagnostics.DebuggerNonUserCodeAttribute()]
Line 294:          private global::System.Web.UI.HtmlControls.HtmlForm @__BuildControlform1() {
Line 295:              global::System.Web.UI.HtmlControls.HtmlForm @__ctrl;
Line 296:
Line 297:              #line 17 "d:\tmp\WebSiteDebugGeneratedCode\Page.aspx"
Line 298:              @__ctrl = new global::System.Web.UI.HtmlControls.HtmlForm();
Line 299:
Line 300:              #line default
Line 301:              #line hidden
Line 302:              this.form1 = @__ctrl;
Line 303:
Line 304:              #line 17 "d:\tmp\WebSiteDebugGeneratedCode\Page.aspx"
Line 305:              @__ctrl.ID = "form1";
Line 306:
Line 307:              #line default
Line 308:              #line hidden
Line 309:              System.Web.UI.IParserAccessor @__parser = ((System.Web.UI.IParserAccessor)(@__ctrl));
Line 310:
Line 311:              #line 17 "d:\tmp\WebSiteDebugGeneratedCode\Page.aspx"
Line 312:              @__parser.AddParsedSubObject(new System.Web.UI.LiteralControl("\r\n    <div>\r\n        "));
Line 313:
Line 314:              #line default
Line 315:              #line hidden
Line 316:              global::System.Web.UI.WebControls.TextBox @__ctrl1;
Line 317:
Line 318:              #line 17 "d:\tmp\WebSiteDebugGeneratedCode\Page.aspx"
Line 319:              @__ctrl1 = this.@__BuildControlTextBox1();
Line 320:
Line 321:              #line default
Line 322:              #line hidden
Line 323:
Line 324:              #line 17 "d:\tmp\WebSiteDebugGeneratedCode\Page.aspx"
Line 325:              @__parser.AddParsedSubObject(@__ctrl1);
Line 326:
Line 327:              #line default
Line 328:              #line hidden

It looks quite ugly and overly wordy, but it’s fairly easy to see what it does:

  • Creates the HtmlForm
  • Set its ID
  • Add a literal control with the start <div> tag to it (since <div> is not a server control here)
  • Create the TextBox and add it to the HtmlForm

If you try this on more complex pages that use fancier features link Bind() (aka two-way data binding), you can really get a good understanding of how those features work.

 

Debugging the generated code

So looking at the code is nice, but now we really want to actually debug this code.  This requires a few tricks, but is not too difficult.

First, let’s talk a little bit about the concept of line pragmas.  In the generated code above, you see all those lines that start with #line, e.g.

Line 318:              #line 17 "d:\tmp\WebSiteDebugGeneratedCode\Page.aspx"
Line 319:              @__ctrl1 = this.@__BuildControlTextBox1();

What this does is tell the compiler that the code following the #line pragma should be treated as if it were at line 17 of your aspx, rather that in the generated code.  This is very useful, as it allows compiler errors to point to your aspx file, which is what in most cases makes sense.  It also allows you to debug into the aspx page.

But although that’s very useful stuff, in this case it’s exactly what we don’t want, since our goal is to debug straight into the generated code!

The answer is simple: get rid of the line pragmas!  Luckily, there is a little known yet very simple directive that will do just that: LinePragmas="false".  So add that to your page:

<%@ Page Language="C#" LinePragmas="false" %>

Now run your page again.  Note that at this time, we still have the little syntax error that we introduced earlier (e.g. void2).  So you’ll get an error, but it won’t look quite the same.  First, it’ll say that the error is in the generated file, not the aspx file.  e.g. you’ll get something like this:

Source File: c:\Users\davidebb\AppData\Local\Temp\Temporary ASP.NET Files\websitedebuggeneratedcode\165e8896\2804a211\App_Web_page.aspx.cdcab7d2.qmy8q0k7.0.cs    Line: 46 

And then, if you expand the “Show Complete Compilation Source” link, you’ll see that the code no longer has line pragmas.  e.g. the code we looked at above now looks like this:

Line 121:          private global::System.Web.UI.HtmlControls.HtmlForm @__BuildControlform1() {
Line 122:              global::System.Web.UI.HtmlControls.HtmlForm @__ctrl;
Line 123:              @__ctrl = new global::System.Web.UI.HtmlControls.HtmlForm();
Line 124:              this.form1 = @__ctrl;
Line 125:              @__ctrl.ID = "form1";
Line 126:              System.Web.UI.IParserAccessor @__parser = ((System.Web.UI.IParserAccessor)(@__ctrl));
Line 127:              @__parser.AddParsedSubObject(new System.Web.UI.LiteralControl("\r\n    <div>\r\n        "));
Line 128:              global::System.Web.UI.WebControls.TextBox @__ctrl1;
Line 129:              @__ctrl1 = this.@__BuildControlTextBox1();
Line 130:              @__parser.AddParsedSubObject(@__ctrl1);

So same code, minus all the #line pragma.

Now let’s get back to our original goal of debugging our page’s generated code!  I’ll give you two different techniques to do this.

 

Technique #1: find the generated folder and open the file from there

Take the following steps.  It looks a little tricky, but nothing you can’t handle!

  1. Start by making sure you have LinePragmas="false" as discussed above.
  2. Copy the generated file’s folder path from above (in my case c:\Users\davidebb\AppData\Local\Temp\Temporary ASP.NET Files\websitedebuggeneratedcode\165e8896\2804a211), and open it in the windows shell.
  3. Remove the compile error we had put in earlier (e.g. void2)
  4. Run your page again.  This causes it to be recompiled, and it will execute normally.
  5. Now, look back a the generated file’s folder, and sort the files by Date Modified.
  6. The newest file should be named something like App_Web_page.aspx.cdcab7d2.q_hetksf.0.cs.  Drag it into VS to open it.
  7. Set a break point in there.  e.g. in the __BuildControlform1() we looked at.
  8. Hit F5 to debug your app, and it should hit your breakpoint!

You can now step through the code as if you wrote it!  Which you kind of did, indirectly :)

 

Technique #2: use a first chance exception to directly open the file for you.

You may either find this harder or easier, depending on your sign.

 

Start by making sure you have LinePragmas="false" as discussed above.  Now, remove our little compile error above (e.g. void2), and add a Page_Init method in your page that throws and catches an exception.  e.g.

void Page_Init() {
    try { throw new Exception("I'm a break point!"); }
    catch { }
}

Set the debugger to break on all first chance exception: Ctrl-Alt-E, and check Thrown for CLR Exceptions:

image

Now debug your page, and boom, it should hit your pseudo-break point, which has the great benefit of opening the generated file in the debugger!  Now you can set break point is other places, and go you’re all set.  Note that you’ll need to send a 2nd request to the page to debug methods like __BuildControlform1(), since they execute way before Page_Init.

Take your MVC User Controls to the next level

Note: this is based on ASP.NET MVC 2 RC, and will not work on earlier builds.

 

The quick pitch: make your User Controls as cool as built-in render helpers!

The goal of this post is to show you how to change the way MVC user controls are called from something like this:

<%= Html.Partial("~/Views/Shared/gravatar.ascx", new { Email = "foo@bar.com", Size = 80 }) %>

To something that looks just like a built-in render helper (like Html.TextBox(…)):

<%= Html.Gravatar("foo@bar.com", 80) %> 

 

The current model for User Controls in MVC

If you have used ASP.NET MVC, you probably know that you can use User Controls (.ascx files) to provide partial rendering.

For example, the default MVC app has a Site.Master and a LogOnUserControl.ascx under Views/Shared, and the Site.Master contains:

<div id="logindisplay">
    <% Html.RenderPartial("LogOnUserControl"); %>
</div>

As a slightly nicer alternative, you can change the RenderPartial call to:

<%= Html.Partial("LogOnUserControl") %>

 

What’s wrong with this pattern

While this pattern certainly works, there are some issues with it.  Let’s look at a few:

Hard coded paths with no intellisense

The first is that you need to refer to them by their path.  In the example above, the UC is in the same folder as the master, so you can use a relative path, but in the general case, you would have to refer to it as “~/Views/Shared/LogOnUserControl.ascx”, which gets ugly.  If you use T4MVC (plugging my other baby if you don’t mind!), it’ll get rid of the literal string and give you intellisense, but in essence it still works the same way: the View engine gets a literal string and tries to go from there.

Inconsistent with HTML render helpers

Another issue is that even though the UC is basically an HTML render helper, it doesn’t look like one when you call it.  Ideally, you really want to call it the same way you call ‘built in’ helpers.  e.g. since you can call Html.TextBox(), you should be able to call Html.LogOnUserControl().  In comparison, the RenderPartial call looks painfully complex.

Difficult to pass parameters

Suppose your UC needs to receive parameters from the caller.  With Partial/RenderPartial, you have to pass those through a model object, which is painful.  You can either rely on untyped data, or create a custom ViewModel type to encapsulate the data you need.  In either case, it looks nothing like a call to a render helper like Html.TextBox(…), which takes ‘natural’ parameters.

 

How we can make this better

The tools at our disposal

There are many little known gems in ASP.NET that allow us to put together a very nice solution that solves all those issues.

The first little known fact is that Web Applications can have an App_Code folder, where all its files get compiled into a single assembly that all pages reference.  Of course, the App_Code folder is very well known in Web Sites, but the fact that they can also be used in Web Application Projects (WAPs) is often overlooked.

The second little known gem is that user controls can go in App_Code!  Come on, admit it, you didn’t know that.  No one knows that! :)

The third one is that you can associate a control builder for an entire User Control (or page), and not just for controls within the page.

And finally, the fourth gem is the ControlBuilder.ProcessGeneratedCode method, which I blogged about a while back.  This method lets us modify the code generated for the User Control (or page), which opens up some very powerful possibilities.

What the end result looks like

Instead of giving you all the technical details here (the full sample is attached), let’s look at what the end result looks like.  In order to use it, you just need to add a reference to the MvcUserControlHtmlHelpers assembly in the sample (I know, lame name).

Then you can just move your User Control into App_Code, and make a small change to it.  e.g. in the example above, you would change the directive from

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

to

<%@ Control Language="C#" Inherits="MvcUserControlHtmlHelpers.UserControlHtmlHelper" ClassName="LogOnUserControl" %>

So basically you change the base type and give it a specific class name.

One you have that, the real fun begins, as you can change Site.master to just have

<div id="logindisplay">
    <%= Html.LogOnUserControl() %>
</div> 

You now have full intellisense, and the call looks just like a built-in helper.  Yeah!

 

So what about parameters?

Suppose you want to write a User Control that displays Gravatars.  You’d put in in App_Code, and write something like this:

<%@ Control Language="C#" Inherits="MvcUserControlHtmlHelpers.UserControlHtmlHelper" ClassName="Gravatar" %>

<script runat="server">
    // Declare the paramaters that we need the caller the pass to us
    public string Email;
    public int Size;
</script>

<%
    // Build hash of the email address
    // Note: in spite of its name, this API is really just a general MD5 encoder
    string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(Email.ToLower(), "MD5").ToLower();

    // Construct Gravatar URL
    string imageURL = String.Format("http://www.gravatar.com/avatar/{0}.jpg?s={1}&d=wavatar", hash, Size);
%>

<img src="<%= imageURL %>" alt="<%= Email %>" title="<%= Email %>" />

The key new concept here is that you declare the parameters that you want as public fields, and you just use them in your code.  Basically, think of this as declaring a method, but without a real method declaration.

And once you have that, things get really nice in your view, where you can now write

<%= Html.Gravatar("foo@bar.com", 80) %>

or if you prefer, you can write

<% Html.RenderGravatar("foo@bar.com", 80); %>

With the same distinction as between Partial() and RednerPartial().  Now for the fun, try hitting F12 (Go To Definition) on one of those methods.  You’ll get:

public static class GravatarExtensions {
    public static string Gravatar(this HtmlHelper htmlHelper, string Email, int Size);
    public static void RenderGravatar(this HtmlHelper htmlHelper, string Email, int Size);
}

What happened in that the special base generated some extension methods to allow you to call the User Control exactly as you would call a ‘built-in’ helper like Html.TextBox.

 

How does it all work

To pull this magic, it uses a combination of the various things I outlined above.  I won’t go into the details since the full source is attached and has enough comments to make it clear what it’s doing.  The file you want to look at is UserControlHtmlHelper.cs.  I warn you, I had to use a scary trick to get around a CodeDom limitation.  Also, there are some edge cases that don’t work yet but could be made to work.  At this point, this is just a sample!

Enjoy, and let me know what you think about this pattern.