Globalization
Setting the culture
- CurrentCulture is date/numbers (ddmmyy or mmddyy; 1.5 or 1,5)
- CurrentUICulture is for looking up resources
On all string/number/date operations use the optional formatting argument (FXCop will complain if you don't). Either System.Globalization.CultureInfo.CurrentCulture or .InvariantCulture (if applicable).
See Intro (Rick Strahl); see also serverside.net and ondotnet.com
For the web, the HTTP header contains user languages (set within IE-Tools-Internet Options-Languages) which you can read in Request.UserLanguages[0] (for the first one). ASP 1: Read it (or a cookie from a user form) in Global.asax Session_Start. In ASP 2 it's automatic.
Resource Files
Use assembly linker for satellite assemblies: al /t:lib /culture:en-UK /embed:strings.en-UK.resources /out:myapp.resources.dll
.Net 1
To load localised strings, the easiest way is a static/shared ResourceManager, passing the current class type:
//C# static ResourceManager rm = new ResourceManager(typeof(ThisClass)); 'VB Shared rm As ResourceManager = New ResourceManager(GetType(ThisClass))
Or pass in the assembly - System.Reflection.Assembly.GetExecutingAssembly() - or even an external assembly
Dim a As Assembly = Assembly.Load("qq")
Dim rm As ResourceManager = New ResourceManager("qq", a)
return rm.GetString("key")
.Net 2
App_GlobalResources (Resources namespace, with intellisense) or App_LocalResources (page specific) .No more ResourceManager!
- App_GlobalResources folder (normally just one .resx). Each directory has App_LocalResources with .resx for for each page (key is page name with extension- default.aspx- not the class name).
- In asp markup: implicit (Tools-Localize -adds meta:resourcekey to controls) vs explicit (<asp:Label ID="lab" runat="server" Text='<%$ Resources:lab %>' / > (globals have $Resources:classname, id format)
- In code: string txt = [HttpContext.]GetGlobalResourceObject("GlobalResources","MyText") as string
or (strong typed but less efficient) string txt = GlobalResources.resources.MyText
or (local) string txt = [HttpContext.]GetLocalResourceObject(["~/Default.aspx",]"localText") as string; - Use asp:Localize (like asp:Literal with a meta:resourcekey)
- Web.config globalization (and Page) culture="auto" uiCulture="auto".
Override Page.InitializeCulture event (to read from cookie/db setting)protected override void InitializeCulture() { if (Request.Form["ListBox1"] != null) //controls not available { String selectedLanguage = Request.Form["ListBox1"]; //set the page properties UICulture = selectedLanguage ; Culture = selectedLanguage ; //set the thread using CultureInfo - needs 2 different ways :( Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage); Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage); } base.InitializeCulture(); } - Sitemaps must be done manually: title="$Resources: SiteMap, Home"