Click here to Skip to main content
Click here to Skip to main content

How to: ASP.NET web localization by extending the Page class

By , 7 Jul 2008
 

Localization

Localization is often required on the web. For that reason, .NET framework includes localization support through the 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 localization available to your web pages and making the system fit to user preferences.

The goal of this article is to provide one of the solutions for a clean and easy implementation of the localization system using the 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 a language selection menu.

Using the code

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

First, we will need to include some additional namespaces and assembly references. The project is built using the 2008 version of Visual Studio and C# 3.0 (and .NET 3.5).

using System;
using System.Configuration;
using System.Web;
using System.Globalization;
using System.Threading;

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

Now, we override the InitializeCulture method:

public class Page : System.Web.UI.Page
{
    // 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 that is required to implement internal localization support for the page. Now, we should actually use it inside a website.

Using the custom Page class to localize a website

Just create a default website and add the previously created class library as a reference. In 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 the built-in resource file based localization, thus we will create Default.aspx.resx files for all the languages we need.

Now, we will programmatically create a language selection menu using the 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:

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));
}

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:

Tips

The point of this code is to give direct control over the settings for each specific user and also to enable Web Forms (pages) to automatically "understand" the URI language setup and combine it with the saved info.

This enables the pages for further processing like a storing system for more per-user settings and also for URL rewriting of the language settings control. One of the other features is also a system that specifically can enable or disable some of the already present translated resources and which can also be used for menu system generation in a very simple way.

Using this system, you are now able to easily extend supported languages and have user language preferences always stored in cookies.

This system can easily be extended according to your needs like many things here, like exception handling and settings storage. Some ideas have been removed here for the sake of simplicity.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Tonci Jukic
Technical Lead
Croatia Croatia
Member
Software architect and developer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralBest Localization Plug-in for Visual Studio.memberAlexander Nesterenko17 Dec '08 - 21:44 
Generalsimply the bestmembergunalorsel29 Jul '08 - 7:05 
General[Message Removed]memberMojtaba Vali7 Jul '08 - 18:27 
AnswerRe: good articlememberTonci Jukic7 Jul '08 - 19:07 
QuestionWhy not just use what the .NET framework already provide?memberleppie7 Jul '08 - 2:48 
AnswerRe: Why not just use what the .NET framework already provide? [modified]memberTonci Jukic7 Jul '08 - 3:00 
GeneralRe: Why not just use what the .NET framework already provide?memberleppie7 Jul '08 - 5:49 
GeneralRe: Why not just use what the .NET framework already provide?memberTonci Jukic7 Jul '08 - 6:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 7 Jul 2008
Article Copyright 2008 by Tonci Jukic
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid