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

Changing web application Culture on the fly

, 7 Mar 2005
Rate this:
Please Sign up or sign in to vote.
This article describes a solution for how to select web application cultures manually.

Introduction

This article describes creating the user interface for manual selection of web application cultures. The idea of the article is to help web application developers implement support for multiple cultures without great effort. The presented solution could be easily integrated into existing web applications.

One possible solution

In principle, the web browser contains a collection of supported cultures. We would be able to access this collection using HttpRequest.UserLanguages. This way, the application culture will be set automatically using the web browser settings. Here is an example of the solution:

using System.Globalization;
using System.Threading;

private void Page_Load(object sender, System.EventArgs e)
{
    Thread.CurrentThread.CurrentCulture = 
        CultureInfo.CreateSpecificCulture(Request.UserLanguages[0].ToString());
    Thread.CurrentThread.CurrentUICulture = 
        new CultureInfo(Request.UserLanguages[0].ToString());

    lblToday.Text = Today;

    lblMessage.Text = "Culture Info Display Name " + 
                      Thread.CurrentThread.CurrentCulture.DisplayName;
}

Solution

The solution described above has one disadvantage: the user can not make his own decision as to which culture to use. It is more user friendly to allow users select which application culture they want to use. The idea is to provide some interface to the application users which could be used to select the application cultures.

Implementation of the solution

First, we should determine which application culture is selected by the user. Second, we should change the application culture. In the web application, we need persist the selected culture and set it again in postbacks.

I am using the HTTP handler to handle the application culture requests. Using of this approach helps creating a flexible architecture; we can easily enable/disable the HTTP handler from the web application configuration file. I created the LanguageHandler class that implements the IHttpHandler and IRequiresSessionState interfaces. The ProcessRequest method of LanguageHandler class processes the HTTP request, extracts the selected culture identifier, and sets the selected culture to the user's session. After the HTTP request is handled, it is redirected to the referrer page. The IRequiresSessionState interface must be implemented in order to allow access to the web application state (session).

public void ProcessRequest(HttpContext context)
{
    HttpRequest request = context.Request;
    HttpResponse responce = context.Response;

    int nLanguageID = 0;
    try
    {    
        nLanguageID = Convert.ToInt32(request.QueryString[
                                           Constants.QUERY_LANGUAGE_PARAM]);
    }
    catch(Exception ex)
    {
        Debug.Assert(false, ex.ToString());
        return;
    }
    
    switch (nLanguageID)
    {
        case Constants.LANGUAGE_GERMAN:
            LanguageHandler.SetLanguage(context, Languages.German);
            break;
        case Constants.LANGUAGE_ENGLISH:
            LanguageHandler.SetLanguage(context, Languages.English);
            break;
        case Constants.LANGUAGE_BULGARIAN:
            LanguageHandler.SetLanguage(context, Languages.Bulgarian);
            break;

        default:
            Debug.Assert(false, "Unsupported language enumeration.");
            return;
    }

    // Redirect to the original web page.
    responce.Redirect(request.UrlReferrer.AbsolutePath);            
}

Using the code

Copy compiled file to bin directory

Put the Utilities.dll to your application bin directory. In your code, add the following directive:

using Utilities;

Change the application configuration

To use the code in your application, you should change the application configuration in Web.config file as shown below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!--<span class="code-comment"> Allow all users access the LanguageHandler.aspx. --></span>
    <location path="LanguageHandler.aspx">
        <system.web>
            <authorization>
                <allow users="*" />
            </authorization>
        </system.web>
    </location>

    <system.web>
        <httpHandlers>
            <add verb="*" path="LanguageHandler.aspx" 
                 type="Utilities.LanguageHandler, Utilities" />
        </httpHandlers>
    </system.web>
</configuration>

The <location> tag is very important, because there are situations in which the application user is not authenticated yet, but in the same time he/she should be able to change the application culture.

Define language selection controls

Define your own web controls that will represent the language selectors. For example, you can use an anchor tag (<a>):

<a href="LanguageHandler.aspx?LanguageID=2" class="languages">English</a>

You can also use picture instead of text, just change the anchor tag to use picture, something like this:

<a href="LanguageHandler.aspx?LanguageID=2" class="languages">
<img src=”[PATH TO YOUR IMAGE]” border=”0”></a>

Load the current application language

In your web page(s), on Load event, add the code below:

private void Page_Load(object sender, System.EventArgs e)
{
    LanguageHandler.SetLanguage(this.Context, 
                                 LanguageHandler.GetLanguage(this.Context));
    …
}

This code gets the current application language value from the user session and sets the current thread culture.

Loading of language-depended texts

To load the language-depended texts, you can use System.Resources.ResourceManager class from the .NET framework. To use this class, you need do some preliminary work. I created a class that includes several helpful methods. As a base for this class, I used "How to read satellite assembly resources in ASP.NET" article created by Adrian Tosca. You can use this class to load the language-depended texts from the resource assembly.

Let's assume that we have a <asp:Button> control named btnUpdate. Then to load the language-depended button caption, the GetString method of ResourceHandler class should be used. The parameter of the GetString method is a resource identifier.

this.btnUpdate.Text = ResourceHandler.GetString("btnUpdate");

If the GetString method could not load the resource string then the [?:[RESOURCE IDENTIFIER]] formed string is returned. This helps to determine which resource identifier value is not defined.

Note that before using of the ResourceHandler.GetString method, you should change the Global.asax.cs as shown below:

protected void Application_Start(Object sender, EventArgs e)
{
    // Initialize application resources.
    // assemlyString: The long form of the assembly name.
    // baseName: The root name of the resources. 
    // In your application you should
    // change the ResourceHandler.InitializeResources
    // parameters to your resource assembly name.
    ResourceHandler.InitializeResources("ChangeCultures", 
                        "ChangeCultures.ChangeCultures");
}

protected void Application_End(Object sender, EventArgs e)
{
    // Release application resources.
    ResourceHandler.ReleaseResources();
}

Using ResourceHandler class from the *.aspx pages

To use the ResourceHandler class from the *.aspx pages, you need to import the ResourceHandler namespace. For this purpose, use "Import" directive:

    <%@ Import Namespace="Utilities" %>

To load the language-depended texts, use the following code:

    <%= ResourceHandler.GetString("Login_UserName") %>

Demo

Installation of the demo application

Download and extract the demo application to your local file system. It is recommended to be used this path: C:\Inetpub\wwwroot\ChangeCultures. Configure the virtual directory with ChangeCultures name to point to the demo application directory.

Languages.ascx web control

This web control contains links to the language handler. For example, the following code sets the English culture:

<a href="LanguageHandler.aspx?LanguageID=2" class="languages">English</a>

Using the web control simplifies support of the application cultures: you can simply declare the web control on the web page, as shown below:

<%@ Register TagPrefix="Custom" 
      TagName="LanguagesControl" Src="controls/Languages.ascx" %>
...
<Custom:LanguagesControl id="ctrlLanguages" runat="server" />

History

  • 22/02/2005 - First version of the article.
  • 27/02/2005 - Second version of the article.
  • 06/03/2005 - Third version of the article. The demo application added and some corrections made.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Nikolai Serdiuk
Web Developer
Bulgaria Bulgaria
I am a senior developer in Melon Technologies Ltd.
 

Comments and Discussions

 
GeneralHelp Pinmembersreejith ss nair18-Sep-05 21:33 
GeneralRe: Help PinmemberNikolai Serdiuk20-Sep-05 9:46 
GeneralRe: Help Pinmembersreejith ss nair20-Sep-05 19:24 
GeneralMe.Culture PinmemberJasonBSteele7-Mar-05 22:41 
Questiondemo zip is empty? Pinmemberwingi5-Mar-05 15:15 
AnswerRe: demo zip is empty? PinmemberNikolai Serdiuk5-Mar-05 21:48 

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.

| Advertise | Privacy | Mobile
Web04 | 2.8.141022.2 | Last Updated 7 Mar 2005
Article Copyright 2005 by Nikolai Serdiuk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid