Okay it’s about time we had a code-related post.
So what’s the solution? The Dojo Toolkit (very nice stuff except I can’t get about 50% of it working in Firefox and the latest version seems to break IE too) uses sub-directories to hold different language resources. That’s quite a nice way to do it, but I wanted to make use of .NET 2K5’s built in stuff so I did it like this.
First, I have a file called ClientMessages.aspx with the following Page directive:
<%@ Page Language="C#" EnableSessionState="False" AutoEventWireup="true" CodeFile="ClientMessages.aspx.cs" Inherits="ClientMessages" Culture="auto" UICulture="auto" %>
That automatically tells .NET to pick up the user’s language and find the correct resource file. The rest of the page looks something like this:
Message1:"<asp:literal runat="server" meta:resourcekey="Message1" />",
Message2:"<asp:literal runat="server" meta:resourcekey="Message2" />",
Message3:"<asp:literal runat="server" meta:resourcekey="Message3" />",
… etc …
MessageN:"<asp:literal runat="server" meta:resourcekey="MessageN" />"
You’ll get the correctly localised version, assuming you have defined as resource file for the chosen culture, otherwise you get the fallback file – exactly as happens with the rest of .NET.
It’s also worth adding something like the following to the page to make sure it gets reloaded if the user changes languages:
<%@ OutputCache VaryByHeader="HTTP_ACCEPT_LANGUAGE" Location="ServerAndClient" VaryByParam="none" Duration="3600" %>
And that’s all there is to it!
I’m getting myself into the habit of writing localisable code now – even when I know full well English is going to be the only language I use. Reason? Well it means you can add new languages fairly painfully if you ever do need to. If a customer comes to you and says "If we give you the translations, could you make your application appear in French for our Paris office?" A reply of "Probably not, but if we could it’d cost you an arm and a leg and everything would need retesting" is not going to go down well, but a reply of "No problem. Couple of days once we get the new text" will. Even better, asking in advance if there are any translation needs is going to make you flavour of the month.
Coding for localisation doesn’t add very much time to your development once you get used to it, and it might just reap benefits later on.