Implementing Localization for the User Interface

Implementing Localization for the User Interface

The two key pieces to keep in mind when implementing localization for the user interface are cultures and resource files. A culture , as you'll see, is an identifier for a particular locale. A resource file is a place where you can store some culture-dependent resources such as strings and bitmaps. (The .NET Framework handles translating other resources, such as date formats, automatically.)

Understanding Cultures

A culture , in .NET terms, is a more precise identifier than a location or language. A culture identifies all the things that might need to be localized in an application, which requires you to know more than just the language. For example, just knowing that an application uses English as its user interface language doesn't give you enough information to completely localize it: Should you format dates and currency amounts in that application in a way appropriate to the United States, the United Kingdom, Canada, Australia, or New Zealand (among other possibilities)?

About Culture Codes

The .NET Framework follows the IETF Standard RFC 1766 to identify cultures, meaning cultures are identified by abbreviations called culture codes . A full culture code consists of a neutral culture code (written in lowercase) followed by one or more subculture codes (written in mixed case or uppercase). Here are a few culture codes as examples:

  • de Identifies the German clture. This is a neutral culture, a culture that does not specify a subculture code. Neutral cultures generally do not provide sufficient information to localize an application.

  • en-GB Identifies the English (United Kingdom) culture. This is a specific culture, a culture that provides enough information to localize an application (in this case, for English speakers in Great Britain).

  • az-AZ-Cyrl An example of a specific culture with two subculture codes. This particular culture refers to the Azeri language in Azerbaijan, written with Cyrillic characters .

The CultureInfo Class

The .NET Framework represents cultures with the System.Globalization.CultureInfo class. This class lets you retrieve a wide variety of information about any particular culture, as shown in the following steps:

  1. Open Visual Studio .NET and create a new blank solution named 315C10 at c:\inetpub\ wwwroot \ExamCram (you might need to change the directory based on your configuration).

  2. Add a new Visual C# ASP.NET Web application at the following location: http://localhost/ExamCram/315C10/Example10_1 .

  3. On the Web form, place a Button control with an ID of btnGetInfo , a TextBox control with an ID of txtCulture , and a ListBox control with an ID of lbInfo on the form. Set the Text property of the Button control to Get Info .

  4. Switch to Code view and add the following using directive:

     using System.Globalization; 
  5. Double-click the Button control and enter the following code to handle the button's Click event:

     private void btnGetInfo_Click(object sender, System.EventArgs e) {    // Create a CultureInfo object for the specified culture    CultureInfo ci = new CultureInfo(txtCulture.Text);    // Dump information about the culture    lbInfo.Items.Clear();    lbInfo.Items.Add("Display Name: " + ci.DisplayName);    lbInfo.Items.Add("English Name: " + ci.EnglishName);    lbInfo.Items.Add("Native Name: " + ci.NativeName);    // Get day names    lbInfo.Items.Add("Day Names:");    String[] strDayNames = ci.DateTimeFormat.DayNames;    foreach(String strDay in strDayNames)    {        lbInfo.Items.Add("  " + strDay);    }    // Get the current year    lbInfo.Items.Add("Current year: " +          ci.Calendar.GetYear(DateTime.Today));    // And the currency symbol    lbInfo.Items.Add("Currency symbol: " +         ci.NumberFormat.CurrencySymbol); } 
  6. Select Debug, Start to execute the project. Enter the name of a culture in the text box and click the Get Info button. The form retrieves and displays some of the information the CultureInfo object can return, as shown in Figure 10.1.

    Figure 10.1. You can retrieve information about a culture using the CultureInfo class.

    graphics/10fig01.jpg

This program works by creating a CultureInfo object to represent the specified culture. It then uses properties of the CultureInfo object (and of the objects the CultureInfo contains, such as the DateTimeFormat , NumberFormat , and Calendar objects) to retrieve information about that culture. This information is useful in localizing applications, and it's all built right in to the .NET Framework.

graphics/alert_icon.gif

You might want a list of all the supported cultures. The static CultureInfo.GetCultures() method returns an array of CultureInfo objects you can enumerate to get that list.


The CultureInfo class is the key to localizing applications. After you've retrieved the proper CultureInfo object, you can derive a wide variety of information from it.

The CurrentCulture and CurrentUICulture Properties

The .NET Framework handles localization on a thread-by-thread basis. Each thread has two properties used for determining the culture to use: CurrentCulture and CurrentUICulture . You can set or view these properties on the Thread.CurrentThread object.

The CurrentUICulture property tells the Common Language Runtime (CLR) which culture to use when choosing resources for the user interface.

The CurrentCulture property is also used by the CLR to manage localization, but it's used in a different way. The CurrentCulture property dictates the format for dates, times, currency, numbers , and other culture-specific functionality such as string comparison rules and casing rules.

The Invariant Culture

One more culture that you should know about is the invariant culture, a special culture that doesn't have an abbreviation. It has two purposes:

  • To interact with other software, such as system services, where no user is directly involved

  • To store data in a culture-independent format that is not displayed directly to end users

There are two ways to create a CultureInfo object that represents the invariant culture as shown in the following code:

 CultureInfo ciInv = new CultureInfo(""); CultureInfo ciInv = CultureInfo.InvariantCulture; 

Displaying Localized Information

Now that you know how culture information is stored in the .NET Framework, you're ready to see its use in code. Take the following steps to learn how to display localized information in a Web form:

  1. Create a new Visual C# ASP.NET Web Application project to the existing solution. Name the project Example10_2 .

  2. Place a Label control (set its Text property to Select a Culture: ), a DropDownList control ( ddlSelectCulture ), and four TextBox controls ( txtCulture , txtDate , txtCurrency , and txtNumber ) on the form. Set the AutoPostBack property of the DropDownList control to true .

  3. Switch to Code view and enter the following using directives:

     using System.Globalization; using System.Threading; 
  4. Attach an event handler to the SelectedIndexChanged event of the drop-down list. Enter the following code in the class definition:

     private void Page_Load(object sender,     System.EventArgs e) {     // Stock the Dropdownlist     if (!IsPostBack)     {       foreach(CultureInfo ci in CultureInfo.GetCultures(           CultureTypes.SpecificCultures))       {             ddlSelectCulture.Items.Add(ci.Name);       }     } } private void ddlSelectCulture_SelectedIndexChanged(      object sender, System.EventArgs e) {   // Create an appropriate CultureInfo object for the thread   Thread.CurrentThread.CurrentCulture = new CultureInfo(      ddlSelectCulture.SelectedItem.Text);   // Display the name of the culture   txtCulture.Text =      Thread.CurrentThread.CurrentCulture.EnglishName;   // Refresh the display of the data   DisplayData(); } private void DisplayData() {     DateTime dtNow = DateTime.Now;     Double dblcurrency = 13472.85;     Double dblnumber = 1409872.3502;     txtDate.Text = dtNow.ToLongDateString();     txtCurrency.Text = dblcurrency.ToString("c");     txtNumber.Text = dblnumber.ToString("n"); } 
  5. Set the project as the start project for the solution and select Debug, Start to execute the project.

  6. Select a culture from the drop-down list. The form refreshes to display localized information, as shown in Figure 10.2.

    Figure 10.2. You can set the culture for the currently running thread using the Thread.CurrentThread . CurrentCulture property.

    graphics/10fig02.jpg

When you select a culture from the drop-down list, the code uses that information to create a CultureInfo object assigned to the CurrentCulture property of the CurrentThread . It then calls a method to display some data on the form. Note that the DisplayData() method simply uses the ToLongDateString() and ToString() methods to format the data it displays. You don't have to do anything special to tell these methods which culture to usethey automatically use the culture specified by the CurrentCulture property.

Setting Culture Properties

When you set the CurrentCulture and CurrentUICulture properties, you have two choices:

  • You can set them based on information stored in the user's operating system.

  • You can provide a user interface to let the user choose a culture for formatting.

To use the culture of the operating system, you don't have to do anything because the .NET Framework chooses the appropriate culture automatically. However, this strategy does not work well in ASP.NET applications because the culture the .NET Framework detects is the culture on the Web server, not the culture on the user's computer.

You can also code your ASP.NET application to sense the culture from the user's browser. The ASP.NET Request object returns an array of strings specifying the language preferences the user's browser has set. The first member of this array is the default language of the browser, in the standard culture code format. You can use this value to create an appropriate CultureInfo object for the current thread. For example, you could use this code:

 Thread.CurrentThread.CurrentCulture = _  new CultureInfo(Request.UserLanguages[0]) 

Attractive though this strategy sounds, it doesn't work well in practice for several reasons:

  • Web browsers aren't required to specify a user language when sending an HTTP request for a Web page.

  • Even if a Web browser specifies one or more acceptable languages, there's no guarantee that any of those languages will exactly match a culture the .NET Framework makes available.

  • The user might be using a Web browser whose language doesn't match the user's own preferred language.

Generally, you should let the user choose the culture the application should use. If you want to let the user choose the culture to use, you can follow a strategy similar to the one you just saw: Provide a control to select a culture and update the CurrentCulture and CurrentUICulture properties when the user makes a selection from this control.

Working with Resource Files

So far, you've seen how to use the CurrentCulture property to handle localized formatting of things such as currency, dates, and numbers. But localizing the text displayed on the user interface is perhaps even more important. The .NET Framework offers support for user interface localization through its capability to select a set of user interface resources at runtime.

The resources you select at runtime are contained in assembly resource files, which are specially formatted XML files that contain localized text. Visual Studio .NET enables you to work directly with assembly resource files.

The following example demonstrates how to use Visual Studio .NET to localize the user interface of a simple application:

  1. Add a new Visual C# ASP.NET Web Application project to the current solution and name it Example10_3 .

  2. Place a Label control with an ID of lblFolder , three RadioButton controls ( rbMyDocuments , rbDesktop , and rbNewFolder ), a DropDownList control with an ID of ddlCulture , and a Button control with an ID of btnSave on the form. Set the AutoPostBack property of the DropDownList control to true .

  3. Select Project, Add New Item; then select the Assembly Resource File template. Name the new item AppStrings.resx and click Open to create the file. The new file opens in the Visual Studio .NET IDE with a grid-based editing interface.

  4. Enter names and values to identify all the text strings on the user interface, as shown in Figure 10.3. You can optionally enter a comment for each string. The type and mimetype columns are not used for localizing strings.

    Figure 10.3. You can enter invariant resources with the help of a grid-based editing interface provided by the Assembly Resource File template.

    graphics/10fig03.jpg

  5. Add two more assembly resource files to the project. The first, named AppStrings.en-US.resx , should contain another copy of the strings in English. The second, named AppStrings.fr-FR.resx , should contain the strings in French, as shown in Figure 10.4. Note that the Name column is the same in the English and French versions; only the Value column changes.

    Figure 10.4. You can enter culture-specific resources with the help of the grid-based editing interface provided by the Assembly Resource File template.

    graphics/10fig04.jpg

  6. Switch to Code view and enter the following using directives:

     using System.Globalization; using System.Resources; using System.Threading; 
  7. Attach an event handler to the drop-down list's SelectedIndexChanged event. Enter the following code in the class definition:

     private void Page_Load(object sender,      System.EventArgs e) {     if (!IsPostBack)     {         // Put language choices in the DropDownList         ddlCulture.Items.Add("English");         ddlCulture.Items.Add("French");         // Initialize the UI text         SetUIText();     } } private void ddlCulture_SelectedIndexChanged(object    sender, System.EventArgs e) {     // When the user selects a language     // change the UI culture     switch (ddlCulture.SelectedItem.Text)     {         case "English":             Thread.CurrentThread.CurrentUICulture =                 new CultureInfo("en-US");             break;         case "French":             Thread.CurrentThread.CurrentUICulture =                 new CultureInfo("fr-FR");             break;     }     // Initialize the UI text     SetUIText(); } private void SetUIText() {     // Create a ResourceManager object     // by passing the fully qualified base name     // and the resource assembly to its constructor     ResourceManager rm = new ResourceManager(          "Example10_3.AppStrings", Type.GetType(              "Example10_3.WebForm1").Assembly);     lblFolder.Text = rm.GetString("Folder");     rbMyDocuments.Text = rm.GetString("My_Documents");     rbDesktop.Text = rm.GetString("Desktop");     rbNewFolder.Text = rm.GetString("New_Folder");     btnSave.Text = rm.GetString("Save"); } 
  8. Set the project as the start page for the solution. Select Debug, Start to execute the application. As you select languages in the drop-down list, the user interface is refreshed with the appropriate resources.

The naming of resource files follows a required pattern. The .NET Framework looks for several specific files when it's loading resources, depending on the base name of the resources and the selected culture. The base name is the second part of the first parameter to the ResourceManager constructorin this case AppStrings . When the CurrentUICulture is set to a CultureInfo object representing the fr-FR (French in France) culture, the .NET Framework checks for resources in three possible files, in this order:

  1. A specific culture file, in this case AppStrings.fr-FR.resx

  2. A neutral culture file, in this case AppStrings.fr.resx

  3. An invariant culture file, in this case AppStrings.resx

In other words, the .NET Framework falls back on increasingly more general resources when trying to load resources for a form.

Runtime user interface resources are actually loaded by an instance of the System.Resources.ResourceManager class. After you have initialized a ResourceManager object by calling one of the class's constructors, you can use these two methods to retrieve localized resources:

  • GetObject() Returns an object from the appropriate resource file

  • GetString() Returns a string from the appropriate resource file



MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net