Dongle for testing and supporting multiple languages (cultures) Web Sites

If you ever tried testing a web-site in different languages you know the pain of having to monkey with browser settings. The trick below shows an easy way to test different languages without changing browser settings.  The mechanism is to add a parameter to the request that will toggle the request to a different culture and persist it via a cookie.

In Global.asax

This location is needed because it must happen before any processing starts or you may end up with a mixed language page.  It also makes it very clean because it applies to every page and request.

 

void Application_BeginRequest(object sender, EventArgs e)
{

    string ci = "ci";
    if (!String.IsNullOrEmpty(Request[ci]))
    {
        try
        {
            
            System.Globalization.CultureInfo requestedCulture = System.Globalization.CultureInfo.GetCultureInfo(Request[ci]);
            System.Threading.Thread.CurrentThread.CurrentCulture = requestedCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = requestedCulture;

            HttpCookie cookie = new HttpCookie(ci, requestedCulture.Name);                
            cookie.Expires = DateTime.Now.AddMonths(3);                
            Response.Cookies.Add(cookie);
        }
        catch (Exception exc)
        {
            ErrorLogging.AddError(exc);
        }
    }
    else if (Request.Cookies[ci] !=null)
    {
        try
        {
            if (string.IsNullOrEmpty(Request.Cookies[ci].Value))
            {
                System.Globalization.CultureInfo requestedCulture = System.Globalization.CultureInfo.GetCultureInfo(Request.Cookies[ci].Value);
                System.Threading.Thread.CurrentThread.CurrentCulture = requestedCulture;
                System.Threading.Thread.CurrentThread.CurrentUICulture = requestedCulture;
            }
        }
        catch (Exception exc)
        {

            ErrorLogging.AddError(exc);
        }
    }
}

Further more, on a login page you could ask what language they wish and set the cookie from this value. The nice thing is that when they return to the site next time they will get the page in the requested language (assuming the same browser) because the cookie is persisted.

Testing different languages is now trivial,  http://localhost/home.aspx?ci=fr-CA  will set the site to French-Canadian for the next 3 months unless you change the language. You can also give the user a choice of language without having to detect and use the browser settings.

Comments

Popular posts from this blog

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

Yet once more into the breech (of altered programming logic)

How to convert SVG data to a Png Image file Using InkScape