Localizing a custom web control in ASP.NET

Localization in custom web controls are needed when we would want to change default text according to some localized language. This allows the developers to create resource satellite assemblies and deploy as a multi-lingual website. In this post, we would look into creating one such localized button whose text is determined based on the language selected.

Create a resource manager –

  • We need a resource manager to read from embedded resource. I have named my resources in the FControls project as “SR”, and so
    • My resource class would be sr.cs
    • My resource text file would be sr.txt
    • My resources generated file would be sr.resources
  • Code snippet for the sr class,
   1: public class SR
   2: {
   3:     private ResourceManager resources;
   4:
   5:     public SR( ) {
   6:         this.resources = new ResourceManager( this.GetType( ) );
   7:     }
   8:
   9:     private static SR _managerDefault = null;
  10:     /// <summary>
  11:     /// Gets the default SR static instance.
  12:     /// </summary>
  13:     /// <value>The default.</value>
  14:     public static SR Default {
  15:         get {
  16:             if ( _managerDefault == null )
  17:                 _managerDefault = new SR( );
  18:             return _managerDefault;
  19:         }
  20:     }
  21:
  22:     /// <summary>
  23:     /// Gets the string from the resource manager.
  24:     /// </summary>
  25:     /// <param name="culture">The culture.</param>
  26:     /// <param name="name">The name.</param>
  27:     /// <param name="args">The args.</param>
  28:     /// <returns></returns>
  29:     public string GetString( CultureInfo culture, string name, params object[] args ) {
  30:         string value = this.resources.GetString( name, culture );
  31:         return string.Format( value, args );
  32:     }
  33:
  34:     public string GetString( string name ) {
  35:         return this.GetString( null, name );
  36:     }
  37:
  38:     public string GetString( string name, params object[] args ) {
  39:         return this.GetString( null, name, args );
  40:     }
  41:
  42: }

How to use the resource manager –

  • Define your constants in a sr.txt file. In our example, we are going to have a button whose text is localized.
  • Create a sr.txt file and add it to the project,

sr.txt

  • Then add the text values that you would expose for localizing. In our FButton, I have kept the localizing string as “ButtonText”. Enter that string in the sr.txt file as,
    • ButtonText = Click Me!!

Generate the resources file using resgen –

  • We need to create a resources file that would enable our resource manager to read the localized strings,
  • Enter the following command in your VS2005/VS2008 command prompt,
    • resgen sr.txt sr.resources.resources
  • This would create a resources file. Include that in your project.

Use the resource value in your control –

  • We would be adding a button control whose text is a localized string. Check out the following code snippet,
   1: protected override void CreateChildControls( ) {
   2:            this.Controls.Clear( );
   3:            Button btn = new Button( );
   4:            btn.Text = SR.Default.GetString( FLocButtonConstants.ButtonCaptionText );
   5:            if ( !this.Width.IsEmpty )
   6:                btn.Width = this.Width;
   7:            else
   8:                btn.Width = new Unit( 100 );
   9:            if ( !this.Height.IsEmpty )
  10:                btn.Height = this.Height;
  11:            this.Controls.Add( btn );
  12:        }
We now have a button control that is localized. Now lets create a website project and demo our localization in different languages.
  • Create a default website project.
  • Point your output directory of the library project to the website’s bin directory. This would make your website project refresh whenever you make a change in the control library ( just a quick way to check out ).

sshot-2

  • Once everything is set, we can use our FLocButton in our webpage,
   1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
   2:
   3: <%@ Register Assembly="FControls" Namespace="FControls" TagPrefix="FControls" %>
   4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   5: <html xmlns="http://www.w3.org/1999/xhtml">
   6: <head runat="server">
   7:     <title>Localization demo on Custom web controls</title>
   8: </head>
   9: <body>
  10:     <form id="form1" runat="server">
  11:     <div>
  12:         <FControls:FLocButton Width="100px" Height="50px" ID="Btn" runat="server" />
  13:     </div>
  14:     </form>
  15: </body>
  16: </html>
  • Running this sample, would turn up a page with a button and a text saying “Click Me!!”. Since we are rather interested in getting the localized string into the button. We would directly see how to create one such.
  • Add a couple of resource files named in any directory as you would wish to,

sshot-3

  • We have a “de-DE” and “fr-FR” named resources added up. Inside the resource file just name the resource string id and its corresponding value that you would want to show up when the UICulture is set. Shown below is a resource string set for “German / de-DE” culture.

sshot-4

Code to localize –

  • To set the UICulture use the following code,
   1: /// <Summary>
   2: /// Sets the current UICulture and CurrentCulture based on
   3: /// the arguments
   4: /// </Summary>
   5: /// <PARAM name="name"></PARAM>
   6: /// <PARAM name="locale"></PARAM>
   7: protected void SetCulture( string name, string locale ) {
   8:     Thread.CurrentThread.CurrentUICulture = new CultureInfo( name );
   9:     Thread.CurrentThread.CurrentCulture = new CultureInfo( locale );
  10: }
  • We need to override the InitializeCulture() function in the Page to set the UICulture for the page. In our application, it has a DropDownList, through which we would want the UICulture to set on each postback,
   1: protected override void InitializeCulture( ) {
   2:     if ( Request["__EVENTTARGET"] != null ) {
   3:         string controlID = Request["__EVENTTARGET"];
   4:         if ( controlID != string.Empty ) {
   5:             string selectedValue =
   6:                    Request.Form[Request["__EVENTTARGET"]].ToString( );
   7:
   8:             switch ( selectedValue ) {
   9:                 case "0": SetCulture( "de-DE", "de-DE" );
  10:                     break;
  11:                 case "1": SetCulture( "fr-FR", "fr-FR" );
  12:                     break;
  13:                 default: break;
  14:             }
  15:         }
  16:     }
  17:     base.InitializeCulture( );
  18: }
  • If you execute the page, the results would be as follows,

sshot-5

  • The zipped version of the sample can be found here.

That’s it!!, we have the strings localized.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: