Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
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
Nevron Chart
Search :       Advanced Search »
Home » Internet & Web » Globalization and Localization in .NET

Globalization and Localization in .NET

Localization is a technique to implement local and culture-oriented applications. This articles explains usage of System.Globalization to implement localization support in .NET applications.

Page Views : 124395
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Globalization, Localization

To implementing a multilingual user interface, you design the user interface to open in the default UI language and offer the option to change to other languages.

Globalization is the first step in the process. A globalized application supports localized user interfaces and regional data for all users. Truly global applications should be culture-neutral and language-neutral. A globalized application can correctly accept, process, and display a worldwide assortment of scripts, data formats, and languages.

While your globalized application may possess such flexibility, ensure that you have separated the application's resources that require translation from the rest of the application's code. If you correctly test for localizability before proceeding to the localization step, you should not have to modify your application's source code during localization.

Globalization in .Net - CultureInfo, ResourceManager and Resgen

In .Net System.Globalization namespace contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. There are around 20 classes in System.Globalization. Here we are only concern to CutureInfo class.

CutureInfo class represents information about a specific culture including the names of the culture, the writing system, and the calendar used, as well as access to culture-specific objects that provide information for common operations, such as formatting dates and sorting strings.

The System.Resources namespace provides classes and interfaces that allow developers to create, store, and manage various culture-specific resources used in an application. One of the most important classes of the System.Resources namespace is the ResourceManager class. The ResourceManager class allows the user to access and control resources stored in the main assembly or in resource satellite assemblies

The Resource File Generator (Resgen.exe) converts .txt files and .resx (XML-based resource format) files to common language runtime binary .resources files that can be embedded in a runtime binary executable or compiled into satellite assemblies.

Creating  .resources files

To proceed with our example, let us first create the .resources files. Here I am using six languages English, French, German, Spanish, Italian and Portuguese (Thanks to Google for this and don''t blame me there is anything wrong in conversion). To create .resources files. Create the following six .txt files in any folder as follows.

resource.en-US.txt - which contains the below English text.

0001=Please Enter User Name
0002=Please Enter Password
0003=User Login
0004=Submit
0005=Cancel
0006=Welcome
0007=How are you today?
0008=Select Language

resource.fr-FR.txt - which contains the below French text.

French.jpg

resource.de-DE.txt - which contains the below German text.

German.jpg

resource.es-ES.txt - which contains the below Spanish text.

Spanish.jpg

resource.it-IT.txt - which contains the below Italian text.

Italian.jpg

resource.pt-PT.txt - which contains the below Portuguese text.

Pourtoguese.jpg

Now open the visual studio command prompt and run the resgen.exe with .txt file as parameter as shown in image below.

Globalization1.gif

You will get resource.en-US.resources file after running the Resgen for resource.en-US.txt. Similarly you will get six .resources files for each .txt files.

Creating a Web Application to use .resources files.

Now open the visual studio and open the new c# web application. Add a new a web page Default.aspx. Now open the Default.aspx in HTML mode and paste the following code below the @ page directive.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

 <HEAD>

  <title>Default</title>

  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">

  <meta name="CODE_LANGUAGE" Content="C#">

  <meta name="vs_defaultClientScript" content="JavaScript">

  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

 </HEAD>

 <body MS_POSITIONING="GridLayout">

  <form id="Form1" method="post" runat="server">

   <asp:RadioButtonList id="rdoLanguage" style="Z-INDEX: 101; LEFT: 60px; POSITION: absolute; TOP: 24px"

    runat="server" AutoPostBack="True" Font-Names="Verdana" Font-Size="Smaller">

    <asp:ListItem Value="en-US" Selected="True">English</asp:ListItem>

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

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

    <asp:ListItem Value="es-ES">Spanish</asp:ListItem>

    <asp:ListItem Value="it-IT">Italian</asp:ListItem>

    <asp:ListItem Value="pt-PT">Portuguese</asp:ListItem>

   </asp:RadioButtonList>

   <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 76px; POSITION: absolute; TOP: 180px" runat="server"

    Font-Names="Verdana" Width="68px" Height="24px" Text="-->" Font-Bold="True" Font-Size="8"></asp:Button>

  </form>

 </body>

</HTML>

See the values of List Item en-US for English, fr-FR for French, de-DE for German, es-ES for Spanish, it-IT for Italian and pt-PT for Portuguese. Resources Files will be read using these values, as you will see this later.

Now Switch to design mode, you will see the following output in design mode

Globalization2.gif

Now in design mode click on the (-->) button. Default.aspx.cs will be opened. Write the following code in Button1_Click event

private void Button1_Click(object sender, System.EventArgs e)

{

          Server.Transfer("Login.aspx");

}

Add new Web Form to the project and rename it to Login.aspx. Now open the Login.aspx in HTML mode and paste the following code below the @ page directive.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

 <HEAD>

  <title>Login</title>

  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">

  <meta content="C#" name="CODE_LANGUAGE">

  <meta content="JavaScript" name="vs_defaultClientScript">

  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">

 </HEAD>

 <body MS_POSITIONING="GridLayout">

  <form id="Form1" method="post" runat="server">

   <TABLE id="Table1" style="Z-INDEX: 107; LEFT: 8px; WIDTH: 455px; POSITION: absolute; TOP: 8px; HEIGHT: 48px"

    cellSpacing="1" cellPadding="1" width="455" border="0">

    <TR>

     <TD align="center" colspan="2"><asp:Label id="Label3" runat="server" Width="268px" Height="9px" Font-Names="Verdana" Font-Size="9pt"

       Font-Bold="True">User Login</asp:Label></TD>

    </TR>

    <TR>

     <TD align="right"><asp:Label id="Label1" runat="server" Width="272px" Height="8px" Font-Names="Verdana" Font-Size="8">Label</asp:Label></TD>

     <TD><asp:TextBox id="TextBox1" runat="server" Width="166px" Height="22px" Font-Names="Verdana" Font-Size="8"></asp:TextBox></TD>

    </TR>

    <TR>

     <TD align="right"><asp:Label id="Label2" runat="server" Width="268px" Height="9px" Font-Names="Verdana" Font-Size="8">Label</asp:Label></TD>

     <TD><asp:TextBox id="Textbox3" runat="server" sWidth="166px" Height="24px" Font-Names="Verdana" Font-Size="8"

       Width="164px"></asp:TextBox></TD>

    </TR>

    <TR>

     <TD align="right">

      <asp:Button id="Button1" runat="server" Text="Submit" Font-Names="Verdana" Font-Size="8"></asp:Button></TD>

     <TD>

      <asp:Button id="Button2" runat="server" Text="Cancel" Font-Names="Verdana" Font-Size="8"></asp:Button></TD>

    </TR>

   </TABLE>

  </form>

 </body>

</HTML>

Now Switch to design mode, you will see the following output in design mode

Globalization3.gif

Now in design mode click on the submit button. Login.aspx.cs will be opened. Write the following code in Button1_Click event

private void Button1_Click(object sender, System.EventArgs e)

{

          Server.Transfer("Welcome.aspx");

}

Similarly for the cancel button, add the following code.

private void Button2_Click(object sender, System.EventArgs e)

{

          Server.Transfer("Default.aspx");

}

On the Page_Load event of the Login.aspx.cs add the following code

private void Page_Load(object sender, System.EventArgs e)

{

          if(!Page.IsPostBack)

          {

                   //Retrive the Language from Default page

                   string strCulture = Request.Params["rdoLanguage"].ToString();

                   //Set the Current culuture to session variable

                   Session["SelectCulture"]= strCulture;

                   //create the culture based upon session culuture

                   CultureInfo objCI = new CultureInfo(strCulture);

                   Thread.CurrentThread.CurrentCulture = objCI;

                   Thread.CurrentThread.CurrentUICulture = objCI;

                   //Read the rsources files

                   String strResourcesPath= Server.MapPath("bin");

                   ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("resource", strResourcesPath, null);

                   //Set the values read from resources to contorls

                   Label1.Text=rm.GetString("0001")+": ";

                   Label2.Text=rm.GetString("0002")+": ";

                   Label3.Text=rm.GetString("0003");

                   Button1.Text=rm.GetString("0004");

                   Button2.Text=rm.GetString("0005");

          }

}

Here you can see that how we have created the CulutureInfo object and passed the current selected culture string as a parameter to CulutureInfo. After that set the current page's culture to selected culture by using Thread.CurrentThread.CurrentCulture. Thread.CurrentThread.CurrentUICulture sets the current culture used by the Resource Manager to look up culture-specific resources at run time

Add new Web Form to the project and rename it to Welcome.aspx. Now open the welcome.aspx in HTML mode and paste the following code below the @ page directive.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

 <HEAD>

  <title>Welcome</title>

  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">

  <meta name="CODE_LANGUAGE" Content="C#">

  <meta name="vs_defaultClientScript" content="JavaScript">

  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

 </HEAD>

 <body MS_POSITIONING="GridLayout">

  <form id="Form1" method="post" runat="server">

   <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 20px; POSITION: absolute; TOP: 36px" runat="server"

    Text="Select Another Language" Font-Size="8" Font-Names="Verdana" Width="152px"></asp:Button>

   <asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 20px; POSITION: absolute; TOP: 12px" runat="server"

    Font-Size="8" Font-Names="Verdana" Width="392px">Label</asp:Label>

  </form>

 </body>

</HTML>

Now Switch to design mode, you will see the following output in design mode

Globalization4.gif 

Now in design mode click on the (Select Another Language) button. Welcome.aspx.cs will be opened. Write the following code in Button1_Click event

private void Button1_Click(object sender, System.EventArgs e)

{

          Server.Transfer("Default.aspx");

}

On the Page_Load event of the Welcome.aspx.cs add the following code

private void Page_Load(object sender, System.EventArgs e)

{

          if(!Page.IsPostBack)

          {

                   string strCulture = Session["SelectCulture"].ToString();

                   CultureInfo objCI = new CultureInfo(strCulture);

                   Thread.CurrentThread.CurrentCulture = objCI;

                   Thread.CurrentThread.CurrentUICulture = objCI;

                   //Read the rsources files

                   String strResourcesPath= Server.MapPath("bin");

                   ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("resource", strResourcesPath, null);

                   string strUserName = Request.Params["TextBox1"].ToString();

                   Label1.Text=rm.GetString("0006")+", " + strUserName + "! " + rm.GetString("0007");

                   Button1.Text=rm.GetString("0008");

          }

}

Now coding part is complete. Copy the all six .resources files created in first step to the bin directory of your web application.

In the solution explorer right click Default.aspx page and set it as start up page. Now run the application.If everything is right in its place, you will see the following out

Globalization5.gif 

Select the language as English and click on the button. You will see the Login page

Globalization6.gif

Enter Any User/Pass and click on submit button. You will see the following output.

Globalization7.gif

Now click on Select Language and select French Language. You will see the Login page as follows

Globalization8.gif

Enter Any User/Pass and click on submit button. You will see the following output in French

Globalization9.gif

Similarly you can check for German, Spanish, Italian and Portuguese for this example.

Conclusion

Here we have seen that how System.Globalization helps us for localization the application   without modify application's source code. You can also explore System.Globalization for more languages and objects like RegionInfo, DateFormats etc.

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
 Article Extensions
Contents added by kha kha on May 05, 2010
fdgdf
gdfgdf
df
Contents added by challa sudhakar reddy on Jan 15, 2010
Contents added by sanjay kumar on May 17, 2009
 [Top] Rate this article
 
 About the author
 
Anand Thakur

 

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:
DevExpress Free UI Controls
Become a Sponsor
 Comments
asp by Indhu On July 5, 2006
details about asp.net
Reply | Email | Modify 
put code in Global.aspx file by sheir On July 5, 2006

Hi,

Is it not better to put the resourcemanager into the Application storage in the Global.aspx file in the Application_Start event.  So the RM is created once for the entire life of the application and is just used afterwards.

Also the code for setting the resource dll can be set in the Application_OnAcquireRequestState event of the Global.aspx file,

where the Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture can be set to the new culture.

 

Just my $0.02

sheir

 

 

Reply | Email | Modify 
need help ...... by murlidakhare On August 13, 2006

 hello,

how r u, i need help.

i have to apply multi language to site for dutch, english, german, whole content is coming from DB which is in english, but it should be displayed in languages selected language.

how can i do it.

thanx

Murli Dakhare

murlidakhare@gmail.com 

Reply | Email | Modify 
Re: need help ...... by Avinash On December 3, 2007

hi,

Have  u got solution for this...

Regards,

Avi

Reply | Email | Modify 
Resource Load Combo Box Code? by Toni On October 10, 2007
Hi, Can anyone help me??? I am looking for the resource load code for a combox box. For instance the code for a label is: this.label5.Text = res.GetString("Component List"); Thanks,
Reply | Email | Modify 
nice example by aditya On March 11, 2008
this code worked in first go, no compilation errors no run time errors
Reply | Email | Modify 
Best Localization Plug-in for Visual Studio. by Alexander On September 24, 2008
RGreatEx is a productivity plug-in for JetBrain ReSharper. Once installed, it adds a set of new refactorings and coding assistance features to Visual Studio, allowing developers to localize a project faster and more conveniently than before, improve coding with new time-saving abilities and generate safer code. RGreatEx integrates into Visual Studio seamlessly and works with it without errors. Supported languages are C#, VB.NET and ASP.NET. The power of RGreatEx lies in its pain-free way to add localization support to a .NET application. This can be achieved thanks to the new refactorings, such as “Move to resource” and “Rename resource”. The tool can automatically analyze strings, resources and their usage, detect strings that should be extracted to resources and resources that haven’t been localized yet. The use of RGreatEx helps to save up to 95% of development time as there’s no need to re-write the entire code to integrate localization support to a project. Adding localization support requires little efforts. Simply select a string and choose “Move string to resource” from the quick fixes, select a resource file where you want to extract and refactoring settings. Then you copy your resource file to a resource file for localization – for instance if you have Resources.resx you need to make a copy with the name – Resources.xx-xx.resx (where xx-xx – is your specific culture). The final step is to translate values in Resources.xx-xx.resx by using the Translate resource quick fix. In addition to localization, RGreatEx will help you make coding much easier and enjoyable. You’ll be able to manipulate strings on the fly thanks to the set of new context actions and highlighting options and produce safer resx code. Unique to RGreatEx is an opportunity to select strings from a file, folder, or a project, choose a resource file and keys for the selected strings and move them to resources – all in one go. Download RGreatEx from www.safedevelop.com.
Reply | Email | Modify 
Nice Example by charith On July 30, 2010
Great Example worked For me on the First Go
Reply | Email | Modify 
Re: Nice Example by Shamus On September 24, 2010

For automated .net localization please check out:

www.alchemysoftware.com

Reply | Email | Modify 
Easy localization of .Net projects by Philippe On February 28, 2011
LocalizNet is an easy-to-use localization toolkit for .Net projects. LocalizNet manages localization for WPF, Forms and program strings. Localiznet has very helpful tools for the translator, including dictionaries, incremental translation and identification of work to do. Localiznet is easy to deploy: just add localization files to your deployment package. There are no runtime fees: a software using LocalizNet can be freely deployed. Evaluation version at www.localiznet.com
Reply | Email | Modify 
Re: Easy localization of .Net projects by Larry On April 7, 2011
I'm the author of a professional Visual Studio add-in that makes the entire translation process extremely easy. See http://www.hexadigm.com
Reply | Email | Modify 
Good Article..Thanks a lot by Murugesan On June 10, 2011
Thanks a lot..Really a good article
Reply | Email | Modify 
Re: Good Article..Thanks a lot by Kevin On June 29, 2011
hello,Following is how i implement Web Application Localization , may it help you ! How to implement Web Application Localization 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. Now there is a EasyUpdate Admin Software which Supports English, we are going to localize it into Chinese. Step one : Generate Resources for every page. For example: There is a Login Page named Login.aspx. and I am going to create two resource files named Login.aspx.resx for English and Login.aspx.zh-cn.resx for Chinese for The login page 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 you will see it as below. double click it and you will see : 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,(Login.aspx. resx)<-> Login.aspx.zh-cn.resx) then translate the values.] 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:Button ID="ButtonLogin" runat="server" Text="Login" OnClick="ButtonLogin_Click" meta:resourcekey="ButtonLoginResource1" /> Localization expressions are identified by the meta:resourceKey attribute of the tag. so we run it and change language in the DropdownList we will see : Step Two : Sharing Resources Between Pages: There are some tips and hardcodes used in some pages , we need to save them into resource files ,Because they don’t belong to any page, so we will create Global resources Global resources are placed in the App_GlobalResources folder. Now when the user click the Login button without inputing anything, I would like to show a Errormessage to the user reading from global resources. The code for Login button click is as follows. public partial class Login : System.Web.UI.Page { string strUserNameError; } protected void Page_Load(object sender, EventArgs e) { strUserNameError = Resources.Messages.strUserNameError.ToString(); } protected void ButtonLogin_Click(object sender, EventArgs e) { if (TextBoxUserName.Text == "") { ScriptManager.RegisterStartupScript(this, GetType(), "nameOrPwdError", "alert('" + strUserNameError + "');", true); } } The output is as follows. Step Three: Switching the culture programmatically by overriding Page.InitializeCulture Method: In Login Page protected override void InitializeCulture() { if (Request.Form["DropDownListLogin"] != null) { string selectedLanguage = Request.Form["DropDownListLogin "]; Response.Cookies["EasyUpdateLanguage"].Value = selectedLanguage; m_strLanguage = selectedLanguage; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage); Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage); } else if ( Request.Cookies["EasyUpdateLanguage"] != null ) { string selectedLanguage = Request.Cookies["EasyUpdateLanguage"].Value; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage); Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage); } base.InitializeCulture(); } Step Four: Set a cookie value in Login Page and Read it in all other pages by overriding Page.InitializeCulture Method In Other Pages Wrap the codes follow into a class (ChangeCulture):System.web.ui.page Let other pages’ class Inherits ChangeCulture protected override void InitializeCulture() { if (Request.Form["ctl00$ctl00$ DropDownListMaster "] != null) { string selectedLanguage = Request.Form["ctl00$ctl00$DropDownListMaster"]; Response.Cookies["EasyUpdateLanguage"].Value = selectedLanguage; String m_strLanguage = selectedLanguage; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage); Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage); } else if (Request.Cookies["EasyUpdateLanguage"] != null) { string selectedLanguage = Request.Cookies["EasyUpdateLanguage"].Value; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage); Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage); } base.InitializeCulture(); } Remark: The first time the page read from cookie, and after Page_load , The page will overwrite cookie value and give the cookie value to dropdownlist.selected.value , so that I can get the value when changing language in dropdownlist , only in this way can I unite the language and the culure in every page . That’s all! Thank you! Kevin Wang May , 2011
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.