Recently I started working at ZYB and haven’t seen all the code yet. Then the other day I fell over a special section in our web.config called tagMapping. I’ve never heard about it before so I asked around and did a little detective work. Basically, it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox instances in the entire website into another control.

That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

[code:c#]

public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
  public override string Text
  {
    get
    {
      return base.Text;
    }
    set
    {
      base.Text = System.Web.HttpUtility.HtmlEncode(value);
    }
  }
}

[/code]

Then I needed to hook the tag mapping up in the web.config to convert all the text boxes into SafeTextBox instances. It simply converts all TextBox instances on the entire site. Here is what’s needed in the web.config:

[code:xml]

<pages>
  <tagMapping>
    <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="SafeTextBox"/>
  </tagMapping>
</pages>

[/code]

That is one smart way of applying your own server control substitute classes on a site wide basis. I'm still a little frustrated by the fact that I didn't know about this before very recently.

Comments


Comments are closed