Recipe 17.4. Using Global Resources and Overriding Currency Formatting


Problem

You want to reuse resources throughout your international application, and you must always display currency with the U.S. dollar symbol, but all other text must follow the language setting in the browser.

Solution

Create a root global resource for your application, add the required items, explicitly set the values of static text in the .aspx files, set the culture and uiCulture attributes of the <globalization> element in web.config to auto, and set the values for dynamic controls in the code-behind class overriding the UI Culture when setting currency values.

Create a global resource file as follows:

  • Create an App_GlobalResources folder in the root of your application.

  • Add a resource file to the App_GlobalResources folder.

  • Edit the resource file to include the required items.

  • Duplicate the root resource file for each language and culture to be supported by your application, setting the values to the resource items as appropriate for the language.

In the .aspx files of your application:

  • Explicitly set the values for all controls that display static text.

Set the culture and uiCulture attributes of the <globalization> element in web.config to auto;

 <globalization culture="auto" uiCulture="auto" /> 

In the code-behind class for each page that needs to support multiple languages, use the .NET language of your choice to:

  • Set the values of controls used for date.

  • Set the values of controls used for currency overriding the UI Culture to be en-US.

  • Set the text of any controls that need to be set programmatically.

Examples 17-7, 17-8 through 17-9 show the .aspx file and VB and C# code-behind files for an application we've written to demonstrate this solution. Example 17-6 shows the web.config settings for globalization.

Discussion

It is not uncommon to have an international application that needs to use the same resources in multiple pages and needs to display dates, a currency value, or other data in a format specific to a language or culture that is not the default. For example, you might need to display currency values in U.S. dollars but all text and dates in the local language of the user. ASP.NET provides support for both requirements.

Global resources are resources that can be used throughout an application (see Recipe 17.2 for an example of using local resources). They are identical in format to local resource files but must be created manually and are placed in the App_GlobalResources folder of your application. Though they must be created manually, the resource editor in Visual Studio 2005 simplifies the task.

Like local resources, the data from global resources can be used to set the values of controls in your ASPX pages without requiring you to write any code. The technique used is different, however. Instead of using meta:resourcekey attributes in the server controls, you explicitly set the properties of the controls.

 <asp:Literal  Runat="server"       Text="<%$ Resources: ASPNetCookbook2, WelcomeToLocalizationResource %>" /> 

The syntax for the command is shown below, where <Root Resource Filename> is the name of the root global resource file and <Resource ID> is the ID of the specific resource item in the file.

 <%$ Resources: <Root Resource Filename>, <Resource ID> %> 

To override the formatting of currency values to be displayed in a specific format, such as U.S. dollars, you must set the format provider to a CultureInfo object that is in turn set to the desired UI Culture, as shown below. If you need to set currency values in many places in your application, you should implement a single method that applies the setting. This will make changes simpler to carry out when they are required.

 

litCost.Text = sampleValue.ToString("C", _ New CultureInfo("en-US"))

litCost.Text = sampleValue.ToString("C", new CultureInfo("en-US"));

When you need to set values programmatically, global resources have a significant advantage over local resources. The global resources are strongly typed, and Intellisense is fully supported. Setting a value from a global resource is identical to using the property of a class, as shown below, where the name of our root global resource file is ASPNetCookbook2 and the name of the resource item is ProgrammaticallySetValue:

 

litProgrammaticallySet.Text = _ Resources.ASPNetCookbook2.ProgrammaticallySetValue

litProgrammaticallySet.Text = Resources.ASPNetCookbook2.ProgrammaticallySetValue;

This recipe and Recipe 17.2 have only touched on the features available in Visual Studio 2005 and ASP.NET 2.0 for internationalizing an application. Search for "ASP.NET Web Page Resources Overview" in the MSDN Library for additional information.

See Also

Recipe 17.2 and "ASP.NET Web Page Resources Overview" in the MSDN Library

Example 17-6. web.config settings for globalization

 <?xml version="1.0"?>  <configuration>   <system.web>     … <!--  GLOBALIZATION          This section sets the globalization settings of the application.     --> <globalization culture="auto" uiCulture="auto" />   </system.web>  </configuration> 

Example 17-7. Global Resources and Overriding Currency (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"    AutoEventWireup="false"    CodeFile="CH17InternationalOverridingCultureVB.aspx.vb"    Inherits="ASPNetCookbook.VBExamples.CH17InternationalOverridingCultureVB"   Title="<%$ Resources: ASPNetCookbook2, HeadingResource %>" %> <asp:Content  runat="server" ContentPlaceHolder>    <div align="center" >      <asp:Localize  runat="server"       Text="<%$ Resources: ASPNetCookbook2, HeadingResource %>" />   </div>   <table width="60%" align="center" border="0" >     <tr>       <td align="center" colspan="2">         <asp:Literal  Runat="server"      Text="<%$ Resources: ASPNetCookbook2, WelcomeToLocalizationResource %>" />       </td>     </tr> <tr>       <td align="right" width="50%">         <asp:Literal  Runat="server"      Text="<%$ Resources: ASPNetCookbook2, WelcomeToLocalizationResource %>" />          :&nbsp;       </td>   <td width="50%">         <asp:Literal  Runat="server" />       </td>     </tr> <tr>       <td align="right" width="50%">         <asp:Literal  Runat="server"      Text="<%$ Resources: ASPNetCookbook2, SampleDateLabel %>" />          :&nbsp;       </td>   <td width="50%">         <asp:Literal  Runat="server" />       </td>     </tr> <tr>       <td align="right" width="50%">          <asp:Literal  Runat="server"       Text="<%$ Resources: ASPNetCookbook2, SampleCostLabelResource %>" />          :&nbsp;       </td>   <td width="50%">         <asp:Literal  Runat="server" />       </td>     </tr> <tr>       <td align="right" width="50%">          <asp:Literal  Runat="server"       Text="<%$ Resources: ASPNetCookbook2, ProgrammaticallySetLabel %>" />          :&nbsp;       </td>   <td width="50%">         <asp:Literal  Runat="server" />       </td>      </tr>    </table>  </asp:Content> 

Example 17-8. Global Resources and Overriding Currency (.vb)

 Option Explicit On  Option Strict On Imports System  Imports System.Globalization Namespace ASPNetCookbook.VBExamples    ''' <summary>    ''' This class provides the code-behind for    ''' CH17InternationalOverridingCultureVB.aspx    ''' </summary>    Partial Class CH17InternationalOverridingCultureVB     Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _                           ByVal e As System.EventArgs) Handles Me.Load       Const sampleValue As Single = 12345.67   'set the control displaying the browser culture setting   If ((Not IsNothing(Request.UserLanguages)) AndAlso _           (Request.UserLanguages.Length > 0)) Then         litLanguageSetting.Text = Request.UserLanguages(0)       Else         litLanguageSetting.Text = "None"       End If       'set the sample date to the current date   litDate.Text = DateTime.Now.ToShortDateString()   'set the sample currency value forcing US formatting    litCost.Text = sampleValue.ToString("C", _                                            New CultureInfo("en-US"))       'set a control programmatically from the global resource file    litProgrammaticallySet.Text = _          Resources.ASPNetCookbook2.ProgrammaticallySetValue     End Sub 'Page_Load    End Class 'CH17InternationalOverridingCultureVB  End Namespace 

Example 17-9. Global Resources and Overriding Currency (.cs)

 using System;  using System.Globalization; namespace ASPNetCookbook.CSExamples {    /// <summary>    /// This class provides the code-behind for    /// CH17InternationalOverridingCultureCS.aspx    /// </summary>    public partial class CH17InternationalOverridingCultureCS :     System.Web.UI.Page   {      ///***********************************************************************  /// <summary>  /// This routine provides the event handler for the page load event.  /// It is responsible for initializing the controls on the page.  /// </summary>  ///  /// <param name="sender">Set to the sender of the event</param>  /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e)     {       const double sampleValue = 12345.67;   // set the control displaying the browser culture setting    if ((Request.UserLanguages != null) &&        (Request.UserLanguages.Length > 0))        {         litLanguageSetting.Text = Request.UserLanguages[0];        }    else        {         litLanguageSetting.Text = "None";       }   // set the sample date to the current date   litDate.Text = DateTime.Now.ToShortDateString();   // set the sample currency value forcing US formatting    litCost.Text = sampleValue.ToString("C",                                            new CultureInfo("en-US"));       // set a control programmatically from the global resource file    litProgrammaticallySet.Text =          Resources.ASPNetCookbook2.ProgrammaticallySetValue;     } // Page_Load    } // CH17InternationalOverridingCultureCS  } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

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