Wednesday, November 28, 2012

Creating multilingual websites

  • To create a multilingual application we need .resx (Resource) file.
  • The .resx file is an XML file, which contains Name and a value.
  • The value in the resource file is substituted at run-time.
  • The file name of the resource file should be name of the aspx file.
e.g. if our aspx file name is Test.aspx, then our resource file name should be Test.aspx.resx(Default resource file for the aspx file).
Test.aspx.en-US.resx (aspx file Name.Culture.resx)

To view the code inside the resx file, Right-click -> View Code

Home US

The data tag contains the string and the value.

To set the culture to the controls and to select the correct resource file we have to set the propertis Culture and UICulture

This two properties are available form the class System.Web.UI.Page

How to attach this value to the server controls?

Import the library
  • System.Threading
  • System.Globalization
There are two types of Asp.Net Folders
  • App_LocalResources
  • App_GlobalResources
App_LocalResources
Resource files for each aspx file
The resource file is embeded with the dll file.
App_GlobalResources
Global resource can be read from any page or code that is in the application.
If we are having some text, which is repeated in most of the pages, have the key and value.

Naming conversion for the resource file
<pagename>.aspx.<language>.resx

Type 1:LocalResources
Implicit coding for App_LocalResources

in the page directive add
Culture="auto:en-US" UICulture="auto"

meta:resourceKey="Label1"
in resx file, we have it as Label1.Text as the key name.

meta:resourceKey is called as ambient language

By default our default language is English
How change the language in Browser Settings
Internet Options -> Languages -> Add -> Chinese [Simplified]
Change the default order

If we are having a Label control, and how can we apply localization,
<asp:Label ID="Label1" runat="server" Text="Label" ForeColor="green"></asp:Label>
<asp:Label ID="Label1" runat="server" meta:resourceKey="Label1"></asp:Label>

In the resx file the name of each property is noted as ControlID.Property



Type 2:App_GlobalResources
App_GlobalResources

Select control -> Press F4 -> Expression -> Text -> Expression Type -> Resource -> ClassKey=Resource,

ResourceKey = We can do this only for the GlobalResources

Title="<%$ Resources:PageTitle %>"

Type 3:Dynamically change the language
Import the library
System.Threading
System.Globalization

Override the page method called InitializeCulture
This is the place where we have to set the culture.

protected override void InitializeCulture()
    {
        string language = Request.Form["ddlLanguage"];
        if (!String.IsNullOrEmpty(language))
        {
            Culture = UICulture = language;

            //For selecting the resource file for the languate
            Thread.CurrentThread.CurrentCulture = new CultureInfo(language);

            //For date and currencies
            //Language + Location => Locale
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);

            WriteCookie("CultureInfo", language);
        }
        base.InitializeCulture();
    }


public void WriteCookie(string name, string value)
    {
        HttpContext.Current.Response.Cookies.Set(new HttpCookie(name, value));
    }

    public string ReadCookie(string name)
    {
        return Request.Cookies["CultureInfo"] != null ?
            Request.Cookies["CultureInfo"].Value : null;
    }

    //This is not needed, since it will be set in the InitializeCulture()
/*
    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        WriteCookie("CultureInfo", ddlLanguage.SelectedValue);
    }
*/

To get the current culture
System.Globalization.CultureInfo currentCulture = 
System.Threading.Thread.CurrentThread.CurrentCulture;

To change the currency symbol
String.Format("{0:c}", 1000.2);

How to get the currency symbol according to the languagecode
Get Currency Symbol by Language-code

How to get the value from a resource file in code behind
private string GetMessage(string resourceKey)
    {
        return Convert.ToString(this.GetLocalResourceObject(resourceKey));
    }

How to get the value from a resource file in JavaScript
alert('<%= Convert.ToString(this.GetLocalResourceObject
("AlertLocationOrCustomer"))%>');

How to get the value from a resource file in DropDownList/ListBox asp:ListItem
-Select-

Error

//If no any resource file available
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Test.aspx.resources" was correctly embedded or linked into assembly "App_LocalResources.root.uhdc5eth" at compile time, or that all the satellite assemblies required are loadable and fully signed.

Title="<%$ Resources:PageTitle %>"
Error parsing attribute 'title': The resource object with key 'PageTitle' was not found.
  • If there is no default resx file.
  • If there is no resx file for the aspx file.
  • If the aspx file in a sub-folder then we have to create a App_LocalResources in side the sub-folder and create the resx file.

How do I localize the column headers in a gridview?
Curtesy
In your bound field add resource key like this:
In your resource file you need to add a key with name

Product.HeaderText and in Value = ????
Similarly you can do the same for footer

Product.FooterText and in Value = ????

How to localize in external javascript file
In the master page add the hidden control.

In the code behind of the master page set the current langauge.
hdnLang.Value = SessionProxy.Search.Language.ToLower();
eg: for, how to localize in external javascript file?
var locale = ($('#ctl00_hdnLang').val() || "en-us");
var show = { "zh-cn": "顯示", "en-us": "Show" };
var hide = { "zh-cn": "隱藏", "en-us": "Hide" };

$('img.image-selector').toggle(
    function () {
        $(this).attr('src', '../images/Show.JPG');
        $(this).attr('title', show[locale]);
    },
    function () {
        $(this).attr('src', '../images/Hide.JPG');
        $(this).attr('title', hide[locale]);
    }
);
Understanding Globalization and Localization in .NET
Using Resources for Localization with ASP.NET
Extending the ASP.NET 2.0 Resource-Provider Model

Asp.net 3.5 Application Architecture and Design- Chapter 9 Localization

Get Currency Symbol by LanguageCode

Friday, November 9, 2012

Setting minDate and maxDate for jquery datepicker

$(function () {
    var dateToday = new Date();
    var startDate = new Date(dateToday.getFullYear(), 
                 dateToday.getMonth(), dateToday.getDate() - 30);
    $("#txtFromDate").datepicker({
        minDate: startDate,
        maxDate: dateToday
    });
    $("#txtToDate").datepicker({
        minDate: startDate,
        maxDate: dateToday
    });
});