Globalizing Your ASP.NET Applications

Taking Advantage of the System.Globalization Namespace

Alex Fedorov

October 30, 2009

12 Min Read
ITPro Today logo in a gray background | ITPro Today

asp:feature

Languages: VB

Technologies: Internationalization | Globalization |System.Globalization

 

GlobalizingYour ASP.NET Applications

TakingAdvantage of the System.Globalization Namespace

 

By AlexFedorov

 

This isthe first article of a two-part series on the globalization and localizationfeatures that are implemented in the Microsoft .NET Framework and available forASP.NET developers. In this first part, I will look at the globalizationfeatures implemented in the System.Globalizationnamespace through different classes and enumerations. I also will createseveral example programs that show how to use these features in ASP.NET.

 

Thesecond part of this article will deal with localization. I will explore howcultural information corresponds to language selections and how to createresource-based ASP.NET applications. I will create several examples to show youhow to use the ResourceManager classto manage resources stored in resourcesfiles and how to use satellite assemblies.

 

Overview

Before Ijump into the details, let me define some terms. Globalization is the process of developing a Web application corewhose features and code design aren't based on a single language or locale andwhose source-code base makes it easier to create editions of the application indifferent languages. Localization isthe process of adapting a Web application so it is appropriate for the area, orlocale, for which it is used. In an international market, this meanstranslating the user interface and the content, customizing features (ifnecessary), and testing the results to ensure the site or program stillfunctions correctly. A localizable application is an application that is readyfor translation - all the strings and images are separated from the code.

 

A goodlocalization and globalization solution is an essential part of anymultilingual project, and it should be considered during the early stages ofthe project design. There may be different approaches to technicalimplementation. For example, I could create a fixed set of Web pages fordifferent languages and store them in separate directories, or I could useonline translation software. I also could use in-memory dictionaries (e.g., theDictionary object that is part ofthe Microsoft Scripting Engine, the LookupTable object, or the MessageManager object that is part ofthe Microsoft Commerce Server 2000) that will be accessed on a per-term basis.

 

Anotheroption is to use the XML-based dictionaries. They serve the same purpose butare more flexible in terms of multilingual support. As for globalization, I canuse some limited support available in the ASP object model and create COMobjects. That would provide the access to National Language Supportfunctionality of the Microsoft Windows platform and its API.

 

.NET PlatformFeatures

Tosimplify development of multilingual applications, the .NET platform uses theconcepts of culture and region. These concepts, supported by appropriateclasses, define the information that contains cultural conventions and regionalsettings. This information is very useful for the globalization of Webapplications.

 

To helpWeb developers localize their applications, the .NET platform extends theconcept of resources to Web applications. Resources in .NET can be stored infiles with the resources extension or in satelliteassemblies and can be managed through the new ResourceManager class. Resources can be used with normal Windowsapplications as well as in Web applications. Using Visual Studio .NET allowsdevelopers to create all the files required for localization. By simplyattaching XML-based resources (resxfiles) to my project, I easily can create applications that support differentlanguages and provide a fallback for the neutral resource (default language),if the resource for a particular language cannot be found.

 

Globalization

Theglobalization features available in the .NET Framework are implemented in the System.Globalization namespace throughdifferent classes and enumerations.

 

The twomain classes for globalization in this namespace are CultureInfo and RegionInfo.The CultureInfo class containscountry-specific cultural information, such as language, calendar, sorting, andso on. Note that culture is the client-defined "value." You specify it as the locale when you install your operatingsystem. The RegionInfo classcontains region-specific information, such as region name, currency symbol,metric-system indicator, and other information. FIGURE 1 shows the members ofthe System.Globalization namespace.

 


FIGURE 1: The System.Globalization namespace members.

 

System.Globalization classes include Calendar, which represents time in divisions such as weeks, months, andyears. There are different calendars for different cultures: GregorianCalendar, HebrewCalendar, HijriCalendar,JapaneseCalendar, JulianCalendar, KoreanCalendar, TaiwanCalendar,and ThaiBuddhistCalendar. The DateTimeFormatInfo class defines howthe selected culture affects the values of the DateTime structure, NumberFormatInfodefines how the selected culture affects numeric values, StringInfo is used to iterate string values, and TextInfo defines code pages and otherfunctions to work with text.

 

Language Negotiation

Languagenegotiation occurs when the user sets his or her preferred language, in orderof preference, in the browser. Then, the browser negotiates with the server toattempt to find a page in a suitable language. For example, in InternetExplorer, you can specify a set of preferred languages by selecting Tools| Internet Options andclicking on the Languages button as shown in FIGURE 2.

 


FIGURE 2: Specifying languageprioritization in Internet Explorer.

 

Theserver code can extract this information later because it's sent as part of theHTTP request and stored in the HTTP_ACCEPT_LANGUAGEvariable. (The HTTP_ACCEPT_LANGUAGEvariable is supported by most HTTP 1.1 browsers.) Sometimes languagenegotiation can produce results that aren't suitable for the user. For example,although the default language may be specified as French, the user may preferto browse the English version of the site. In this case, you might provide alanguage-selection menu on the start page.

 

Some Websites use another scenario: They try to guess a user's language preference bylooking up the country extension in the IP address. For example, if the user issurfing from proxy.myprovider.co.uk (a providerbased in the United Kingdom), the sites assume the user speaks English. This isoften a convenient strategy, but is not necessarily the most accurate. Forexample, many users browse from .com, .net, or similar address suffixes that donot have any obvious relationship to a particular language.

 

Toaccess a user's language preferences in ASP.NET, you can use the UserLanguages property of the HTTPRequest class that contains aweighted string array of client language preferences. The fact that they'reweighted means that if the user has specified more than one language, the firstone will be the default language, and others will have numeric weightsindicating how far the particular language is from the default one. Forexample, the languages shown in FIGURE 2 have the weighted string array shownin FIGURE 3.

 


FIGURE 3: Language preferenceweights for the languages specified in FIGURE 2.

 

Thesource code for the page shown in FIGURE 3 (langpref.aspx) is provided in the download files accompanying thisarticle (see end of article for details).

 

I'll usethis feature to create a menu based on client languages that will be used inlater examples of this article. Note that although I easily could specify thedefault language as the main language for an application, it is always betterto give the user a chance to change the default language. FIGURE 4 contains theVisual Basic .NET code that populates a list box with the region names,extracted from the list of languages.

 

SubPage_Load(ByVal sender As Object, ByVal e As EventArgs)

  Dim UserLangs() As String

  Dim Count As Integer

  Dim Pos   As Integer

  Dim Lang  As String

 

 If Not IsPostBack Then

  UserLangs = Request.UserLanguages

   For Count = 0 To UserLangs.GetUpperBound(0)

    Pos = InStr(1, UserLangs(Count),";")

     If Pos > 0 Then

      Lang = Left(UserLangs(Count).ToUpper,Pos-1)

     Else

      Lang = UserLangs(Count).ToUpper

     End If

    Pos = InStr(1, Lang, "-")

    If Pos > 0 Then

      Lang = Lang.Substring(Pos, Lang.Length-Pos)

    End If

    LangList.Items.Add(Lang)

   Next Count

  End If

 End Sub

FIGURE 4:Populating the list box with region names.

 

Using RegionInfo Class

Now I amready to use the RegionInfo class.I'll create an application that will allow me to check various region settingsfor specified regions. To do this, I need to implement the OnSelectedIndexChanged event handler for my list box that waspopulated with the code from FIGURE 4. The code for the event handler is shownin FIGURE 5.

 

SubIndex_Changed(sender As Object, e As EventArgs)

  Dim Region As RegionInfo

 

  Region = NewRegionInfo(LangList.SelectedItem.Text)

 

   AddRow(RegTable, "Name",        Region.Name)

   AddRow(RegTable, "EnglishName", _

    Region.EnglishName)

   AddRow(RegTable,"DisplayName",   _

    Region.DisplayName)

   AddRow(RegTable,"CurrencySymbol", _

    Region.CurrencySymbol)

   AddRow(RegTable,"ISOCurrencySymbol",   _

    Region.ISOCurrencySymbol)

   AddRow(RegTable, "IsMetric",   Region.IsMetric)

   AddRow(RegTable,"TwoLetterISORegionName", _

    Region.TwoLetterISORegionName)

   AddRow(RegTable,"ThreeLetterISORegionName", _

    Region.ThreeLetterISORegionName)

   AddRow(RegTable,"ThreeLetterWindowsRegionName", _

    Region.ThreeLetterWindowsRegionName)

End Sub

FIGURE 5:This code populates a table with RegionInfoinformation.

 

On eachlist-box click, I create a new RegionInfoobject with the specified region name and show its attributes. For example,information for the United States is shown in FIGURE 6.

 


FIGURE 6: Regionalinformation for the United States that was populated with information from the RegionInfo class.

 

Notethat the IsMetric property value isset to False. That means that for this region, I should perform conversions ofthe length and weight measurements because the current region does not use themetric system.

 

For allcountries that are part of the European Community, the CurrencySymbol property will contain the Euro symbol, and the ISOCurrencySymbol will contain EUR. TheEuro currency became the official currency in January. FIGURE 7 shows theregional information for Spain.

 


FIGURE 7: Regionalinformation for Spain. Note the Euro symbol in the CurrencySymbol property.

 

FIGURE 8shows the members of the RegionInfoclass. The complete source code for the RegionInfopage is provided in the download files accompanying this article.

 


FIGURE 8: Members of the RegionInfoclass.

 

Using the CultureInfo Class

Before Ican build an application that will use the CultureInfoclass, I need to modify the code that builds the menu. I need to include thefull name of the language in the form ll-RR,in which ll represents the language, and RR the region. This conforms to theRFC 1766 standard, in which language code is a lowercase, two-letter codederived from ISO 639-1 standard; and in which region code is an uppercase,two-letter code derived from ISO 3166 standard. For more information aboutthese standards, refer to the References section at the end of this article.The modified menu-building code is shown in FIGURE 9.

 

SubPage_Load(ByVal sender As Object, ByVal e As EventArgs)

  Dim UserLangs() As String

  Dim Count As Integer

  Dim Pos   As Integer

  Dim Lang  As String

 

 If Not IsPostBack Then

  UserLangs = Request.UserLanguages

   For Count = 0 To UserLangs.GetUpperBound(0)

    Pos = InStr(1, UserLangs(Count),";")

     If Pos > 0 Then

      Lang = Left(UserLangs(Count).ToUpper,Pos-1)

     Else

      Lang = UserLangs(Count).ToUpper

     End If

    LangList.Items.Add(Lang)

   Next Count

  End If

 End Sub

FIGURE 9:Menu-building code.

 

Thedifference here is that I preserve the language name if it is in the ll-RRform. For languages that contain only the region name, such as FR, DE, ES, andIT in this example, I add the missing part programmatically. I do this in theevent handler for the list box, which starts with the following code:

 

SubIndex_Changed(sender As Object, e As EventArgs)

  Dim Culture As CultureInfo

  Dim CID As String

 

  CID =LangList.SelectedItem.Text

  If InStr(1, CID, "-") = 0 Then

     CID += "-" & CID

   End If

 

In .NETterms, the neutral culture is the culture associated with a language but notwith a country or region.

 

FIGURE 10 shows the members of the CultureInfo class.

 


FIGURE 10: Members of the CultureInfo class.

 

In .NET,each individual thread maintains its own culture information. The defaultculture information is available through Thread.CurrentThread.CurrentCultureobject of CultureInfo type. Tochange the current culture, you need to create a new object of CultureInfo type and assign a newculture ID:

 

Culture = New CultureInfo(CID)

 

I willdo that in the event handler for the list box:

 

Culture = NewCultureInfo(CID)

Thread.CurrentThread.CurrentCulture=Culture

 

After Ihave changed the current culture to the one the user selected, I can displaysome of its properties, as shown in FIGURE 11.

 

  With Culture

   AddRow(CultTable, "Name",         .Name)

   AddRow(CultTable,"DisplayName",  .DisplayName)

   AddRow(CultTable,"EnglishName",  .EnglishName)

   AddRow(CultTable, "NativeName",_     

    .TextInfo.ToTitleCase(.NativeName))

   AddRow(CultTable, "Parent",       .Parent.Name)

   AddRow(CultTable,"TextInfo",     .TextInfo.ANSICodePage)

   AddRow(CultTable, "LCID",         .LCID)

   AddRow(CultTable,"Calendar",     .Calendar.ToString())

   AddRow(CultTable,"DateTime",      DateTime.Now.ToString("D", _

     Nothing))

   AddRow(CultTable,"DayNames",      GetDayNames(Culture))

   AddRow(CultTable,"MonthNames",    GetMonthNames(Culture))

  End With

FIGURE 11:Displaying properties of the current culture using an instance of the CultureInfo class.

 

The result of this code, for French language used in Switzerland,is shown in FIGURE 12.

 


FIGURE 12: The cultureinfo.aspx page displaysinformation about a particular culture.

 

In thecode shown in FIGURE 11, I'm using several properties of the CultureInfo class as well as otherclasses. For example, I use the TextInfoinstance that allows me to find the code page information for the currentlyselected culture. TextInfo also allows me to performlowercase-to-uppercase conversion (ToTitleCasemethod). I have also used the DateTime.Nowmethod to display the current date in a country-specific format.

 

Twocustom functions, GetDayNames and GetMonthNames, are used to createstrings with day and month names for the selected language, respectively. Thesymbol, used to separate the list, is taken from the ListSeparator property of the TextInfoinstance. The code for the GetDayNamesfunction is shown in FIGURE 13.

 

 Function GetDayNames(C AsCultureInfo) As String

  Dim I         As Integer

  Dim DayNames  As String()

  Dim SDayNames As String

 

  DayNames =C.DateTimeFormat.DayNames

 

   For I=0 to DayNames.GetUpperBound(0)

    SDayNames += DayNames(I)

    If I < DayNames.GetUpperBound(0) Then

     SDayNames += C.TextInfo.ListSeparator& " "

    End If

   Next

   GetDayNames = SDayNames

 

 End Function

FIGURE 13:Code for the GetDayNames function,which is used to create a list of day names for the selected culture.

 

Notethat I could achieve the same result by using the DayNames property of the DateTimeFormatInfoclass.

 

The complete source code for the CultureInfo page is provided in the accompanying download files.

 

Conclusion

Bycombining the information found in the RegionInfoand CultureInfo objects, I have allthe information required for globalizing a Web application. The next thing todo is localize the application, which involves translating the user interfaceand all the content. To do so in ASP.NET applications I can use the cultureinfo provided by the CultureInfoclass, resources, and the ResourceManagerclass. I will cover localization of ASP.NET applications in the conclusion ofthis two-part series.

 

References

 

The complete source code for the projects referenced inthis article is available for download.

 

Alex Fedorovis a chief technology officer for Netface SA, based in Lausanne, Switzerland (http://www.netface.ch). He co-authored Professional Active Server Pages 2.0 and ASP Programmer's Reference published by Wrox, as well as Advanced Delphi Developer's Guide to ADO, published by Wordware Publishing. Alex also has contributedseveral articles to Delphi Informant Magazine.

 

Tell us what you think! Please send any comments about thisarticle to [email protected] include the article title and author.

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like