Blue Theme Orange Theme Green Theme Red Theme
 
Safari Books Online
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET » 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:
Total page views :  15401
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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.


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
 Comments
arabic page localization by mohi88 On June 3, 2007
dear Muhammad thank you very much for the artical it is very useful. here i have a challange on changing the page layout from english to arabic when the user asks for arabic language. there for do you have any idea about how and what to be used to solve thie problem. best regards Muhanad YOUNIS
Reply | Email | Delete | Modify | 
Re: arabic page localization by Muhammad On June 5, 2007

What do you mean by chaning layout?! do you mean changing the whole design?! In this case all you need to do is change the design but retain resource keys "Control IDs".

Or Add you localization keys to a global resource file, link your controls to those keys.

And if you want to change the direction like LTR to RTL I've mentioned that near the end of the article.

I wished I could help more

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.