Localization in ASP.NET 4.0

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 48310 red flag
Rating: 5 out of 5  
 1 vote(s)

Creating web application that serves different users with different cultures is crucial for clients who are doing business gloablly and ASP.NET helps developers to create such kind of application easily. In article I shall describe how to achive localization in ASP.NET web application. Localization helps to develop a global application that can be used by the global users having different cultures.


 Download source code for Localization in ASP.NET 4.0

Introduction

In this article, we shall learn how to use ASP.NET localization to develop a global application that can be used in any computer enabled language. In order to develop localized application, we will need to use an ASP.NET out of the box CultureInfo object. Below are some of the properties I have got from the CultureInfo object that will help us to understand the culture information of the current request. 

Listing Culture specific details

For this example, I have used Arabic language as displayed in the Picture 1.

Picture 1

In order to change the language of your browser, go to your Internet explorer and select Tools > Internet Options and click on Languages button. Click Add ... button to add any language you want to use. You can use multiple languages so that if a website doesn't support the first language it searches for the 2nd one from the list and so on.

Listing culture specific property details

As my browser language is set to Arabic, my code behind code will return the result displayed in Picture 2. You will need to use following namespaces to execute codes of this article.

using System.Globalization;

using System.Threading;

Get solutions of your .NET problems with video explanations and source code in .NET How to's.

protected void Page_Load(object sender, EventArgs e)

{

CultureInfo info = System.Threading.Thread.CurrentThread.CurrentCulture;

 

lblMessage.Text = "Culture nane: " + info.Name + "<br />" +

"Culture parent name: " + info.Parent.Name + "<br />" +

"Display name: " + info.Parent.DisplayName + "<br />" +

"English name: " + info.EnglishName + "<br />" +

"Native name: " + info.NativeName + "<br />" +

"ISO name: " + info.Parent.ThreeLetterISOLanguageName + "<br />" +

"Calendar type: " + info.Calendar.ToString();

 

lblMessage.Text += "<hr />" + DateTime.Now.ToString();

}

Picture 2

On another note, look at the calendar control, it is smart enough to identify the current culture and give you the day, month labels accordingly.

Setting culture programatically

Now, suppose I want to change the current culture programmatically, I can use following code to set the new culture.

Thread.CurrentThread.CurrentCulture = new CultureInfo("gsw-FR");

Notice the string in the bracket, you can get your culture specific string from the Picture 1 displayed above (click on the Add button in and you will see the list of language supported by your browser and their culture string).

Creating global application

To create a global application we need to use local resources that can be created in App_LocalResources folder. Let us develop a sample web page. My sample web page looks like below picture in which first one is with simple English and second comes when browser language is set to French (As I do not know French so I have written the French label suffixed with "(In French Language)" :).

Let us create a default.aspx page with a label, a textbox, and a button. Note the attribute meta:resourcekey that comes only when you generate the resource file from Visual Studio, so you do not need to write it explicitely.

<div>

<h3>Localization</h3>

<asp:Label ID="lblName" runat="server" Text="Enter your name: "

meta:resourcekey="lblNameResource1" />

<asp:TextBox ID="txtBox1" runat="server" meta:resourcekey="txtBox1Resource1" />

<asp:Button ID="btnSubmit" runat="server" OnClick="SubmitDetials" Text="Submit"

meta:resourcekey="btnSubmitResource1" /> <br />

<asp:Label ID="lblResponse" runat="server"

meta:resourcekey="lblResponseResource2" />

</div>

How to generate the resource (.resx) file?

To generate the resource file go to the Design View of the .aspx page and go to Tools > Generate Local Resource menu. It will create a App_LocalResources folder (if doesn't exists) with the file named "default.aspx.resx" (In my case the .aspx file name is default.aspx).

This was your default resource file, what if you want to create a resource file that should be used for different language? Well, you will have to create this kind of resource file for every language you want your application to support. You will also need to specify language specific values for the different keys available in the resource file. So just copy this file with another name accordingly. (For example, I wanted to create resource file for French, I will create a file named "Default.aspx.gsw-FR.resx", notice the string "gsw-FR" between .aspx and .resx. This is used by ASP.NET to identify the resource file to be used for each request.

Notice that you need to add two attributes in the page directives if Visual Studio doesn't add it automatically while creating the resource files.

<%@ Page Language="C#" AutoEventWireup="true" Culture="Auto" UICulture="Auto" CodeFile="Default.aspx.cs" Inherits="Localization_Default" meta:resourcekey="PageResource1" %>

Notice the bold Culture and UICulture attributes value to "Auto". This enable the web page to be localized by detecting the current culture.

How it works?

Now we have two resource files, one of my default culture that is English and another for French. When I request the web page by setting my browser language as English (en-US) (assuming my local user is using my application), the default resource file (Default.aspx.resx) is used to display the labels so all the text on the page will be displayed in English language but when I set my browser language to French (assuming someone from France is using my application), the French resource file (Default.aspx.gsw-FR.resx) will be used and all text on the page will be displayed in French. Is n't ASP.NET coool?

How to retrive a value from Resource file (.resx file)?

Notice the .resx file; it is a xml file and data are stored in key and value pair. You are free to create your own custom keys and values (so for example if you want to write a success message in different languages, create a custom key in all different resource files with different values in different languages.)

string thisValue = GetLocalResourceObject("lblNameResource1.Text").ToString() + " : " + txtBox1.Text;

To retrieve the value from the resource file, we can use GetLocalResoureceObject method by passing the keys available in the resource file. In this case, I wanted to retrieve the value of "lblNameResourece1.Text" key.

Specifying culture settings

There are different ways of specifying the culture settigns.

1. Through web.config file. We can specify application level culture setting by using the gloabalization tag in the web.config file.

       <system.web>

<globalization culture="gsw-FR" uiCulture="gsw-FR" />

       </system.web>

2. Page level. We can also specify culture information at page level where we can specify it in Page directives.

<%@ Page Language="C#" AutoEventWireup="true" Culture="Auto" UICulture="Auto" CodeFile="Default.aspx.cs" Inherits="Localization_Default" %>

What if user culture specific resource file is not available on our server?

In case you want a specific culture to be applied when a user from other culture (you do not support) is using your application, in that case you can mention a fallback culture using colon at the page level.

<%@ Page Language="C#" AutoEventWireup="true" Culture="Auto:en-US" UICulture="Auto:en-US" CodeFile="Default.aspx.cs" Inherits="Localization_Default" %>

What is GlobalResource file?

Whatever resource files we created till now was specific to a page, what if we want to create a resource file that can be used throughout the application? Yes, you can do that. Right click your web Project add folder by going to  Add ASP.NET Folder  > Add App_GloablResources. Right click the this folder and add a new resource file (in my case I added Resource.resx file and added a key called MyName).

Now as we did for LocalResources, we need to create different files for different cultures so I have created a file called "Resource.gsw-FR.resx" for French with same key but different value.

How to retrieve the value from GlobalResource file?

You can use Resources obect in the .aspx page something like this

<asp:Label ID="Label1" runat="server" Text='<%$ Resources: Resource, MyName %>' />

or in the code behind page something like

 

Response.Write(Resources.Resource.MyName.ToString());

 

// OR

 

Response.Write(GetGlobalResourceObject("Resource", "MyName").ToString());

Source Code

I have attached the sample code used to describe localziation in this article, please feel free to download and play with it.

Conclusion

Creating web application that serves different users with different cultures is crucial for clients who are doing business gloablly and ASP.NET helps developers to create such kind of application easily.

Hope this article will help some of you creating global application, please caste your vote for this article and respond if you like or even didn't like !

Thanks for reading and keep reading, learning and sharing ! 

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Akiii on: 5/21/2012 | Points: 25
Great article Sir...



Thanks and Regards
Akiii
Posted by: Raj.Trivedi on: 7/15/2013 | Points: 25
Hello Sir,

Great Article..

I have one question

I have a Master Page which has a Drop Down and in which i want languages like Arabic,German,French,Spanish and if the user selects the language from the drop down then the entire application language should be changed as per selection.


Login to post response

Comment using Facebook(Author doesn't get notification)