How to: Adding localization support to ASP.NET web by extending Page class (C#)

 Rate It (0)

Localization

Localization is often required on the web. For that reason, .NET framework includes localization support trough System.Globalization namespace.

However, while there is support, you need some extra work to use it. One of the most repeated tasks is actually making the localization available to your web pages and making the system fit to user preferences.

Localization system

The goal of this article is to provide one of the solutions for a clean and easy implementation of the localization system using regular Culture settings provided by ASP.NET.

To do it, we will extend the basic System.Web.UI.Page class by overriding the IntilializeCulture method. This way, our web pages will be integrated with a persistent localization system that will, except for keeping track of user language selection while browsing the page, also keep track of user preferences for future visits.

This way, our only job on localization will be to provide users with language selection menu.

Implementation

We will start by creating a new class library to create our own Page class. After creating the Page.cs file, we start to create our new, extended and localized Page class.

First, we will need to include some additional namespaces and assembly references:

using System;

using System.Configuration;

using System.Web;

using System.Globalization;

using System.Threading;

Do not forget to reference: System.Web and System.configuration.

Library

Now, we override InitializeCulture method:

// Override InitializeCulture method to provide integrated localization support.

protected override void InitializeCulture()

{

base.InitializeCulture();

// For this example, we will use a local web.config application settings section to define

// page defaults and available settings.

// To start we need a CultureInfo object constructed from a default language selection.

// You could also contruct a specialized section or a private configuration file.

CultureInfo selectedCulture = new CultureInfo(ConfigurationManager.AppSettings["Localization_DefaultLanguage"]);

// To save permanent information about user language selection, we will use cookies.

HttpCookie cookie = Request.Cookies.Get("lang");

// Setting up a cookie to expire in a custom-defined time frame (also defined in web.config).

DateTime cookieExpiration = DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["Localization_LanguageCookieExpirationInDays"]));

// Now, we will check for explicit query string language selection.

// This way we enable users to change language using url variables

if (Request.QueryString["lang"] != null)

{

selectedCulture =
new CultureInfo(Request.QueryString["lang"]);

 

// We will also write a cookie to remember our selection.

cookie = new HttpCookie("lang", selectedCulture.Name) { Expires = cookieExpiration };

Response.Cookies.Add(cookie);

}

// If no explicit selection is found, use the one saved in a cookie.

else if (cookie != null)

{

selectedCulture =
new CultureInfo(cookie.Value);

}

// If for any reason both methods fail, fall to default settings.

else

{

// Just write a cookie to save default option.

cookie = new HttpCookie("lang", selectedCulture.Name) { Expires = cookieExpiration };

Response.Cookies.Add(cookie);

}

// Apply selected language to Page culture.

Thread.CurrentThread.CurrentUICulture = selectedCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture.Name);

}

That would be all required to implement internal localization support for the page. Now we should actually use it inside a web site.

Using custom Page class to localize a web site

Just create a default web site and add previously created class library as a reference.

On the Default.aspx page we will add a small Label for demonstration purposes. It will contain a meaningless text that will be translated.

To provide localization, we will use built-in resource file based localization, thus we will create Default.aspx.resx files for all the languages we need.

Resx, references

Now, we will programatically create a language selection menu using previously prepared settings in the Web.config file:

<appSettings>

<add key="Localization_AvailableLanguages" value="en-gb,en-us,hr,it,fr,de,es,ru"/>

<add key="Localization_DefaultLanguage" value="fr"/>

<add key="Localization_LanguageCookieExpirationInDays" value="5"/>

</appSettings>

The menu will be created using a simple inline foreach loop:

<ul>

<%

foreach (string language in ConfigurationManager.AppSettings["Localization_AvailableLanguages"].Split(','))

{

Response.Write(
string.Format("<li><a href='{0}?lang={1}'>{2}</a></li>", Request.Path, language, new CultureInfo(language).NativeName));

}

%>

</ul>

And this would be pretty much all. Do not forget to change the Page class used by the Default web form class:

public partial class _Default : WikiArticle_LocalizationLib.Page

Press F5 (build and run) and enjoy the show. If you did everything correctly, you should be seeing the page like this:

Result page

 

Using this system, you are now able to easily extend supported languages and have user language preferences always stored in the system. This system can easily be extended according to your needs.

Library settings could be placed in a private configuration file, but for the sake of simplicity we put it in Web.Config.

 

That would be all. I hope this will make localization dilema a bit easier.

 

Regards,

Tonci Jukic

Revision number 1, Monday, July 07, 2008 2:01:03 PM by tjukic

Comments

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter