Tatham Oddie

Enter the Tatrix

Archive for the ‘ASP.NET’ Category

Web Forms Model-View-Presenter on Hanselminutes

with 2 comments

Over the last few months Damian Edwards and myself have been spending quite a bit of time building out a Model-View-Presenter framework for ASP.NET Web Forms.

Until now we’ve been pretty quiet about it all on our blogs because we were busy polishing off v1 and trying to get all the documentation in order. Nevertheless, the word has definitely started to spread as Scott Hanselman interviewed me about the library on this week’s Hanselminutes episode.

Listen to the podcast

Learn more about the library

Written by Tatham Oddie

February 21, 2010 at 20:43

Video: Building Fast, Public Websites

with one comment

Following up from my last post about the ASP.NET MVC vs ASP.NET WebForms debate, we’ve had a second TechTalk posted, also from TechEd Australia. In this video, Michael Kordahi, Damian Edwards and I sat down to discuss building fast, public websites. It was a bit of a teaser for our breakout session at the conference, which will be available online as a screencast in the next week or two.

If you’re interested in learning more about building large public websites on ASP.NET, remember that the full video from our recent REMIX session is still available online too.

Building Fast, Public Websites

Watch Online or Download

Written by Tatham Oddie

September 14, 2009 at 21:04

Video: ASP.NET MVC vs ASP.NET WebForms – Will WebForms be replaced by MVC?

with 2 comments

At the recent TechEd Australia conference, Paul Glavich, Damian Edwards and myself sat down to discuss what we thought about the current MVC vs WebForms debate. Our TechTalk has now been posted on the TechEd Online site, and available for anyone to watch.

Check it out, and feel free to continue the debate with any of us. :)

ASP.NET MVC vs ASP.NET WebForms – Will WebForms be replaced by MVC? 

Watch Online or Download

Written by Tatham Oddie

September 14, 2009 at 20:52

Accessing ASP.NET Page Controls During PreInit

with 5 comments

If you’ve read my previous post explaining a common pitfall with view state, I’d hope you’re preparing all your controls in the Init event of the page/control lifecycle.

Even if I’m not reusing them through my application much, I like to factor elements like a drop down list of countries into their own control. This centralizes their logic and allows us to write clear, succinct markup like this:

<tat:CountriesDropDownList ID="AddressCountry" runat="server" />

The code for a control like this is quite simple:

[ToolboxData("<{0}:CountriesDropDownList runat=\"server\" />")]
public class CountriesDropDownList : DropDownList
{
    protected override void OnInit(EventArgs e)
    {
        DataSource = Countries;
        DataBind();

        base.OnInit(e);
    }
}

The Problem

Once you start using this encapsulation technique, it won’t be long until you want to pass in a parameter that affects the data you load. Before we do, we need to be aware that the Init event is fired in reverse order. That is, the child controls have their Init event fired before that event is fired at the parent. As such, the Page.Init event is too late for us to set any properties on the controls.

The natural solution is to try and use the Page.PreInit event, however when you do you’ll often find that your control references are all null. This happens when your page is implemented using a master page, and it relates to how master pages are implemented. The <asp:ContentPlaceHolder /> controls in a master page use the ITemplate interface to build their contents. This content (child controls) is not usually prepared until the Init event is called, which means the control references are not available. For us, this represents a problem.

The Solution

The fix is remarkably simple; all we need to do is touch the Master property on our Page and it will cause the controls to become available. If we are using nested master pages, we need to touch each master page in the chain.

I often create a file called PageExtensions.cs in my web project and add this code:

public static class PageExtensions
{
    /// <summary>
    /// Can be called during the Page.PreInit stage to make child controls available.
    /// Needed when a master page is applied.
    /// </summary>
    /// <remarks>
    /// This is needed to fire the getter on the top level Master property, which in turn
    /// causes the ITemplates to be instantiated for the content placeholders, which
    /// in turn makes our controls accessible so that we can make the calls below.
    /// </remarks>
    public static void PrepareChildControlsDuringPreInit(this Page page)
    {
        // Walk up the master page chain and tickle the getter on each one
        MasterPage master = page.Master;
        while (master != null) master = master.Master;
    }
}

This adds an extension method to the Page class, which then allows us to write code like the following:

protected override void OnPreInit(EventArgs e)
{
    this.PrepareChildControlsDuringPreInit();

    MyCustomDropDown.MyProperty = "my value";

    base.OnPreInit(e);
}

Without the call to the extension method, we would have received a NullReferenceException when trying to set the property value on the MyCustomDropDown control.

You now have one less excuse for preparing your controls during the Load event. :)

Written by Tatham Oddie

December 20, 2008 at 06:30

How I Learned to Stop Worrying and Love the View State

with 11 comments

(If you don’t get the title reference, Wikipedia can explain. A more direct title could be: Understanding and Respecting the ASP.NET Page Lifecycle.)

Page lifecycle in ASP.NET is a finicky and rarely understood beast. Unfortunately, it’s something that we all need to get a handle on.

A common mishap that I see is code like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        AddressCountryDropDown.DataSource = CountriesList;
        AddressCountryDropDown.DataBind();
    }
}

The problem here is that we’re clogging our page’s view state. Think of view state as one of a page’s core arteries, then think of data like cholesterol. A little bit is all right, but too much is crippling.

To understand the problem, lets investigate the lifecycle that’s in play here:

  1. The Page.Init event is being fired, however we are not subscribed to that.
  2. Immediately after the Init event has fired, view state starts tracking. This means that any changes me make from now on will be saved down to the browser and re-uploaded on the next post back.
  3. The Page.Load event is being fired in which we are setting the contents of the drop down list. Because we are doing this after the view state has started tracking, every single entry in the drop down is being written to both the HTML and the view state.

There’s yet another problem here as well. By the time the Page.Load event is fired, all of the post back data has been loaded and processed.

To investigate the second problem, let’s investigate the lifecycle that’s in play during a post back of this same page:

  1. The user triggers the post back from their browser and all of the post back data and view state is uploaded to the server.
  2. The Page.Init event is fired, however we are not subscribed to that.
  3. Immediately after the Init event has fired, view state starts tracking. This means that any changes me make from now on will be saved down to the browser and re-uploaded on the next post back.
  4. The view state data is loaded for all controls. For our drop down list example, this means the Items collection is refilled using the view state that was uploaded from the browser.
  5. Post back data is processed. In our example, this means the selected item is set on the drop down list.
  6. The Page.Load event is fired however nothing happens because the developer is checking the Page.IsPostBack property. Usually, they say this is a “performance improvement” however it is also required in this scenario otherwise we would lose the selected item when we rebound the list.
  7. The contents of the drop down list are once again written to both the HTML and the view state.

How do we do this better? Removing the IsPostBack check and placing the binding code into the Init event is all we need to do:

protected override void OnInit(EventArgs e)
{
    AddressCountryDropDown.DataSource = CountriesList;
    AddressCountryDropDown.DataBind();

    base.OnInit(e);
}

What does this achieve?

  • We are filling the contents of the drop down before the Init event is fired; therefore a redundant copy of its contents is not written to the view state.
  • We are filling the contents of the drop down before the postback data is processed, so our item selection is successfully loaded without it being overridden later.
  • We have significantly reduced the size of the page’s view state.

This simple change is something that all ASP.NET developers need to be aware of. Unfortunately so many developers jumped in and wrote their first ASP.NET page using the Page_Load event (including myself). I think this is largely because it’s the one and only event handler presented to us when we create a new ASPX page in Visual Studio. While this makes the platform appear to work straight away, it produces appalling results.

Written by Tatham Oddie

December 18, 2008 at 19:07

Video: DG.TV at Web on the Piste

without comments

Written by Tatham Oddie

August 26, 2008 at 13:35

Video: The best web stack in the world

with 2 comments

This is the demo I made for the Microsoft Demos Happen Here competition. The criteria was that it had to be under 10 minutes, and show one or more of the features from the launch wave technologies – Visual Studio 2008, SQL Server 2008 and Windows Server 2008.
I chose to demonstrate PHP running on IIS7 using FastCGI, then integrating this with an ASP.NET application before finally load balancing the whole application between two servers in a high availability, automatic failover cluster.
I managed to do all that with 2 minutes to spare, so I think it’s pretty clear that Windows Server 2008 is the best web stack in the world.

http://vimeo.com/1439786

Update 5-Sep-08: I won. :)  

Written by Tatham Oddie

July 31, 2008 at 12:50

Tearing down the tents (and moving them closer together)

with 2 comments

Being fairly focused on Microsoft technologies myself, I see a lot of the “us vs. them” mentality where you either use Microsoft technologies, or you’re part of “the other group”. Seeing Lachlan Hardy at Microsoft Remix was awesome – he was a Java dude talking about web standards at a Microsoft event. The more we can focus on the ideas rather than which camp you’re from, the more we’ll develop the inter-camp relationships and eventually destroy this segmentation. Sure, we’ll still group up and debate the superfluous crap like which language is better (we’re nerds – we’ll always do that) but at least these will be debates between the sub-camps of one big happy web family. (It’s not as cheesy as it sounds – I hope.)

What’s the first step in making this happen? Meet people from “the other group”!

The boys and girls at Gruden and Straker Interactive have put together Web on the Piste for the second year running. It’s a vendor neutral conference about rich internet technologies – so you’ll see presentations about Adobe Flex and Microsoft Silverlight at the same event (among lots of other cool technologies of course). These types of events are a perfect way to meet some really interesting people and cross pollinate some sweet ideas.

It’s coming up at the end of August, and I understand that both conference tickets and accommodation are getting tight so I’d encourage you to get in soon if you’re interested (Queenstown is crazy at this time of year).

And of course, yours truly will be there evangelising the delights of Windows Live as well as ASP.NET AJAX to our Flash using, “fush and chups” eating friends. :)

Will you be there?

Written by Tatham Oddie

July 29, 2008 at 13:13

Video: ASP.NET MVC Preview 3

with one comment

Last night I gave an introduction to MVC at the Wollongong .NET User Group. We had a bit of time at the end, so I also covered off Inversion of Control (IoC) and how it can be used with the MVC framework.

The talk assumed a working knowledge of ASP.NET, but required no existing knowledge about ASP.NET MVC or IoC.

You can watch it on Vimeo:

Tip: Watching on the actual Vimeo site instead of this embedded player will give you a bigger and clearer video.

Or download it as a WMV:

http://tatham.oddie.com.au/presentations/20080709-WDNUG-AspNetMvcPreview3-TathamOddie.wmv (64MB, 68min)

Written by Tatham Oddie

July 10, 2008 at 11:52

Video: Architectural Considerations for the ASP.NET MVC framework

with one comment

Update (16th July 2008): There’s a better version of this presentation available at http://blog.tatham.oddie.com.au/2008/07/10/video-aspnet-mvc-preview-3/

This talk doesn’t actually assume any prior knowledge of the ASP.NET MVC Framework, so it goes through the whole intro at the start (albeit quickly). I then delve into some IoC concepts, and finally mash it all together. The IoC framework used is Castle Windsor.

This was recorded at the VIC.NET usergroup in Melbourne, Australia on 10th June 2008.

You can grab the Windows Media file directly from:

http://tatham.oddie.com.au/presentations/20080610-VICNETMelbourne-ArchitecturalConsiderationsForAspNetMvc-TathamOddie.wmv (48MB, 47min)

Or stream it from Google Video:

Written by Tatham Oddie

June 20, 2008 at 09:39