Thursday, October 30, 2014

Custom Server Controls That Wrap Content

So when building a custom server control, most Google results will tell you to use a Template Control to handle wrapping your control around content. This results in markup that looks like this:

<uc:MyControl runat="server">
    <Content>
        <asp:TextBox runat="server"/>
    </Content>
</uc:MyControl>

This is annoying, since you have to specifically add a <content> section every time you'd use the wrapping control.

The solution is actually rather simple:

public override void RenderControl(HtmlTextWriter writer)
{
    // top of your wrapping code here

    foreach (Control i in Controls)
        i.RenderControl(writer);

    // bottom of your wrapping code here
}

This lets you wrap whatever code you need around whatever controls are nested inside your markup start/end tags.

Tuesday, October 7, 2014

Your Code: If you can't be an example, be a warning

I was just talking with a friend about some re-work he was having to do, and he was very frustrated by the "wasted time" he created as a result of the original work.

I told him to look at it from the Tomas Edison viewpoint: now you know what not to do, and that is just as important!

The next time you have to go blow away some code and rewrite it because of some error or mistake you got yourself into, take a good hard look at the existing code before you get rid of it. Try to figure out the anti-pattern that caused the problem, and remember it! Write it down, create a mnemonic for it, whatever you have to do!

Your goal is to implant some small seed of that anti-pattern in your brain, so that the next time you're coding along, that little corner of your brain will tickle and you'll realize you're building an anti-pattern, and fix it before it's a problem.

So many programmers talk about Design Patterns and Best Practices, but we don't bother to study anti-patterns and bad practices to understand them and question ourselves and our code to improve even the smallest and most common boilerplate code.

Interview question: Tell me about an anti-pattern you used, how you identified it, and how you fixed it?