Resources and localization in ASP. NET 2.0

Source: Internet
Author: User
Tags file url net command
Released on: 2006-08-22 | Updated on: 2006-08-22

Ted Pattison

DownloadCode: Basicinstincts2006_08.exe (878kb)

This article discusses website localization in ASP. NET 2.0.

I assume that you are familiar with regional UI and regional settings, cultureinfo objects, resource files, ResourceManager classes, and automatically generated strongly typed resource classes. In addition, I also assume that you have a basic understanding of Microsoft. NET Framework from the defaultProgramSet, or determine whether to load resources from a localized satellite assembly. If you need more background information about these topics, read the basic instincts column I published in May 2006.ArticleAnd then continue reading this article.

Control page-level regional settings

ASP. NET 2.0 allows you to easily change the culture settings page by page. You only need to add the uiculture and culture attributes to the page commands on pages similar to. aspx.

 <%  @ page uiculture  = "   fr  "   Culture  = "   fr-be  "    %>   

In the early stages of the page lifecycle, A. ASPX page that runs with these attributes will use the appropriate cultureinfo object to initialize the currentuiculture and currentculture attributes of the current thread. During the test, if you add the property shown above to one. and then add a built-in ASP. net web control (such as the calendar control), you will immediately see that everything works normally, as shown in 1. The calendar control on the left is displayed on the page where the culture is set to en-us, and the calendar control on the right is displayed on the page where the culture is set to Fr-be.

Figure 1 localized calendar Control

However, in most production websites, it is not feasible to set hard encoding for specific regions to pages like this. Users in different languages will see different localized content on the same page. If you assign an "Auto" value to both the uiculture and culture attributes, ASP. NET will automatically initialize the culture settings for you based on each request.

 <%  @ page uiculture  = "   auto  "   Culture  = "   auto  "    %>   

ASP. NET initializes these settings by checking the HTTP headers sent by the browser. By changing the language preference settings in the Internet Options dialog box, you can test different localized versions of the page in Internet Explorer.

Generally, you want all the pages on the site to comply with the same regional settings. You can assign an "Auto" value for the site range for the uiculture and culture attributes, so that you do not have to allocate each page separately. Add the following elements to the Web. config file at the root of the site:

<GlobalizationUiculture= "Auto"Culture= "Auto" />

In addition to automatic settings, you can also specify a default culture for ASP. NET (if it cannot locate the HTTP title to determine the preferred culture for the user ):

<GlobalizationUiculture= "Auto: en"Culture= "Auto: En-us" />

Use the configuration file to track language preferences

Although automatic setting does make things easier, it is not always so convenient for users. For example, assume that a user is more willing to read technical websites in English and commercial websites in French. When he switches back and forth between two sites, he will be very upset when he needs to constantly change the browser settings. This user will like the website that allows him to select language preferences very much.

To learn how to generate a UI and support implementation that makes it easier for users to switch back and forth between different languages, download this month's code example-an ASP. NET 2.0 website named litwarewebapp. Its UI 2 is shown.

Figure 2a English version

Figure 2B localized version

The litwarewebapp site uses the new configuration file feature introduced in ASP. NET 2.0 to track users' language preferences. You can add a string-Based Configuration File Attribute named languagepreference to support anonymous identification by adding the following elements to the website's web. config file:

 <  Configuration  >  
< System. Web >
< Anonymousidentification Enabled = "True" />
< Profile >
< Properties >
< Add Name = "Languagepreference" Type = "String"
Defaultvalue = "Auto" Allowanonymous = "True"   />
</ Properties >
</ Profile >
</ System. Web >
</ Configuration >

The litwarewebapp site is designed to have a standard layout in the master page, which contains a radiobuttonlist control named lstlanguage. Note that this control not only displays friendly language names (such as American English and Belgian French ), the selectedvalue attribute is also used to trace the real regional names (such as en-US and FR-be ). When you change the language preferences, the selectedindexchanged event of the lstlanguage control will trigger and execute the following code to update the attributes of the languagepreference configuration file:

Profile. languagepreference = lstlanguage. selectedvalue
Response. Redirect (Me. Request. url. absolutepath)

If you call response. redirect will force a new round-trip from the browser to the Web server to restart the lifecycle of the page after the configuration file attribute is set using the required language preferences.

The next thing to do is to program and adjust the regional settings within the page lifecycle at the appropriate time. The correct way to perform this operation in ASP. NET 2.0 is to replace the page class named initializeculture. The page lifecycle has been designed to always call initializeculture before the page itself or any of its child controls use localized resources for any work.

The design of the sample site requires you to add a replacement initializeculture implementation to each page in the site. Unfortunately, you cannot replace the initializeculture method at the master page level because the masterpage class does not inherit from the page class. In addition, it is tedious to replace initializeculture with each page on the website. It will lead to many repeated implementations, leading to serious maintenance problems.

A more effective method for initializing the site range of the regional settings is to create a public page to derive the base class, and then let all. the ASPX page file inherits from this class. This is what I did in the litwarewebapp sample site. My page derived base class named litwarepage (see figure 3) is defined in the source file named litwarepage and has been added to the app_code directory, in this way, Asp. net automatically compiled and used for other code on the current website.

After you create a base class for page derivation, you can update the. ASPX page definition to be derived from this class rather than from the standard page class. For example, you can modify the Department class in default. aspx. VB.

Partial Class_ Default:InheritsLitwarepage
'* ** The page class definition is located here
End Class

In this case, I have a website that can track user language preferences and initialize the regional settings based on each request. Now, I have to use the resource file as the ASP. NET 2.0 website localization string text to meet the needs of users in different languages.

Resource files in ASP. NET 2.0

By default, Visual Studio 2005 does not use projects to manage ASP.. NET 2.0 website, so there will be no project-level resource files, just like in Windows Forms applications or class library DLL. Instead, you must explicitly create a resource file and add it to your website. In addition, you must also use. NET 2.0 special folder: resource files containing global resources should be added to the app_globalresources folder, and local resources specific to a file should be added to the app_localresources folder. Global Resources are resources from pages and other files (such as site charts) that can be used based on the site scope. Supports ASP. NET file types of local resources, including pages (. aspx files), master pages (. Master files), and user controls (. ascx files ).

Unlike ASP. NET 2.0, you do not need to compile resources in advance as you did when developing an international Windows Forms Application. On the contrary, ASP. NET will compile global and local resource files into DLL on time, just like the. aspx file. This is a powerful feature, because the company only needs to copy the. resx file xto a web production server to add Localization support for the new language.

Let's complete an example of creating and using a global resource file in ASP. NET 2005 website using Visual Studio 2.0. You can select the Add new item command first, and then select resource file to create a new global resource file.

When you click Add to create a new global resource file, Visual Studio 2005 prompts you in a dialog box, we recommend that you place the new resource file in the app_globalresources directory. Click Yes ). If you place it elsewhere, ASP. NET will not automatically compile the resource file into the DLL.

Resource files used in ASP. NET are the same as those used in Windows Forms applications. First, create a resource file whose string text has been localized to the default regional settings. In our example website, there is a global resource file for this purpose. The name of this file is litware. resx, 4. After you add all specified strings that use the default culture settings, you can copy the resource file and rename it. For example, rename it to litware. Fr. resx to provide a localized French string. You can also copy the French resource file and rename it to litware. fr-BE.resx to maintain strings that have been locally localized to Belgian French.

Figure 4 localized Resources

It is easy to add and maintain specified strings in the resource file, because Visual Studio 2005 provides an easy-to-use resource editor, as shown in Figure 5. Remember that resource files are not limited to localized strings. You can add other types of resources, such as files, Cascading Style Sheets, and client JavaScript files.

Figure 5 Visual Studio 2005 resource editor

Now, we will create a page to retrieve the specified string from the global resource file. This is very easy to do, just like when developing an international Windows Forms Application, you do not need to directly program the ResourceManager class provided by. net. ASP. NET and Visual Studio 2005 can generate a strongly typed Resource class for each global resource file in the background and make it available through intelliisense.

You can use a strongly typed class that resides in a top-level namespace named resources to access the specified string that you add to the global resource file. It uses a line of code to assign a localized string to the property value of the control:

Lblapplicationname. Text=Resources. litware. applicationname

In addition to programming access, ASP. NET 2.0 also introduces declarative syntax, which can be used to bind a specified string to the properties of a page or control. This syntax uses the dollar sign ($) followed by the resource namespace, resource file name, and string name:

<%$ Resources: litware, applicationname%>

For example, if you want to bind a string named applicationname to the text attribute of a tag on the. ASPX page, you can write a tag like this:

<ASP: LabelID= "Lblapplicationname"Runat= "Server"
Text= "<% $ Resources: litware, applicationname %>" />

Visual Studio 2005 also provides an easy-to-use tool named expression builder, as shown in figure 6. This utility helps you generate the syntax required to bind the specified string in the resource file to a control or page attribute. After you add one or more global resource files with the specified string. the ASPX page is placed in the design view, and the expressions attribute is accessed through the property table to access expression builder.

Figure 6 expression Builder

Note that declarative resource binding expressions are not limited to. aspx files,. ascx files, and. Master files. It can also be used to localize the string text in the site map defined in the web. sitemap file. Figure 7 shows the XML from the site map of the litwarewebapp website, which is used to localize the link title displayed in the navigation menu of the site.

Use local resources

A local resource file contains resources that are used for file-based individual items in the site, such as pages, master pages, or user controls. Each local resource file must be named correctly and added to the app_localresources folder for compilation by ASP. NET.

The name of the local resource file should be consistent with the file-based item for which it will provide resources. For example, the local resource file that contains the default regional resources for the addcustomer. ASPX page should be named addcustomer. aspx. resx. The local resource file containing French resources should be named addcustomer. aspx. Fr. resx.

After you add a specified string to a local resource file, you can access them from the page or user control in three ways. First, you can access it through programming. Second, you can use the explicit syntax to bind it to it as a declaration. Third, you can use the implicit syntax to bind it as a declaration. Next we will discuss these methods one by one.

Assume that you have created a local resource file to localize all the Control headers displayed on the addcustomer. ASPX page. To localize the title displayed on the submit button of this page, you can create a localized string named btnsubmit. Text. After adding the specified string to a local resource file, you can access it by calling the getlocalresourceobject method and the code that converts the returned value to a string:

'*** Code in addcustomer. aspx. VB
Btnsubmit. Text=_
Me. Getlocalresourceobject ("Btnsubmit. Text"). Tostring ()

This code is not as good as the previously displayed code. The previously displayed code is used to access the specified string from a global resource using a strongly typed class. Local resource files do not have associated strongly typed classes, so you cannot benefit from intelliisense, and you must explicitly convert object-based return values when calling getlocalresourceobject.

If you want to use the explicit declarative binding syntax, it is usually used in the same way as using global resources. The only difference is that you can ignore the name of the resource file when using local resources:

<ASP: buttonID= "Btnsubmit"Runat= "Server"
Text= "<% $ Resources: btnsubmit. Text %>" />

The implicit declarative binding syntax is the most powerful option. First, add a special attribute named meta: resourcekey to the control tag, or add it to an ASP. NET command, such as page, master, or control. For example, if you want to use the implicit declarative binding syntax using the button (button) control in the. aspx file, you can write a tag like this:

<ASP: buttonID= "Btnsubmit"Runat= "Server"
Meta: resourcekey= "Btnsubmit" />

After you add the meta: resourcekey attribute, you only need to consider one thing, that is, ensure that the strings in the local resource file have the correct name. In my example, ASP. NET automatically loads a localized string named btnsubmit. Text and assigns it to the text attribute of the control named btnsubmit.

The key lies in that, based on Implicit binding, the created string should have a name that matches the target and attribute name defined in the meta: resourcekey attribute. In this example, because meta: resourcekey is for btnsubmit, you only need to add more specified strings to the local resource file, so that you can not only bind to text, you can also bind several other property values, as shown in figure 8.

Figure 8 Add a specified string

Note that When Visual Studio 2005 opens a page, user control, or master page in the design view editor, a generate local resource is provided in the Tools menu) easy-to-use commands. This command automatically creates local resource files in the default region. You can also add the meta: resourcekey attribute on the page and create a corresponding string value in the local resource file to act as the target of the Meta: resourcekey attribute project.

Finally, note that there is a new ASP. NET 2.0 component named localize (localization) control that allows you to localize any elements on the. ASPX page. It provides a design time function not provided by its base class: literal (text) controls; in particular, localize (localization) controls provide design time editing for static content, this allows you to view default values when working in page design mode.

Embed resources in DLL Projects

I will discuss a new ASP. NET technology that uses embedded Resources in the class library DLL. This technology allows you to embed image files, Cascading Style Sheet files, and JavaScript files in DLL and provide them on the hosted web server through DLL.

Note that this technology requires a class library DLL for the ASP. NET 2.0 website. This new feature is provided by ASP. specifically added by the net team, the aim is to provide a better way for the control creators on the server side to allocate resource files while assigning custom controls and Web components. It is not necessary to allocate resource files and DLL files together, nor to ensure that they are copied to an accessible path on the Managed Web server. resource files can now be allocated within the DLL, and can be run by ASP.. net.

The litwarewebapp website contains a library DLL project named litwarewebcomponents, which demonstrates this technology. In this project, an image file named litwareslogan.png has been embedded as a resource. You can change the "generate operation" of the file to "embedded resource" to embed the resource into a set of programs, as shown in figure 9.

Figure 9 embedded Resources

To provide web-based access to an embedded resource file in the DLL, you must add an assembly-Level Attribute named webresource. When you add the webresource attribute, it must contain the qualified name of the resource file and Its MIME type. In the Visual Basic Class Library DLL project, specify that the resource file name contains the project name.

'* ** In assemblyinfo. VB
ImportsSystem. Web. UI
<Assembly: Webresource (_

The webresource attribute allows you to provide the required metadata for ASP. NET runtime to retrieve resource files from DLL by using URLs generated during runtime. To generate the resource File URL from the code in the server control, you can call a method named getwebresourceurl, as shown in 10.

This is the background situation that enables the technology to run. A call to getwebresourceurl generates a URL pointing to a built-in HTTP handler named webresource. axd. The dynamically generated URL also contains a query string to identify the name of the target DLL and the embedded resource file. By loading a custom httphandler class named assemblyresourceloader, ASP. NET can respond to webresource. axd requests during runtime.

When the assemblyresourceloader class is called to load resource files from DLL, it can read the metadata provided by the webresource attribute. The assemblyresourceloader class has been implemented to extract the requested resource file from the DLL image and direct it back to the calling program. Assemblyresourceloader class even provides CacheAlgorithmYou can reuse the same resource file in multiple requests after it is loaded to the front-end web host memory.

Display localized Images

Although embedded resource files and webresource attributes have powerful functions, they still have some obvious limitations. First, you can only use this technology in DLL projects for ASP. NET 2.0 websites. You cannot directly use this technology on the ASP. NET 2.0 website. Second, the technology does not actually support any form of localization. If your website has localized resource files such as various images and Cascading Style Sheets, you will have to use other methods.

The litwarewebapp website displays a graphic image named litwareslogan.png. The website displays images of different versions based on whether the current user prefers English or French. Although ASP. NET 2.0 does not directly support localized image files, it does not require too much custom code to achieve the desired results.

You can add the image files of the localized version to the global resource files of the localized version and start with this. For example, litwareslogan.png in English version has been added to a global resource file named litware. resx, while in French version has been added to litware. Fr. resx. The resources in these two resource files have the same name: litwareslogan.

When different localized versions of global resource files contain localized image files, you can use the name litwareslogan. the custom processing program file of ashx is loaded conditionally based on your language preferences, as shown in Figure 11.

Litwareslogan. the Custom Handler class defined in ashx can use the similar logic that you saw in the Custom initializeculture method before retrieving image files from the global resource file, initializes the currentuiculture settings of the current thread. You may notice that to load the correct resource file, you must initialize the currentuiculture attribute of the current thread, but do not need to initialize the currentculture attribute.

After the Custom Handler correctly initializes the currentuiculture setting, it can access image files through the strongly typed Resource class of litware. resx. Then, you only need to write the digits of the image file to the HTTP Response stream. The final step for displaying localized images is to allocate the litwareslogan. ashx URL to the imageurl attribute of an image control on any page of the site.


ASP. NET 2.0 makes international websites and resources easier. By checking the HTTP title sent by the browser, you can easily initialize the page's regional settings on the website. In addition, you can easily design more complex mechanisms so that users can customize their experience by configuring the desired language preferences.

Please send your questions and comments to Ted to the

Ted Pattison, author and trainer, recently established gorilla training, a company dedicated to providing highly powerful developer training on SharePoint technology. Ted is also writing a book named inside Windows SharePoint Services 3.0 for Microsoft press.

This article is taken from msdn magazine, published in August 2006.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.