‘Twas a cold autumn night …

It was the day after April Fools, and I awoke in the morning eager to iron my shirt and get to work.

I was however distracted by the email waiting on my screen.

From: support@mvpaward.com [mailto:support@mvpaward.com]
Sent: Wednesday, 2 April 2008 1:26 AM
To: tatham@oddie.com.au
Subject: [MVP] Congratulations! You have received the Microsoft MVP Award

Dear Tatham Oddie,

Congratulations! We are pleased to present you with the 2008 Microsoft® MVP Award! The MVP Award is our way to say thank you for promoting the spirit of community and improving people’s lives and the industry’s success every day. We appreciate your extraordinary efforts in Windows Live Platform technical communities during the past year. Microsoft will soon send your MVP Award gift package. It is our way to say “thank you for making a difference.” You will receive an e-mail message in the next 10 business days that contains your MVP Award gift package shipping information and your tracking number.

On behalf of everyone at Microsoft, thank you for your contributions to technical communities.

Sincerely,

Roseanne Stamell, your MVP Lead

Yay. 🙂

Thanks to all the guys in Microsoft DPE who’ve continued to support me over the years. Frank, Coatesy, Fin, Kordahi and their peers. 🙂

The move to Readify

As you may have gathered from my last two posts, I’ve now joined the world of Readify. As of last Monday, I am a Senior Consultant with the organisation.

I’ll be working with them 80% of my time (41 weeks out of 52), and using the remaining time to work on my startups like www.tixi.com.au (also only a fortnight old).

I’m looking forward to my time at Readify as an opportunity to get some more corporate experience under my belt, and get access to larger projects that I wouldn’t have been able to before as an independent. It’ll also give me some more opportunities to present and engage with the community, as well as being part of a great group of consultants who I can call on for help at 3am. 🙂

ReadiMIX Slides, Code and Links – ASP.NET MVC Preview 2

Here are my slides and code from this morning’s RDN session where I presented on ASP.NET MVC Preview 2 that was released last week:

http://tatham.oddie.com.au/files/20080310-RDN-ReadiMIX-ASP.NET-MVC-Preview-2.zip

The ZIP is most useful for people who actually saw the presentation, but if you’re game jump in and download it anyway.

And some link love:

Download ASP.NET MVC Preview 2

Official ASP.NET 3.5 Extensions Documentation

Official ASP.NET MVC Forums

Because Mitch couldn’t make this morning’s session, I also covered the IE8 bits briefly:

Download Internet Explorer 8 Beta 1

Mitch’s blog post about how to implement WebSlices

Mitch’s blog post about two new IE8 activities he has created

I’ll be writing a blog post later this morning that explains WebSlices and activities for those who haven’t seen them yet as Mitch’s posts both expect you to know what they already do. 🙂 He was pretty keen about implementing them in a lot of places, very quickly!

Thanks to those who made it along to this morning’s presentation. I’ll look forward to meeting some more people at tonight’s session. For those who can’t make it, the session is also being filmed.

Any questions or ideas about ASP.NET MVC, IE8 or just in general? Email tatham@0ddie.com.au

ReadiMix: IE8 coolness and ASP.NET MVC Preview 2 **TUESDAY**

As a bit of a last minute change, I’m now going to be delivering tomorrow’s RDN (Readify Developer Network) session. These are free sessions, sponsored by Readify which we deliver every fortnight in Melbourne and Sydney. We do two sessions to make it easy for you to get along – one at 7:30am and one at 6:00pm.

Tomorrow we’ll be conducting a bit of a “ReadiMix” hot on the heels of last week’s Mix conference in Las Vegas. Even with some of our guys still on the plane home, we’ve got IE8 and ASP.NET coolness ready to demo, including live code running in real applications already. (Mitch was pretty keen!).

More details here have just been published here: http://readify.net/rdn.aspx

Session 1: ASP.NET MVC R2, presented by Tatham Oddie
What is this whole MVC thing anyway? Hot on the heels of MIX08 and last week’s release of ASP.NET MVC Preview 2, Tatham Oddie will demonstrate how to use the model-view-controller (MVC) pattern to take advantage of your favourite .NET Framework language for writing business logic in a way that is de-coupled from the views of the data. We’ll discuss the advantages to MVC on the web, the other frameworks that are available, and build an app with it – all in an hour.

Session 2 (only presented at the Sydney PM session): IE8 and Silverlight Debugging, presented by Mitch Denny
A slew of exciting new features in Internet Explorer 8 were revealed last week at MIX08, including Web Slices and Activities. Come and hear Mitch Denny show you how to implement them into your own websites and workflows. Mitch will also present a quick introduction to debugging Silverlight in .NET – not to be missed!

Get ahead of the pack with primer and in depth technical education from the nation’s technical readiness specialists.

Register now and come say hi.

Sorting TimeZoneInfo.GetSystemTimeZones() properly

The documentation for System.TimeZoneInfo.GetSystemTimeZones() states:

Returns a sorted collection of all the time zones about which information is available on the local system.

Unfortunately, while the result is technically sorted, it’s a silly sort which shows GMT, then the eastern hemisphere, then the western hemisphere. It seems to be sorted by TimeZoneInfo.DisplayName instead of TimeZoneInfo.BaseUtcOffset.

Luckily this is easily fixed (and concise too thanks to anonymous methods!).

List<TimeZoneInfo> timeZones = new List<TimeZoneInfo>(TimeZoneInfo.GetSystemTimeZones());
timeZones.Sort(delegate(TimeZoneInfo left, TimeZoneInfo right) {
    int comparison = left.BaseUtcOffset.CompareTo(right.BaseUtcOffset);
    return comparison == 0 ? string.CompareOrdinal(left.DisplayName, right.DisplayName) : comparison;
});

In the devil’s language (VB.NET) you can achieve it using some slightly different code (no anonymous methods in VB.NET):

Dim timeZones As List(Of TimeZoneInfo) = New List(Of TimeZoneInfo)(TimeZoneInfo.GetSystemTimeZones())
timeZones.Sort(New Comparison(Of TimeZoneInfo)(AddressOf CompareTimeZones))

Private Function CompareTimeZones(ByVal left As TimeZoneInfo, ByVal right As TimeZoneInfo) As Integer
    Return IIf(comparison = 0, String.CompareOrdinal(left.DisplayName, right.DisplayName), comparison)
End Function

This will result in the list being sorted in the same order that you see under “Adjust Date/Time” in Windows.

Maybe they could fix this in the next release. 🙂 To help make that happen, vote for the issue on Microsoft Connect.

Update – 5 Feb 08: Daniella asked for a VB.NET version, so I’ve updated the post with one. Because VB.NET doesn’t support anonymous methods, you need an extra function somewhere to do the comparison.

Update – 12 Feb 08: Whitney correctly pointed out that the order still wasn’t quite right for time zones that shared the same offset. We need to sort by name as well. I’ve updated the C# and VB.NET version accordingly. I changed Whitney’s version a bit to use the conditional operator so that I could avoid two return statements, as well as translating it to VB.NET. Thanks Whitney!

Update – 15 Feb 08: Added Microsoft Connect link.

Writing Good ASP.NET Server Controls

I’ve being playing around with an XHTML WYSIWYG editor called XStandard lately. Their actual product is awesome, but before I jumped in and used their supplied ASP.NET wrapper I thought I’d just take a quick look at it in Reflector. Unfortunately, like many redistributed controls, there were some issues that jumped out at me. (This post isn’t a dig at them – they just kicked off the writing idea in my head, although I’d love it if they implemented the relevant changes.)

This post is designed as a quick guide around some of these issues, and represents the generally accepted best practice approach for control development. These were just the first issues that came to mind – in another post I’ll cover rendering best practices, as well as incorporate any suggestions by you.

Survive the postback – use ViewState

After a page has finished rendering, it is mostly destroyed in memory. When a postback occurs, the ASP.NET runtime has to rebuild all of the objects in memory. If we use fields as the backing stores for our properties, these values won’t survive the postback and thus your control will be re-rendered differently.

A traditional .NET property might look like this:

private string _spellCheckerURL;

public string SpellCheckerURL
{
    get { return _spellCheckerURL; }
    set { _spellCheckerURL = value; }
}

But in ASP.NET server controls, we need to write them like this:

public string SpellCheckerUrl
{
    get { return (string)ViewState[“SpellCheckerUrl”] ?? string.Empty; }
    set { ViewState[“SpellCheckerUrl”] = value; }
}

You might notice my use of the C# coalesce operator (??). Until we store anything in the property, requesting it from view state is going to return null. Using the coalesce operator allows us to specify a default value for our property, which we might normally have specified on the field like so:

private string _spellCheckerURL = string.Empty;

Respect the ViewState (and thus the user)

The rule above (store everything in the ViewState) is nice and reliable, but it can also be a bit nasty to the end user – the person who has to suck down your behemoth chunk of encoded ViewState.

For some properties, you can safely lose them then just work them out again. Our rich text editor control gives a perfect example – we don’t need to store the text content in the ViewState because it’s going to be written into our markup and passed back on the post-back. We can (and should) be storing this data in a backing field for the first render, then obtaining it from the request for postbacks.

Build your control as the abstraction layer that it’s meant to be

ASP.NET server controls exist to provide a level of abstraction between the developer, and the actually workings of a control (the markup generated, the postback process, etc). Build your control with that in mind.

The XStandard control is a perfect example of a server control being implemented as more of a thin wrapper than an actual abstraction layer – you need to understand the underlying API to be able to use the control.

Their Mode property looks like this:

public string Mode
{
    get { return this.mode; }
    set { this.mode = value; }
}

For me as a developer, if the property accepted an enumeration I wouldn’t need to find out the possible values – I could just choose from one of the values shown in the designer or suggested by IntelliSense.

public enum EditorMode
{
    Wysiwyg,
    SourceView,
    Preview,
    ScreenReaderPreview
}

public EditorMode Mode
{
    get { return (EditorMode)(ViewState[“Mode”] ?? EditorMode.Wysiwyg); }
    set { ViewState[“Mode”] = value; }
}

This adds some complexity to our control’s rendering – the names of the enumeration items don’t match what we need to render to the page (eg. EditorMode.ScreenReaderPreview needs to be rendered as screen-reader). This is easily rectified by decorating the enumeration, as per my previous post on that topic.

You might also have noticed that the casing of SpellCheckerUrl is different between my two examples above. The .NET naming guidelines indicate that the name should be SpellCheckerUrl, however the XStandard control names the property SpellCheckerURL because that’s what the rendered property needs to be called. The control’s API surface (the properties) should be driven by .NET guidelines, not by rendered output. This comes back to the idea of the control being an abstraction layer – it should be responsible for the “translation”, not the developer using the control.

Support app-relative URLs

App-relative URLs in ASP.NET (eg. ~/Services/SpellChecker.asmx) really do make things easy. Particularly working with combinations of master pages and user controls, the relative URLs (eg. ../../Services/SpellChecker.asmx) can be very different throughout your site and absolute URLs (http://mysite.com/Services/SpellChecker.asmx) are never a good idea.

The XStandard control uses a number of web services and other resources that it needs to know the URLs for. Their properties look like this:

[Description(“Absolute URL to a Spell Checker Web Service.”)]
public string SpellCheckerURL
{
    get { return this.spellCheckerURL; }
    set { this.spellCheckerURL = value; }
}

This made their life as developers easy, but to populate the property I need to write code in my page’s code-behind like this:

editor.SpellCheckerURL = new Uri(Page.Request.Url, Page.ResolveUrl(“~/Services/SpellChecker.asmx”)).AbsoluteUri;

This renders my design-time experience useless, and splits my configuration between the .aspx file and the .aspx.cs file.

All properties that accept URLs should support app-relative URLs. It is the controls responsibility to resolve these during the render process.

Generally, the resolution would be as simple as:

Page.ResolveUrl(SpellCheckerUrl)  (returns a relative URL usable from the client page)

however if your client-side code really does needs the absolute URL, you can resolve it like this:

new Uri(Page.Request.Url, Page.ResolveUrl(SpellCheckerUrl)).AbsoluteUri

Because we’re using the powerful URI support built in to .NET, we don’t even need to worry about whether we were supplied an absolute URL, relative URL or file path … the framework just works it out for us.

Either way, it’s your responsibility as the control developer to handle the resolution.

Use the URL editor

Now that we’ve made it really easy for developers to specify URLs as page-relative, app-relative or absolute, let’s make the designer experience really sweet with this editor (notice the […] button on our property):

image

image

That’s as simple as adding two attributes to the property:

[Editor(“System.Web.UI.Design.UrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”, typeof(UITypeEditor))]
[UrlProperty]
public string SpellCheckerUrl
{
    get { return ViewState[“SpellCheckerUrl”] as string ?? string.Empty; }
    set { ViewState[“SpellCheckerUrl”] = value; }
}

Document with XML and attributes

IntelliSense reads the XML comments, but the designer reads attributes. Document your control’s API surface using both of them.This is a bit annoying, but really not that hard and well worth it. Make sure to specify the summary in XML, as well as the Category and Description attributes.

Our typical property now looks something like this:

/// <summary>
/// Gets or sets the URL of the return handler (a handler inheriting from <see cref=”PermissionResponseHandler”/>).
/// This should be a URL to a HTTPS resource to avoid a scary warning being shown to the end user.
/// </summary>
[Category(“Behavior”)]
[Description(“The URL of the return handler (a handler inheriting from PermissionRequestReturnHandler).”)]
public string ReturnUrl
{
    get { return ViewState[“ReturnUrl”] as string ?? string.Empty; }
    set { ViewState[“ReturnUrl”] = value; }
}

If you look closely, you’ll notice the documentation isn’t actually duplicated anyway … the messaging is slightly different between the XML comment and the attribute as they are used in different contexts.

Provide lots of designer hints

In the spirit of attributes, let’s add some more to really help the designer do what we want.

For properties that aren’t affected by localization, mark them as such to reduce the clutter in resource files:

[Localizable(false)]

Define the best way to serialize the data in the markup. This ensures a nice experience for developers who do most of their setup in the design, but then want to tweak things in the markup directly.

[PersistenceMode(PersistenceMode.Attribute)]

Declare your two-way binding support. If you mark a property as being bindable (which you should) then you also need to implement INotifyPropertyChanged (which you should):

[Bindable(true)]

Declare default values. Doing so means that only properties that are explicitly different will be serialized into the markup, keeping your markup clean.

[DefaultValue(“”)]

Clearly indicate properties that are read-only. Doing so will make the read-only in the designer, rather than throwing an error when the user tries to set them:

[ReadOnly(true)]

If a property isn’t relevant to the design-time experience, hide it.

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

At the class level, it’s also good to define your default property so that it can be auto-selected first in the property grid.

[DefaultProperty(“Text”)]

Don’t get creative with IDs

ASP.NET has a great system for managing client side IDs and avoiding any conflicts – use it.

Use the ClientID property, and where needed, the INamingContainer interface. Don’t create IDs yourself.

Define your tag template

Add a ToolboxData attribute to your control class so that users get valid code when they drag it on from the toolbox:

[ToolboxData(“<{0}:XhtmlEditor runat=\”server\”></{0}:XhtmlEditor>”)]

Define your tag prefix

Define a tag prefix so that your controls have a consistent appearance in markup between projects.

[assembly: TagPrefix(“FuelAdvance.Components.Web”, “fa”)]

You only need to do this once per assembly, per namespace. Your AsssemblyInfo.cs file is generally a good place to put it.

Update 6-Nov-07: Clarified some of the writing. Added another screenshot.