Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Visual C# » How to build Multi-Language Web Sites with ASP.NET 2.0 and VS.Net 2005

How to build Multi-Language Web Sites with ASP.NET 2.0 and VS.Net 2005

In this article, we will explore the necessary details for working with resources in ASP.NET applications and for creating international ASP.NET applications based on embedded resources and the integrated localization support.

Author Rank :
Page Views : 240411
Downloads : 4601
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
LocalizationDemo.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

In order to reach international markets through the Internet, supporting different cultures through our applications is essential for being successful. The .NET Framework 2.0 as well as 1.x comes with an integrated infrastructure for creating international applications. Basically, the CLR supports a mechanism for packaging and deploying resources with any type of application. The CLR and the base class library of the .NET Framework come with several classes for managing and accessing resources in applications. These classes are located in the System.Resources and System.Globalization namespaces. Here we will explore the necessary details for working with resources in ASP.NET applications and for creating international ASP.NET applications based on embedded resources and the integrated localization support.

Assumptions:

This article assumes that you already know how to build web forms and to use controls and validation controls.

Localization and resource files:

Localization support in .Net Framework 2.0 in general and in ASP.Net 2.0 specifically become much more easier and brings fun during localization process. Usually resources are created for every culture the application should support. More specifically, each Web Form -Page- in your web site should have a resources for every culture -language- it should support. For example:

If you have a web form with name default.aspx and your web site support English, German and Arabic, then you should have 3 resource files for each culture. The CLR defines a behavior for finding culture-specific resources. With that said, every set of resources has to define a base name that is specified through the first part of the name of the resource file. The second part of the name defines the culture. If the culture portion in the name is not specified, the resources defined in the resource file are used as default resources. For example:

Your page name is default.aspx., you have 3 resource files as mentioned earlier, each one resource file should be named as:

default.aspx.en-US.resx, default.aspx.de-DE.resx and default.aspx.ar-EG.resx. Not here that we are using United States English, German's Gemran, and Egyptian's Arabic. You can use general English or general German or general Arabic like this:

default.aspx.en.resx, default.aspx.de.resx and default.aspx.ar.resx. Also you can use another specific culture like using Switzerland German culture this way: default.aspx.de-CH.resx. For list of supported cultures in .Net Framework return to
MSDN.

How to build Multi-Language Web Sites with ASP.NET 2.0 and Visual Studio.Net 2005:

For localizing a page, just select Tools > Generate Local Resources. Visual Studio then generates a resource file in the App_LocalResources folder, which includes the values for every control of the page currently open in design view





Visual Studio generates resources for several properties of each control. The resources are always prefixed with the name of the control and postfixed with the name of the property. Visual Studio automatically generates the default resources for the controls of the page only. You must add any further culture-specific resources manually by copying the generated resources and giving them the appropriate name (for example, default.aspx.ar-EG.resx) then translate the values.

The resource generation tool creates an entry for every property that is marked with the [Localizable] attribute in the control. Therefore, if you want to create a custom, localizable control, you have to mark all [Localizable] properties with this attribute.

Copying the resources created previously and renaming this copy to default.aspx.de.resx and default.aspx.ar-EG.resx adds the culture-specific resources for the German and Arabic cultures to the application.

Arabic Resources German Resources

In addition to generating the resource file, Visual Studio has changed the page's source code. For every [Localizable] property of each control placed on the page, it has added a localization expression, as shown in the following code snippet:

<asp:Label ID="LegendFirstname" runat="server" Text="Firstname:" meta:resourcekey="LabelResource1"> </asp:Label>

Localization expressions are identified by the meta:resourceKey attribute of the tag.

The localization expression in the previous code is called implicit localization expression. Implicit localization expressions are something like shortcuts to resource keys included in the embedded resources for a page. They have to adhere to the naming conventions used by Visual Studio for generating the resources. Implicit localization expressions just specify the base resource key for the embedded resource without a property name. Property names are derived from the second part of the name. Note that you can use implicit localization expressions for [Localizable] properties only.

In the attached sample, there are RegularExpressionValidator controls. Although the RegularExpressionValidator control is included in the generated resources, the validation expression property is not included, because it is not marked with the [Localizable] attribute. But the validation of both the birth date and the annual salary has to happen based on the culture settings of the user browsing to the page, because US visitors want to add their birth date in the format they are used to (and the same goes for Germans and Arabs or any other visitors).

Therefore, you need to do some additional work before you are finished localizing the application. Basically, two ways for localizing the validation of those two text fields are available. The first one is to automatically generate the regular expression for the validation based on the CultureInfo object created for the user's culture. The second approach is to add an entry to the embedded resources for the validation expression. But we will go for the second approach to discuss how explicit localization expressions work. First, you have to add two new entries, containing the regular expression for validating the user's birth date and annual salary input, to the embedded resources. Afterward, you need to change the definition of those controls as follows (assuming that the resource entries are called RegularExpressionValidatorResource1.Validation and RegularExpressionValidator-Resource2.Validation):

<asp:RegularExpressionValidator ControlToValidate="BirthdateText" ErrorMessage="Invalid date!!" ID="RegularExpressionValidator1" runat="server" ValidationExpression= '<%$ Resources: RegularExpressionValidatorResource1.Validation %>' meta:resourcekey="RegularExpressionValidatorResource1" />

You can probably see that the previous validator still contains some static text-in this case ErrorMessage. Don't worry about that. Because the validation control has a meta:resourcekey, the control will ignore the static text, and the runtime will get its data from the generated resources. As soon as a control has such a meta:resourcekey attribute, it ignores static text and reads all information from embedded, localized resources. In the case of the ValidationExpression, you have to use explicit localization expressions, because automatic localization is not provided for this property. The general format for explicit localization expressions follows this syntax:

<%$ Resources: [ApplicationKey, ] ResourceKey %>

The application key identifies shared application resources and therefore can be omitted when accessing local resources.

The following screen shot shows that localized properties are marked with special icons in the Properties window. The localization expressions themselves leverage the new expression engine included with ASP.NET 2.0.

Sharing Resources Between Pages:

Generating local resources for a single page might lead to a duplication of resource strings or other resource information. Therefore, it is definitely useful to share resources between pages through global resources. Global resources are placed in the App_GlobalResources folder. One good use for it for identifying system messages for each culture, or text direction setting, or common validation expressions for regular expression validators. For example, the validation expressions for date formats and number formats used earlier are definitely good candidates to be reused in several pages of the application, it is useful to put them into a global resource file. For this purpose you just need to add a new, global resource file and then add the values to those resources.

Now you have to adopt the explicit localization expression for the two validation controls. For this purpose you have to change the name and add the ApplicationKey parameter. Because we already named the global resource file ValidationResources.resx previously, this will be the value for the ApplicationKey property (without the .resx extension).

<asp:RegularExpressionValidator ControlToValidate="BirthdateText" ErrorMessage="Invalid date!!" ID="RegularExpressionValidator1" runat="server"
ValidationExpression='<%$ Resources:ValidationResources, DateFormat %>' meta:resourcekey="RegularExpressionValidatorResource1" />

Also you may need a way to specify the text direction in international applications, because some cultures read from left to right and others read from right to left. You can use a couple of controls in ASP.NET, such as the Panel control and the WebPart control, to deal with this. Therefore, it makes sense to define a property in either the global resources or the local resources for the text direction and to use explicit localization expressions for setting the direction property of these controls. For setting this property directly in the root element of your HTML file, you must use the runat="server" attribute to the <html> tag itself, and then you can apply explicit localization expressions to it, as shown in the following code excerpt:

<html runat="server" dir='<%$ Resources:ValidationResources, TextDirection %>' >

Setting Page Culture:

To set the page culture, you can set the Culture Property of the page and UICulture to use specific culture or set it to Auto to automatically Client Browser Language. Also you can make a default culture for your application by adding the following code to your web.config under system.web tag:

<globalization enableClientBasedCulture="true" culture="ar-EG" uiCulture="ar-EG"/>

Or switching the culture programmatically by overriding Page.InitializeCulture Method:

protected override void InitializeCulture()
{

string culture = Request.Form["cmbCulture"];
if (string.IsNullOrEmpty(culture)) culture = "Auto";
//Use this
this.UICulture = culture;
this.Culture = culture;
//OR This
if (culture != "Auto")
{
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
}
base.InitializeCulture();

}
Protected Overrides Sub InitializeCulture()

Dim _culture As String = Request.Form("cmbCulture")
'Use this
If (String.IsNullOrEmpty(Culture)) Then
culture = "Auto"
Me.UICulture = _culture
Me.Culture = _culture
End If
'OR This
If (_culture <> "Auto") Then
Dim ci As New System.Globalization.CultureInfo(Culture)
System.Threading.Thread.CurrentThread.CurrentCulture = ci
System.Threading.Thread.CurrentThread.CurrentUICulture = ci
End If
MyBase.InitializeCulture()

End Sub

The above code is using a DropDownList with ID cmbCulture.

One Important thing about the InitializeCulture method, it is called very early in the page life cycle, before controls are created or properties are set for the page. Therefore, to read values that are passed to the page from controls, you must get them directly from the request using the Form collection. Just as we did above.

This is all, test it and have fun with localization support of ASP.NET 2.0

Read VB.NET Version

References:

Pro ASP.NET 2.0 In C# 2005 book from APress.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Muhammad Mosa
Muhammad M. Mosa Soliman: Software Engineer, graduated from the Faculty of Computers & Information Systems year 2003-Ain Shams University- in Cairo. Working with Microsoft .NET technology since early beta releases. Main experiance based on ASP.NET, SharePoint Portal 2003 & SQL Server. Worked as trainer for Microsoft .NET for 2 years in Cairo. Likes to read about new technologies and self-learning. Extremly Hard worker when motivated. MCT MCSD.NET MCTS: .Net 2.0 Web/Windows Applications MCPD: Enterprise Application Developer MCTS: WSS 3.0 & MOSS 2007 Config
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Arabic Numbers and VS Web Developer 2005 (Express Edition) by M On February 22, 2006
I am working on a multi language site (English and Arabic). I am having trouble getting VS Web Developer 2005 to accept/display arabic numbers. Everytime I a number, the number is automatically converted to English and is never displayed in Arabic. I have set up the correct setting in Windows XP and in other programs (Word, Notepad, IE, etc..) I am able to enter arabic numbers. Even I enter an Arabic number in MS Word and then cut and paste it into VS Studio Developer 2005, the number is automatically converted to its English equivilent. VS Web Developer 2005 does accept Arabic letters but not Arabic numbers. Even the code line numbers in VS Web Developer 2005 display in Arabic, but not the numbers that I input via the keyboard. Do you have any suggestions for this?
Reply | Email | Modify 
Re: Arabic Numbers and VS Web Developer 2005 (Express Edition) by Muhammad On February 7, 2007
You mean arabic numbers that is indian numbers, this is just to make sure of what you mean. I'll try to look as it and get back to you
Reply | Email | Modify 
Multilanguage globalization and master pages by Koen On March 9, 2006

hi

I created one dropdownlist in asp.net after that filled it in runtime  and related checkbox is there

the problem is that when user checked a one check box the related record(before it fill in runtime) should be highlight in dropdownlist

so how to do that

if anybody find this answer then mail me --abhisheka.nayak@gmail.com

thanks and regards

Abhisheka

 

Reply | Email | Modify 
Re: Multilanguage globalization and master pages by Muhammad On March 11, 2006

Yes I've noticed that too, but I think this is a bug in the framework but I'm not sure.

 

Reply | Email | Modify 
Re: Multilanguage globalization and master pages by Muhammad On March 11, 2006
Reply | Email | Modify 
Need help in asp search page by Hafeez On May 3, 2006
Mr. Mosa
Could you help me in asp page connected with access .mdb. I cant search Arabic record but english search ok. What should I do to search arabic record. thanks
 
Reply | Email | Modify 
retrieve a dropdownlist value inside InitializeCulture() !!! by Nacer On November 26, 2006

Hi,

i am using a child page inside a master page.

the child page is to set the language for my application. it contains :

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Langues.aspx.cs" Inherits="Langues" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

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

<br />

<asp:DropDownList ID="Language1" runat="server" AutoPostBack="True">

<asp:ListItem Value="auto">Auto</asp:ListItem>

<asp:ListItem Value="en-US">English (US)</asp:ListItem>

<asp:ListItem Value="en-GB">English (UK)</asp:ListItem>

<asp:ListItem Value="de">German</asp:ListItem>

<asp:ListItem Value="fr">French</asp:ListItem>

<asp:ListItem Value="fr-CA">French (Canada)</asp:ListItem>

<asp:ListItem Value="hi">Hindi</asp:ListItem>

<asp:ListItem Value="th">Thai</asp:ListItem>

</asp:DropDownList>

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

</asp:Content>

in the code behind of this page i added :

protected override void InitializeCulture()

{

string lang = Request["Language1"];

if (lang11 != null && lang != "")

{

Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);

}

base.InitializeCulture();

}

THE PROBLEM IS :

string lang = Request["Language1"];  ====> returns always null

Thank you for yoyr help

Nacer

 

Reply | Email | Modify 
Re: retrieve a dropdownlist value inside InitializeCulture() !!! by Muhammad On February 21, 2007

yes, because the control name now is not "Language1" You are using a Master page and this is a naming container, the control will be rendered with deferent name than Language1.

You may refer to the following blog entry to see how you can resolve you issue

http://dotnetslackers.com/community/blogs/mosessaur/archive/2006/10/17/Setting-MasterPage-ID-Property.aspx

Reply | Email | Modify 
How can I change the resource in runtime? by chuot On April 1, 2007
hi, I mean, I have 2 global resource files for English and France, in this syntax: <%$ Resources: [ApplicationKey, ] ResourceKey %> , how can I change the ApplicationKey in runtime? Can you help me for this? Thanks very much
Reply | Email | Modify 
Re: How can I change the resource in runtime? by Muhammad On April 2, 2007

Do you mean you want to switch from english to french!

in this case you'll need to override InitializeCulture method.
this was mentioned at the end of the article. also review comments on this article.

 

Reply | Email | Modify 
Dynamic Content in Multi lingual by Hiren On April 18, 2007
Hi, This is very good article and its very useful for beginners but I just want information about conversation of dynamic content in multi lingual application If you are binding one datagrid with some data When you press on French link all datagrid data should be convert to frence language is it possible in asp.net 2.0? Regards, Harry
Reply | Email | Modify 
Re: Dynamic Content in Multi lingual by Muhammad On April 18, 2007

Well, this of course requires that you store french content into your database.
Before binding, you should retrieve the content related to the current selected culture.
I think this cannot be done automatically as in static content stored in resources.

Reply | Email | Modify 
Controls not visible!!! by Eduardo On August 19, 2007
I'm new to this multilingual issues, I'm following this tutorial but when I finally managed to add the local resources, almost every control in the aspx disappear (labels, textboxes and buttons). Only one control stays alive (a label), wich indicates that the resources are working "fine". Could anybody help me please?
Reply | Email | Modify 
Re: Controls not visible!!! by Eduardo On August 19, 2007
Maybe this can help you to help me: I have 2 resources: Default.aspx.resx (for spanish) Default.aspx.en-US.resx (for english) I have this on my aspx: [code] <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %> Prueba

[/code] I have this on my code behind (ommiting the uses'): [code] public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected override void InitializeCulture() { string culture = Request.Form["ddlLenguaje"]; if (string.IsNullOrEmpty(culture)) culture = "Auto"; //Use this UICulture = culture; Culture = culture; //OR This if (culture != "Auto") { System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(culture); System.Threading.Thread.CurrentThread.CurrentCulture = ci; System.Threading.Thread.CurrentThread.CurrentUICulture = ci; } base.InitializeCulture(); } protected void cambiaCultura(Object sender, EventArgs e) { string cultura = ddlLenguaje.SelectedValue; this.UICulture = cultura; this.Culture = cultura; } } [/code] But when I try to run it I get this HTML code, no matter what I have selected in the drop down list: [code] Prueba

Introduce tus datos de usuario para ingresar

[/code] PLEASE HELPPP!!!
Reply | Email | Modify 
Re: Re: Controls not visible!!! by shiva On May 26, 2009
can u tell me how to enter arabic letters into a textbox from keyboard?
Reply | Email | Modify 
Question about article by Kaushal On May 27, 2009
Hello,

       Article is very useful to develop application with multi language,but now i have some of the question after refer the demo application,we have develop resource file for the arabic language,on that we wrote the text for particular label,now how can i get that text and how can i mention that text on resource file using our English keyboard.do we need to perfom that task for all forms and all controls in our application?

Thanks
Kaushal Pathak
Reply | Email | Modify 
how to use kannada in aspx page? by sharath On August 14, 2009
Hi friends. 
I want to use kannada font in aspx page, Is it possible to use kannada font in aspx page?
I want code for aspx.cs also if it contains any cs coding. Pls help me out
Thanks in advance,,
Reply | Email | Modify 
Multi-Language Web Sites by ashish On August 24, 2009
hi ..i have tested ur example ..but gives me a warning when i give the lable text in language resource file ...it says "Warning    1    The resource name 'lbl1Resource1.Text' is not a valid identifier."so that it does not convert the desired text from english to german ...plz let me know where i am wrong ..thnx :)
Reply | Email | Modify 
Good Article... by Amit On December 21, 2009
Hello Muhammad,
     This is nice article for beginners like me in localization, providing us basics of localization and culture.
Thanks..
Reply | Email | Modify 
Develop Website in Multi Language by JasRaj On December 23, 2009
Jas Raj Bishnoi
Thanks Mosa,
For help me.
Reply | Email | Modify 
Re: Develop Website in Multi Language by riky On June 14, 2010
how to use this in master page?
Reply | Email | Modify 
thanks by joe On December 2, 2010
this demo is very helpful 4 me
Reply | Email | Modify 
thanks by avrail On February 22, 2011
thanks a lot
Reply | Email | Modify 
thanks Mosa by tuan On March 25, 2011
thanks for your help
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.