Click here to Skip to main content
Licence CPOL
First Posted 7 Jul 2008
Views 12,519
Downloads 69
Bookmarked 14 times

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

By | 7 Jul 2008 | Article
This article will guide you through a fast and practical way to integrate localization within the Page class.

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

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralBest Localization Plug-in for Visual Studio. PinmemberAlexander Nesterenko21:44 17 Dec '08  
Generalsimply the best Pinmembergunalorsel7:05 29 Jul '08  
General[Message Removed] PinmemberMojtaba Vali18:27 7 Jul '08  
AnswerRe: good article PinmemberTonci Jukic19:07 7 Jul '08  
QuestionWhy not just use what the .NET framework already provide? Pinmemberleppie2:48 7 Jul '08  
AnswerRe: Why not just use what the .NET framework already provide? [modified] PinmemberTonci Jukic3:00 7 Jul '08  
GeneralRe: Why not just use what the .NET framework already provide? Pinmemberleppie5:49 7 Jul '08  
GeneralRe: Why not just use what the .NET framework already provide? PinmemberTonci Jukic6:17 7 Jul '08  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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