Search This Blog

Wednesday, March 10, 2010

Localization in ASP.NET 2.0

Abstract

In this article, I am going to present the new localization feature provided by .NET framework 2.0. Throughout the article, the new tools provided by Visual Studio 2005 to support localization will be highlighted and used to show you how easy it is to localize your web applications with ASP.NET 2.0.


Introduction

A few years ago we started hearing new terms in economics about globalization and integration of international markets.  This made many large business companies begin thinking of how to attract markets from all over the world and not only from domestic markets.  The first idea that might come to the company is to have a Multilanguage website; clients from a set of targeted countries can localize their website to their own native language.

ASP.NET 2.0 comes with a rich environment that makes localization of web applications a very easy task to perform.  There are two main kinds of localization in ASP.NET 2.0: implicit localization and explicit localization, each of which will be discussed in more detail throughout this article.

Preliminary Steps

When you think of localizing a web application, some preliminary steps should be taken into account.  Those steps can be summarized in two main points:

Globalization: The main strategy of the web application is set in this step.  The web application architect shall ask the following questions: How many countries or languages are targeted in the application?  What sections are to be localized?  Etc.  In addition, gathering of resources for all the predetermined languages should be collected before any implementation starts.

Localization: The actual localization and implementation through code is done in this step.  The resources needed are supplied to the web application and then it is the developer's role to allow the application being worked on to support all the predetermined languages required by their application.

Localization and Visual Studio 2005

Visual Studio 2005 now ships with a new resource editor that allows you to easily add/remove/update any resource key in any ASP.NET resource file (.resx).

In addition, Visual Studio 2005 makes generating resource files an easy step to do by just going to Toolsà Generate Local Resource while your WebForm is in the Design view.

Moreover, Visual Studio 2005 provides two ways of localizing a web application.  The first is using Local Resources; a local resource is a resource file attached to a WebForm.  Or you could use   Global Resources in which you can combine all common resource keys used by several ASP.NET web forms into a single resource file.

The above tools and concepts will be revisited throughout this article while creating and manipulating resource files.

Working with Local Resources

In this section we are going to show how easy it is to generate a local resource file for any ASP.NET web form.  By local resource we mean that a single resource file is in a many to 1 relationship with the ASP.NET web form.  In other words, if you have a Label server control and you want to show some text in this label for each culture available in the web application, then you place a resource key in an accompanying resource file for a specific culture.  At run time, the resource key will be looked up in the culture-specific resource file, evaluated and replaced with the proper text translation.  You can have several resource files for the same ASP.NET web form, each representing a specific culture.

To generate a local resource file in Visual Studio 2005, start by creating a new website.  Open the default.aspx page and add few controls, including the following:

Label Server Control, with an ID of lblName

TextBox Server Control, with an ID of txtName

Button Server Control with an Id of btnSubmit

The figure below shows what the default.aspx page looks like.



Make sure your default.aspx page is in the design view.  Then go to Tools à click on the Generate Local Resource command.

You will notice two changes to your web application and ASP.NET page.  First of all, a new "system" folder has been added in the web application’s root folder called App_LocalResources.  The App_LocalResources folder has been newly added to the ASP.NET 2.0 web application. This folder holds all the resource files for all the ASP.NET web forms.  The ASP.NET runtime uses the .NET framework, ResourceManager, to perform resource key lookups.  The ResourceManager will look at the App_LocalResources folder at all times.  This means that any resource file located outside this folder will be ignored.

You can easily add a new resource file to that folder to represent any additional language for your web application by simply copying the default resource file of an ASP.NET form and pasting it with a new name.  For instance, if you have the default.aspx.resx resource file, which represents the English language, then you have English set as the default language of your machine.  Now you want to add the Arabic-Lebanese language for your web application.  You simply copy the default.aspx.resx and rename it to defaut.aspx.ar-LB.resx.  This way you have added support for a new language.  The only thing left to do is to change the values of every resource key inside the resource file added.

Next, open the source view of the default.aspx page and you will notice new tags have been added to the controls that require localization.

Listing 1


<form id="form1"runat="server">
<div>
<asp:Label ID="lblName"runat="server"meta:resourcekey="lblNameResource1">asp:Label>
<asp:TextBox ID="txtName"runat="server"meta:resourcekey="txtNameResource1">asp:TextBox><br/>
<br />
<asp:Button ID="btnSubmit"runat="server" Text="Submit"meta:resourcekey="btnSubmitResource1" />div>
form>

As you can see, a “meta:” tag has been added to every server control together with a resource key that corresponds to the resource key entry in the default.aspx.resx resource file.

The snapshot of the default.aspx.resx is shown below.

Figure 2




For each server control a single resource key has been added with multiple properties of .Text and .ToolTip.

As mentioned above, at runtime the resource key will be evaluated and the corresponding text in the resource file will be displayed.

Now we can add the Text and ToolTip values for every control in the resource file.  However, before we can run this page and see how it is being localized automatically, we have to specify the Culture and UICulture properties in the Page directive.  This way, the ASP.NET runtime will know the culture used and apply the specific resource file for that chosen culture.

To do so, add the following to the Page directive:

Listing 2


Culture="auto:en-US" UICulture="auto"

We have set the Culture to be auto and have a default value of en-US and the UICulture set to auto.  Having an auto property means that the request will automatically detect the culture specified on the client browser.

Run the application and you will see that the server mainly controls the Label and that the Button Text property will be evaluated based on the culture and the resource file of that culture.

To support an additional culture, copy the original resource file as mentioned above and add your translation for the entire resource key and test it in your browser.  To test your application with other cultures, refer to the following: Setting a Preferred Language in Internet Explorer.

Working with Global Resources

As mentioned above, the Local Resources are in a many to 1 relationship with ASP.NET web forms.  In some cases, your ASP.NET web forms in an application might share a set of resource keys.  Instead of having redundant data in your resource files, ASP.NET 2.0 introduces the App_GlobalResources folder which lets you place all the global resources, i.e. resources shared by some ASP.NET web forms, in one location.

To create a new global resource, right click your web application root, add an ASP.NET Folder and choose App_GlobalResources.  Then right click this folder and add a new Resource file.  The structure of this resource file is the same as the structure of the resource files placed inside the App_LocalResources.  However, the name of this file can be any meaningful name and is not limited to the name of the ASP.NET web form.  This file, as mentioned above, will hold shared resource keys for several ASP.NET web forms.

To have the same resource file available for several languages, you need to follow the same steps mentioned while discussing the local resources.  The default global resource file is named resource.resx and the French version is written as resource.fr.resx.

Add a new Label Server control to the default.aspx page as:

Listing 3

<asp:Label ID="lblwelcome" runat="server"/>

Inside the resource.resx and resource.fr.resx files add one resource key called “welcome.”

English:

Key: welcome

Value: Welcome to our website

French:

Key: welcome

Value: Bienvenue à notre site Web

To link the global resource to the above label, we need to do the following:

Right click on the label in Design view, click on properties and then choose Expressions.  A pop-up window is then opened for you so choose from the Bindable properties, Text property and form the Expression Type, Resources.  In the Expression Properties you set the ClassKey to be resource.resx and the ResourceKey to be welcome.

You can see now how the label server control looks.

Listing 4

<asp:Label ID="lblwelcome"runat="server" Text="<%$ Resources:resource, welcome%>">asp:Label>

Instead of having implicit localization as the case of local resources, the explicit localization in global localization is done by evaluating an expression and giving this expression the original resource name and the resource key in that resource file.

Now, run your application in a browser and try to change the default culture of your browser from English to French and see how the text inside the label changes as specified in the two resource files mentioned above.

CurrentCulture and CurrentUICulture

Before going on with this article, let us stop and discuss the two main properties of concern, mainly the CurrentCulture and CurrentUICulture.

CurrentCulture and CurrentUICulture are both of the type CultureInfo which belongs to the System.Globalization.

CurrentCulture and CurrentUICulture are both properties of the current thread represented by System.Threading.Thread.CurrentThread.CurrentCulture and System.Threading.Thread.CurrentThread.CurrentUICulture

CurrentCulture is used mainly to format the Dates, Currencies, etc.  For that reason, it should be set as specific and not left as neutral.  For instance, you need to set the CurrentCulture as:

Listing 5

System.Threading.Thread.CurrentThread.CurrentCulture= newCultureInfo("ar-LB");

We have set the current culture to be a specific culture, Arabic - Lebanese.  So make sure to always be specific in specifying the CurrentCulture.

CurrentUICulture is mainly used for language/text translations.  The ResourceManager is based upon the CurrentUICulture.  It does not matter whether the culture set here is specific or neutral.  For instance, either ar or ar-lb works fine with the CurrentUICulture.

Listing 6

System.Threading.Thread.CurrentThread.CurrentCulture= newCultureInfo("ar");

Programmatically Setting Culture and UICulture

In the above discussion, we have seen that the Culture and UICulture properties inside the Page directive were set to "auto."  In this section we will learn how to set both properties programmatically inside our VB.NET or C# code.

Create a new ASP.NET web form and add the following code:

Listing 7

<asp:DropDownList ID="ddlLanguage"runat="server" AutoPostBack="True">
<asp:ListItem Selected="True"Value="auto">Autoasp:ListItem>
<asp:ListItemValue="en-US">English (US)asp:ListItem>
<asp:ListItemValue="en-GB">English (UK)asp:ListItem>
<asp:ListItemValue="ar">Arabicasp:ListItem>
<asp:ListItemValue="fr">Frenchasp:ListItem>
asp:DropDownList>

This DropDownList lists a few options to change the default culture.  One of the methods of the Page class is called InitializeCulture().  This method is being executed in the early stages of the page creation.  It is the responsibility of this method to set the Culture and UICulture of the current request.  We will override this method to build our own logic in setting the above two mentioned properties based on the selection from the DropDownList.

Copy this code and paste it inside your code behind class.

Listing 8

protected override void InitializeCulture()
{
  string lang =Request["DropDownList1"];


  if ((lang != null))
  {
    if (lang != "")
    {
      Thread.CurrentThread.CurrentUICulture =new CultureInfo(lang);
      Thread.CurrentThread.CurrentCulture =CultureInfo.CreateSpecificCulture
        (lang);
    }
  }
}

In this piece of code, we are first getting the selection from the language DropDownList.  Notice that we did not use the DropDownList properties to access the selected option; this is done on purpose, since the first time the page is visited the DropDownList will not be created.  We use the Request object to access the form's controls.

The CurrentUICulture property is set to the language selected.

The CurrentCulture, as mentioned above, should always be set to a specific culture.  Keeping that in mind, we have to use the static method of CultureInfo object, CreateSpecificCulture().   This takes as an input a parameter specifying the culture and returns a CultureInfo instance having a specific culture set.

Once a culture is chosen from the DropDownList, the current Culture and UICulture will be set accordingly.


Conclusion

We have presented the new localization features in ASP.NET 2.0.  Visual Studio 2005 has been improved to give a better experience in many aspects, mainly the Localization of web applications.  Two new features in ASP.NET 2.0 Localization, Implicit and Explicit localization, have been discussed.  A distinction between CurrentCulture and CurrentUICulture was given showing the similarities/differences and the effect of each of them.  Finally, a programmatic way of setting the CurrentCulture and CurrentUICulture was shown.

Hope you enjoyed this article.

Happy Dot Netting!!

No comments:

Post a Comment

Leave your suggession & comment...