Creating Multilingual Websites

xiaoxiao2021-03-06  65

IntroductionDeveloping websites to support multiple languages ​​can be a challenging and time-consuming process. With standard HTML pages this involves creating and maintaining duplicate versions of each page for each supported language as well as having the language content embedded into the HTML, where content can Yang easily be edited. While the process improved slightly with the introduction of scripting technologies such as ASP and PHP, no significant development or maintenance time was saved. For those of you who have to develop multi-lingual interfaces and applications, you Yun l be glad TO KNOW THAT ASP.NET MAKES Things ConsideRably Easier.

ASP.Net and the .Net framework ship with support for multilingual applications, namely in the form of Resource Files, the CultureInfo class and the System.Globalization and System.Resources.ResourceManager namespaces. Unfortunately in its present state, localizing content in ASP. . Net applications is still a tedious process Like everything else .Net though, the object model and sheer power available makes extending what's already available and developing new functionality to support better localization easy as 1 - 2 - 3.

In this First Part, We'll Develop a Custom Resource Manager Which Avoids The Limitation of .NET Assembly Resource Files As Well AS Extend A Number of Classes To Easily Support localization. In The

SECOND PART WE 抣 L Spend More Time Talking About Creating Multilingual Applications, Specify Looking At Database IMPLEMENTATIONS AND TECHNIQUES.

................ ..

Before we get startedIf you are not familiar with localization in .Net, do not worry. This tutorial mostly skips what's available in .Net and talks about alternatives to make the job easier. There are a couple core principals you should know though. (Even if you don't know the basic, you can Skip this section anddownload the simple application I've create, playcase the core functionality, Playing with it to undrestand)

BasicsThe way localization works in .Net is fairly straightforward. Content is stored in a pretty simple XML files called Resource Files. You create a Resource File for each supported language (more can be added later on). When the application is compiled, the resource files are embedded into assemblies - the default resource file is embedded in the main assembly (.dll file), language-specific resource files are embedded into their own assemblies called satellite assemblies Resource files are pretty simple and look a lot like a Hashtable,. they have a name and a value - the name is the same for all resource files, and the value is a language specific translation of some content In essence, this allows you to use the System.Resources.ResourceManager class to do things like:.

1: Usernamelabel.text = myResourceManager.getstring ("username");

2: UsernamevaliDator.ErrorMessage = MyResourceManager.getstring ("RequireduserName");

.. The resource manager will automatically load the right resource file based on the current thread's CurrentCulture value - more on this in the next section Hopefully you are already seeing a lot of potential Some of the key highlights are:

Content is separated into simple XML files There's a separate XML file for each supported language The code to load values ​​is relatively simple and short The ResourceManager class automatically retrieves the content from the right XML file based on the thread's CurrentCulture value You can easily have 1 actual page, for N supported languageCulturesIt's important to have a good understanding of Cultures since our new code will make use of them -. specifically the System.Globalization.CultureInfo class and the culture name value which follows the RFC 1766 naming standard Basically, you create a New CultureInfo Instance By Specifying The Culture Name in The Constructor:

1: CultureInfo C = New CultureInfo ("En-US"); // Creates a CultureInfo Instance for American ENGLISH

2: CultureInfo C = New CultureInfo ("en-au"); // Creates a CultureInfo Instance for Australian ENGLISH

3: CultureInfo C = New CultureInfo ("HE-IL"); // Creates a CultureInfo Instance for Israel Hebrew

Once you have a CultureInfo instance, you can set the current thread's UIculture to it, which will make your ResourceManager in the above code automatically fetch the content from the right XML resource file.

1: CultureInfo C = New CultureInfo ("En-US"); // Creates a CultureInfo Instance for American ENGLISH

2: system.threading.thread.currentthread.currentculture = c; // Will Automatical format Dates and Such

3: system.threading.thread.currentthread.currentuicultunicuicultuicultuicultuicultuicultuicultuicultuicultuicultuicultuicultuicultuiculture = C; // buy by the resourcemanager to get the correct XML file

In

part 2 we'll discuss ways to figure out which culture to load, but for now, it can be as simple as passing a code in the QueryString. For example, when lang = f is present, the French Canadian culture should be used. The other key factor is where to do all of this. The simplest and most logical place is in the Global.Asax's Begin_Request.Download dummy applicationThe best way to understand the basics is to play with some code. I've created an extremely basic VB .NET Web Application To DemonStrate The Basic Principals. Download It and Play IT. Look at The Structure of The 3 Resource Files, The Codebehind for Index.aspx, And The Code in Global.asax.

Download

?. Why not use what's available as-is While it's certainly possible to develop a multilingual application with the tools provided with ASP.Net, there are a number of limitation which make the task less than streamlined Some of the key problems are:

Resource files are embedded into [satellite] assemblies Resource files can not return strongly-typed objects Web controls are not easily hooked with resource files While the list might seem small, the above three issues can be quite serious - with the first being the . worst For example, since resource files are embedded into assemblies, its very difficult to ship a product which provides the client with the flexibility to change the content -. a feature offered by many products At my previous job, every time the translation department wanted To change some text, we'd need to recompile the entire application, Stop 20 Web Servers and copy the .dll into the bin folder - a frustrating process.

Building a better Resource ManagerOur first task is to build a better Resource Manager which will not cause our Resource Files to be embedded into assemblies. This will allow Resource Files to be easily edited in a production or client environment. Our core functionality will be located in three functions: The public method GetString which is used throughout the application to access the required resource The private method GetResource which gets a Hashtable either from the cache or by calling LoadResource The private method LoadResource which parses the XML file and stores it into the cache

GetString ()

1: Public static string getString (String Key) {

2: Hashtable message = getresource ();

3: IF (Messages [key] == null) {

4: Messages [key] = String.empty;

5: #if Debug

6: Throw New ApplicationException ("Resource Value Not Found for Key:" KEY);

7: #ENDIF

8: }

9: Return (String) Messages [key];

10:}

THE METHOD Accepts a Single Argument, The Key of The Resource We Want To Get. It Then Retrieves a Hashtable of Content Using

GetResource, which is culture-aware and returns us the correct Hashtable. If the requested key doesn Yang exist, we Yun l throw an exception if the application is in DEBUG mode, else we Yun l simply return an empty string.

GetResource ()

1: private static hashtable getresource () {

2: String currentculture = currentculturename;

3: String defaultculture = localizationConfiguration.getconfig (). Defaultculturename;

4: String cachekey = "localization:" defaultculture ':' currentculture;

5: IF (httpruntime.cache [cachekey] == null) {6: hashtable resource = new hashtable ();

7:

8: LoadResource (Resource, Defaultculture, Cachekey);

9: IF (defaultculture! = Currentculture) {

10: Try {

11: LoadResource (Resource, Currentculture, Cachekey);

12:} catch (filenotfoundexception) {}

13:}

14:}

15: return (hashtable) httpruntime.cache [cachekey];

16:}

The GetResource () method is slightly more complicated. Its goal is to retrieve a Hashtable which can be looked up by a key to retrieve a value. The method will first look to see if the Hashtable has already been loaded and cached

[Line: 5]. if So, IT Simply Returns The Value from the cache. Otherwise it will use loadingResource () to Parse the appropriate XML File

[Lines: 6-13].. Something worthy of noting is that the "appropriate XML file" is actually a mix of the XML file for the current culture as well as the one for the default culture The default culture is specified in the configuration File

[Line: 3], And The Current Culture Is Retrieved from The Current Thread's Current Culture

[line: 2].

First The Default Culture Is loadinged

[Line: 8], And the Current Culture Is Loaded

[Line: 11]. This means if a key is defined in both XML files (which most should be), the default value will be overridden by the culture-specific value But if it doesn Yang exist in the culture-specific value,. The default value will be used.

LoadResource ()

1: Private Static Void LoadResource (Hashtable Resource, String Culture, String CacheKey) {

2: String file = localization.getconfig (). LanguageFilePath '//' culture "//Resource.xml"; 3: XmLDocument XML = New xmlDocument ();

4: Xml.Load (file);

5: Foreach (XMLNode N in Xml.selectsinglenode ("resource")) {

6: if (nodettype! = XMLNODETYPE.COMMENT) {

7: resource [n.attributes ["name"]. Value] = n.innerText;

8: }

9: }

10: httpruntime.cache.insert (cachekey, resource, new cachedependency (file), datetime.maxvalue, timeespan.zero;

11:}

LoadResource Loads The XML file

[Line: 4] (It gets the root path from our configuration file

[Line: 2]) And Simply Parses It While Loading The VALUES INTO OUR HashTable

[Line: 5 - 9]. Finally, The Hashtable Is Stored in The Cache

[line: 10].

Other enhancements

WrappersThere are a number of minor enhancements which can be done to our ResourceManager class. For example, I build bilingual webpages in English and French. Annoyingly, in English a colon is always glued to the word it follows, but in French there has to be a space. for example:

Username: // 中文 g

NOM d'utilisateur: // French

This Means The Colon Needs to Be Localized. Instead of Using The getString () Method, We CAN SIMPLY Build A Wraper:

1: Public static string colon {

2: Get {return getString ("colon");

3:}

IN OUR ENGLISH RESOURCE FILE The Colon Would Simply Be ':', while in the French ONE IT Would Have A Space ':'.

Strongly-typed resourcesThe reason we use Hashtable instead of a NameValueCollection is because the ResourceManager class can be expanded to return strongly-typed objects. For example, you might have localized help content which is more than just a single value. It might have a title , an example and the help text. While exploring this is beyond the scope of this article (perhaps a part 3 ??) the capability exists.Localized ControlsOur next goal is to make our life easier when developing a website by expanding existing server controls ( LITERALS, LABELS, Buttons to Be Localization-Aware. We beginning..........!!!!!!!!!!!!!!

ILocalize

1: Public interface ilocalized {

2: String key {get; set;}

3: bool colon {get; set;}

4:}

Ilocalized Defines A

Key property which will be passed to our ResourceManager's GetString () method. In order to show how you can expand these classes to fit your own needs, I've also included a Colon property as a boolean, which will tell our controls if they shoudl Append a colon at the end of their value.

Localizedliteral

1: Public Class Localizedliteral: Litral, Ilocalized {

2: #Region Fields and Properties

3: Private string key;

4: Private bool colon = false;

5:

6: Public bool colon {

7: Get {return colon;}

8: set {color = value;}

9: }

10:

11: Public string key {

12: Get {return key;}

13: set {key = value;}

14:}

15: #ndregion

16:

17:

18: Protected Override Void Render (HTMLTextWriter Writer) {

19: Base.text = ResourceManager.getstring (key);

20: IF (color) {21: base.text = resourcemanager.colon;

twenty two: }

23: Base.Render (Writer);

twenty four: }

25:}

The First Web Control That We'll Look at Making Localization-Aware IF The Off- Used

System.Web.ui.WebControls.literal. First We make it inherit from the literal control and inherit ou ilocalized interface

[Line: 1]. Next We Implement The Key and Colon Properties As Defined in The ilocalized interface

[Line 3 - 14]. Finally We override the render method of out u o r c 正品 正品 正品 正品 正品 店 0

[Line: 19 - 22]. don't forget to call the base class render () Method installs to let it work it ing it

[line: 23].

RINSE, WASH AND REPEATERYOU CAN CONSE AND PAST The Same Code over and over again and us ie inherits from, for example, let's do a localized button:

1: Public Class LocalizedButton: Button, Ilocalized {

2:

3: #Region Fields and Properties

4: Private string key;

5: private bool colon = false;

6:

7: public string key {

8: Get {return key;}

9: set {key = value;}

10:}

11:

12: Public bool colon {

13: Get {Return COLON;

14: set {color = value;}

15:}

16:

17: #ndregion

18:

19: Protected Override Void Render (HTMLTextWriter Writer) {

20: Base.text = ResourceManager.getstring (key);

21: IF (color) {

22: Base.text = ResourceManager.colon;

twenty three: }

24: Base.Render (Writer);

25:}

26:}

Notice that only the two bolded words have changed.When desired, you can expand the functionality. For example, it is not uncommon to have a LinkButton which pops up a JavaScript confirmation box when deleting something. We can easily achieve this by creating a 2nd Key Property:

1: Using System.Web.ui;

2: using system.web.ui.webControls;

3:

4: Namespace Localization {

5: Public Class LocalizedlinkButton: LinkButton, Ilocalized {

6: #Region Fields and Properties

7: PRIVATE STRING KEY;

8: Private bool colon;

9: private string confirmkey;

10:

11: Public string confirmkey {

12: Get {return.

13: set {confirmkey = value;}

14:}

15: Public string key {

16: Get {Return Key;}

17: set {key = value;

18:}

19: public bool colon {

20: Get {return colon;}

21: Set {color = value;

twenty two: }

23: #ndregion

twenty four:

25: Protected Override Void Render (HTMLTextWriter Writer) {

26: IF (key! = Null) {

27: Text = ResourceManager.getstring (key);

28: IF (color) {

29: Text = ResourceManager.colon;

30:}

31:}

32: IF (confirmkey! = Null) {

33: Attributes.Add ("OnClick", "Return Confirm ('" resourceManager.getstring (confirmkey) .Replace ("'", "/ '") ");");

34:}

35:

36: Base.render (Writer);

37:}

38:

39:}

40:}

Using Localized ControlsYou use the localized controls like any other server control First register the control on the page:. 1: <% @ Register TagPrefix = "Localized" Namespace = "Localization" Assembly = "Localization"%>

THEN, You CAN SIMPLY Add The Control Either by Drag and Dropping It in The Designer, or in the html mode by type:

1:

2:

DownloadThe best thing to do now is to play a bit with some code. I've again created a sample site (similar to the previous one), but this time using our new ResourceManager class and Localized controls. You might need to change the web .config's languagefilepath property to point to the right folder.

C # Download VB.NET Download

转载请注明原文地址:https://www.9cbs.com/read-110133.html

New Post(0)