My Photo

Technical Architect with over 15 years experience in a wide range of technologies.

@TheCodeKing

rss feed

Programmatically setting control adapters for url rewriting & Ajax | Thursday, June 19, 2008

Introduction

Anyone who has spent time developing URL rewriters will know that these do not always play nicely with AJAX components. This is because the HtmlForm element written out by .NET uses the actual URL for post-backs, and not the page's virtual URL that you are trying to preserve. This article discusses how this can be resolved cleanly, and also shows how control adapters may be set programmatically using Reflection. This is useful for creating plug & play components such as URL rewriters in order to minimise the amount of configuration required.

Background

In order to preserve the rewritten URL on post-back (and fix AJAX components), the HtmlForm's action attribute needs to be changed to the virtual URL.

Without this fix, you may experience the following error when using Asp.Net Ajax This happens when your virtual URL is in a different directory than the real path.

Sys.WebForms.PageRequestManagerServerErrorException:
   An Unknown error occurred while processing the request on the server.

The standard approach might be to extend the HtmlForm and override its Render method so that it alters the action attribute on render. Whereas this would work, it is a poor solution. It requires that all ASPX pages are edited in order to apply the fix. It also requires prior knowledge of the issue when other developers start creating pages, and it makes the URL rewriter component less pluggable.

A better solution would be to use a control adapter. This can be added via configuration settings in order to change the rendered HTML of all HtmlForm elements within an application. This would then not only apply the fix to all existing pages, but also to any future pages.

For anyone new to control adapters, these are discreet classes extended from the ControlAdapter class. These can be mapped to specific .NET controls via config settings located in the App_Browsers special directory. The adapters are invoked by the framework at runtime, and can alter the rendered HTML of any .NET control. A common use is to make the standard .NET controls more CSS friendly.

OK, so sounds like a good solution? Not yet! Imagine we are developing a component to be used by a third party that requires a control adapter. After they have plugged in our component, how do we ensure they add the control adapter to the solution? The standard approach is to provide heaps of documentation, and if it breaks... well... it's user error.

A smarter solution is to set the control adapter programmatically from within our component. In this way, the component is self-contained. It will be attached, when required, automatically, wherever and whenever our component is used. The bad news is, this ability isn't supported in the current framework. The good news is, it can be done, and here's how.

Solution

Firstly, we need a control adapter to correct the action attribute of the HtmlForm element. Here's one I made earlier.

public class HtmlFormAdapter : ControlAdapter
{
  protected override void Render(HtmlTextWriter writer)
  {
    base.Render(new HtmlFormWriter(writer));
  }
  private class HtmlFormWriter : HtmlTextWriter
  {
    public HtmlFormWriter(HtmlTextWriter writer)
      : base(writer)
    {
      this.InnerWriter = writer.InnerWriter;
    }
    public HtmlFormWriter(TextWriter writer)
      : base(writer)
    {
      this.InnerWriter = writer;
    }
    public override void WriteAttribute(string key, string value, bool fEncode)
    {
      if (string.Compare(key, "action")==0)
      {
        value = HttpContext.Current.Request.RawUrl;
      }
      base.WriteAttribute(key, value, fEncode);
    }
  }
}

The next step is to set the control adapter programmatically. In order to do this, we use Reflection to access the hidden private _adapter property of the HtmlForm control and set this to an instance of our adapter. In this example, we assume we are running from within a HttpModule that is doing the URL rewriting, and hook the PreRequestHandlerExecute event. We can then hook the page's PreRender event in order to grab the HtmlForm control and attach the adapter.

private void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
 HttpApplication application = (HttpApplication)sender;
 HttpContext context = application.Context;
 if (context.Handler is Page)
 {
    Page page = (Page)context.Handler;
    page.PreRender += new EventHandler(RegisterControlAdapters);
 }
}

private void RegisterControlAdapters(object sender, EventArgs e)
{
 Page page = (Page)sender;
 page.PreRender -= new EventHandler(RegisterControlAdapters);
 if (page.Form != null)
 {
    // attach new instance of control adapter
    FieldInfo adapterFieldInfo = page.Form.GetType().GetField("_adapter",
                                 BindingFlags.NonPublic | BindingFlags.Instance);
    if (adapterFieldInfo != null)
    {
        HtmlFormAdapter adapter = new HtmlFormAdapter();
        FieldInfo controlFieldInfo = adapter.GetType().GetField("_control",
                                     BindingFlags.NonPublic | BindingFlags.Instance);
        if (controlFieldInfo != null)
        {
             controlFieldInfo.SetValue(adapter, page.Form);
             adapterFieldInfo.SetValue(page.Form, adapter);
        }
    }
 }
}

Summary

This is a pretty specific example; however, the point is that using this technique greatly aids the creation of smart components that require minimal configuration. It also provides a greater degree of power to component developers, who are then able to hook into the actual rendering of all the controls in an application from a single line in the web.config.

<add name="RewriteModule" type="CodeKing.Web.UrlRewriter, CodeKing.Web"/>

This leads to more pluggable components and fewer problems when it comes to development cycles or swapping out of components.

Further Reading

History

  • 19th June 2008: First published
  • 23rd June 2008: Further Reading section updated
  • 24rd June 2008: Updated demo to use HtmlTextWriter

No comments:

Post a Comment