Understanding Globalization and Localization in .NET

21 06 2008

Understanding Globalization and Localization in .NET

Now days as the audience for web applications has bursted from computers to pda’s, cell phones and many other gadgets, Globalization has become must for web application. Globalization allows your web application to be useful for different people in different parts of the world who speaks different languages.

Thanks to Microsoft .Net Globalization feature.

Using this feature one can easily build a web application available to dispersed audience throughout the world.

In this article I will walkthrough the steps that are essential for creating a multi cultured application. This example will include the use of Global and Local resource files that are heart for multi cultured web application.

ASP.Net supports two types of resources

Local Resource and Global Resource.

Both types of Resources are xml based resource files that can contain text translated into particular language

Local Resources:

Local resource is specific to particular webpage. All the resource files related to particular webpage must be placed in a special .Net folder named App_LocalResources. This folder must be in the same folder of the webpage that you want to localize. So App_LocalResources can be subfolder for any folder of your website.

Global Resources:

They are the resource files for the entire web application. They are not specific to any page. They can be accessed from the entire web application. Global resource files must be located in a special .Net folder named App_GlobalResources. App_GlobalResources must be at the root of the web application.

Steps to create local Resource file.

1) Switch to design view of the webpage for which you want to create the resource file.

2) Go to Tools menu and click Generate Local Resource.

3) As the result of step 2 .Net generates the .resx file.

Naming conventions that Resource files follow is as explained below:



myWebPage.aspx.resx: This is the default resource file of your page. If no culture matches than this resource file is used.

myWebPage.aspx.es.resx: For Neutral Spanish culture it may look like this.

myWebPage.aspx.es-MX.resx: For Specific Spanish Mexican culture it may look like this.

What do you mean by neutral and specific cultures? I leave this small exercise to readers.

Steps to create global Resource file.

1) Their are no specific utilities in .Net to generate Global resource files automatically. But you can create App_GlobalResources folder at root level and add a resource file manually Or you may copy the local resource file and change it at your will.

Ways in which you can Globalize or localize your application.

Implicit Localization

<asp:Label ID="lblLoadLocalResource" runat="server" 

Text="Local Resource" 




Implicit Globalization

<asp:Label ID="lblLoadGlobalResource" runat="server" 

Text="<%$ Resources:Resource, commonHeader %>" 

ToolTip="<%$ Resources:Resource, commonHeader %>">



Programmatic Localization

lblLoadLocalResource.Text = GetLocalResourceObject

lblLoadLocalResource.ToolTip = GetLocalResourceObject


Programmatic Globalization

lblLoadGlobalResource.Text = GetGlobalResourceObject
("Resource", "commonHeader").ToString();

lblLoadGlobalResource.ToolTip = GetGlobalResourceObject
("Resource", "commonHeader").ToString();



How to change the UI Culture?

Steps to check and configure the UI Culture of your webpage

1) To change it programmatically you need to override the InitializeCulture() of your web page.

protected override void InitializeCulture()
 UICulture = "en";


2) To change it implicitly from .aspx page Set

<%@ Page Language="C#" UICulture="en" %>

3)To change it globally from web.config file

 <globalization uiCulture="es"/>

Note: If you set UICulture=”auto” then .Net runtime will automatically detect the requesting browsers preferred language setting and will compile the related resource file for that culture. In this case you do not have to write a single piece of code for setting UICulture.

How to check this?

1) Open IE and go to Tools > internet Options

2) Click Languages tab.

3) This will open language Preference dialog box window.

4) Add the language by clicking the add button. Make sure to add the language for which you have configured the resource file of your web page.

5) Select the language that you have added and using Move Up button, bring it to the first topmost position in the language list.

6) Press Ok and again Ok to return.

Open your webpage in the browser and enjoy the taste of globalized web application.

I believe that few lines of code can speak thousand words and so I have prepared a small demo that includes both Globalization and Localization.

To download the entire source code Click Here.

Note: Globalizing the web application entirely, requires lots of other things like changing the Culture, formatting dates and currency and lot more. I will try to incorporate all this stuff in my next article.

Implementing ICallbackEventHandler in .Net 2.0

14 06 2008

Implementing ICallbackEventHandler in .Net 2.0 Custom Control. 

In this article I depict the use of ICallbackEventHandler with an example that shows random text generated from the server side code. For this purpose I have created a custom control named Show Tip.

How Show Tip control works.
Show Tip control renders the HTML button. Clicking this button initiates AJAX call to the server. The server processes the AJAX call raised from the client browser and returns the result. Lastly a JavaScript registered on the client browser displays the result in a DIV tag. The main motive behind this is to avoid the full page post backs. Show tip Button directly communicates with the server using “Sneaky Post back”.

How callbacks also known as “Sneaky Post back” actually work.
The main magic lies in the ICallbackEventHandler interface.By implementing this interface and some lit bit of code one can easily trap the events raised from Client Browser, on the server and can respond to such events.


Steps to use ICallbackEventHandler .

Step 1)Render the JavaScript on Client Browser that will initiate the AJAX call.
To create the JavaScript that initiates the AJAX call use Page.ClientScript.GetCallbackEventReference() method.

This method returns a string

This is the JavaScript function that is used to callback to the server.

The parameters used for GetCallbackEventReference() method are listed below.
1)  control – the control that initiates the AJAX call.

2) argument – the argument that is send to the server. In this example it is null as we are not passing any value back to server. But you can pass any value Example if you want to display price for the selected item from combo.

3) clientCallback – the name of the JavaScript function that executes after the result is returned from the server.

4) context – the argument that is passed back to the clientCallback() and clientErrorCallback() methods after the AJAX call completes . In this example it is null as we are not passing any value to client browser.

5) clientErrorCallback –  the name of the JavaScript function that executes on client browser if an error on the server occues during AJAX callback.

6) useAsync – pass false to perform the AJAX call asynchronously.


Step 2)Implement the methods of ICallbackEventHandler to handle the AJAX call.
ICallbackEventHandler has two methods that need to be implemented on the server side.
1) RaiseCallbackEvent – This method is called first on server by AJAX call from the client.
2) GetCallbackResult – This method Returns the result of the AJAX call to the client.


Step 3)Render the JavaScript on Client Browser that manipulates the result received from the server. To render the JavaScript on Client Browser use Page.ClientScript.RegisterClientScriptInclude(“ShowTip”, Page.ResolveClientUrl(“~/ClientScripts/ShowTip.js”)) method.
The parameters used for RegisterClientScriptInclude() method are listed below.
1) key – any string that represents the script instance name.
2) url – the path of the JavaScript file to register on the client browser that is called when results are returned from the server.


To download the entire example Click Here


ASP .Net 2.0 bundles some controls like Grid View, Tree View and Details View that use AJAX callbacks to perform some special tasks like
Grid View uses callback to perform AJAX based paging and sorting.
Tree View uses callback to perform AJAX based expansion of nodes.
Details View uses callback to perform AJAX based paging.
You will have to enable some property to do so. I leave this small exercise to the readers.

How to Paste HTML content in blogspot?

5 06 2008

Problem in pasting HTML content in your blog?

This is because all the blogs does not allow to directly use html in their content area due to security reasons.

The area for writing the content in Blogspot is commonly known as What You See Is What You Get (WYSIWYS) editor.

This WYSIWYG editor interprets the pasted HTML as true HTML. It will render exactly whatever you paste in it as HTML. This might spoil the look and feel of your blog.

Why this happens?

Special characters used for HTML language like <,>,”,& etc should be treated in special manner.
 < can be treated as <
 > can be treated as >
 ” can be treated as “e;
 & can be treated as &

So writing these special characters in this manner and pasting it in blog can solve your problem. But this may be a tedious task to perform manually.

So here is the solution for it.

Step 1) After making the below code working in .Net 2.0 copy the HTML you want to put in your blog and paste in the text area.

Step 2) Click Encode HTML button.

Step 3) 2nd step will generate the encoded html below the button.

Step 4) Copy the output from 4th step to your blog content (WYSIWYG) editor.

Following sample code converts HTML to Encoded HTML format using Code behind Modal in .Net.

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title>Encode HTML</title>
    <form id="form1" runat="server">
           <asp:TextBox ID="txtHTML" runat="server" Columns="75" Rows="10" TextMode="MultiLine"></asp:TextBox>     
           <asp:Button ID="btnEncode" runat="server" Text="Encode HTML" OnClick="btnEncode_Click" />
           <asp:Literal ID="litEncodedHTML" runat="server" Mode="Encode"></asp:Literal></div>



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)


    protected void btnEncode_Click(object sender, EventArgs e)
        litEncodedHTML.Text = Server.HtmlEncode(txtHTML.Text.Trim());




Those who are unaware of .Net they can use the same logic with their know language.

The main crux here is Server.HtmlEncode() method which transforms the HTML to encoded HTML.

How to Freeze Webpage while it is being processed in .Net 2.0 using AJAX?

4 06 2008

How to Freeze Webpage while it is being processed in .Net 2.0 using AJAX?
Blocking a webpage seems to be difficult task while the data on the page is being posted back to the server or it is being refreshed. It becomes tricky to track the postback and reloading of the page. Though this can be achieved by using Response.Flush() method but it requires some extra effort.

But thanks to AJAX Update Progress Panel.

Using Update Progress Panel its just the mater of putting it on the page. The real magic lies in this panel and the DIV tag inside it. The panel takes care of the events required during the page updation and the DIV blocks the page till the panel is active. The magic that actually blocks the page lies in the DIV tag. I leave this to readers to find the crux of the magic.

Following is the Code you can use to block the Webpage.

<ajax:UpdateProgress ID="UpdateProgress1" runat="server">
<div style="top: 0px; height: 1000px; background-color: White; opacity: 0.75; filter: alpha(opacity=75);
          vertical-align: middle; left: 0px; z-index: 999999; width: 1000px; position: absolute;
          text-align: center;"></div>

I have used simple DIV tag but it can be enhanced using an animated gif file or other custom JavaScript for showing loading image or processing time.

If you are using this code on the local server than AJAX might be so fast that the effect of this may not be visible.
So try to use this code where the server requires some time to process the request OR use Thread.Sleep(5000) on your page.

Sample Code Using Code Behind Modal:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WaitForRequest.aspx.cs" Inherits="WaitForRequest" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Wait For Request</title>
    <form id="form1" runat="server">
            <ajax:ScriptManager ID="ScriptManager1" runat="server">
            <ajax:UpdatePanel ID="UpdatePanel1" runat="server">
                    <asp:Button ID="btnGetDate" runat="server" Text="Get Date" OnClick="btnGetDate_Click">
                    <asp:Label ID="lblTime" runat="server"></asp:Label>
            <ajax:UpdateProgress ID="UpdateProgress1" runat="server">
<div style="top: 0px; height: 1000px; background-color: White; opacity: 0.75; filter: alpha(opacity=75);
                        vertical-align: middle; left: 0px; z-index: 999999; width: 1000px; position: absolute;
                        text-align: center;"></div>

using System;
using System.Threading;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class WaitForRequest : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
    protected void btnGetDate_Click(object sender, EventArgs e)
        lblTime.Text = DateTime.Now.ToString();