Presentation is loading. Please wait.

Presentation is loading. Please wait.

Localization and Globalization in .NET Framework 2.0

Similar presentations

Presentation on theme: "Localization and Globalization in .NET Framework 2.0"— Presentation transcript:

1 Localization and Globalization in .NET Framework 2.0
ದೀபക गुલાటీ ISV Developer Evangelist Microsoft

2 The Global Software Market Global PC Market in 2010?
1400 1200 1000 Emerging Markets Number of 800 US, Europe, Asia- PCs in Pacific millions 600 Current Install Base Emerging markets: China, India, Indonesia, Brazil, Pakistan, Russia, Nigeria, Bangladesh, Mexico, Philippines, Vietnam, Egypt, Ethiopia, Turkey, Iran and Thailand Caveat: Platform shifts not anticipated 400 200 2004 2010 Source:

3 Reasons to Go Global Increasing market Multinational enterprises
Local Indian market largely untapped! Multinational enterprises Flexibility Web-based applications or distribution International data exchange Emphasize that costs get higher the later the global enabling of code is done. Lots of different topics mixed together? Alternative: Reasons to go global Increasing market Multinational enterprises Flexibility Web-based applications or distribution Data interoperability? International data exchange?

4 Internationalization Global user expectations
Features are added that are specific to a given culture Market Specific The User Interface is translated Localized Application-specific: ask us at the Dr. International Clinic WEB326 CLI324 Webcast This talk DAT290 DBA319 Text and data are stored in a culture-neutral format World Ready

5 Definitions Definitions Globalization Localizability Localization
Resources Before we explore the international support that .NET provides, we need to agree on the definition on a set of terms that we’ll be using throughout this session. When developing world-ready applications, you need to focus on a variety of issues during the application design and development process. The 3 most important issues are: Globalization Globalization is ensuring that your application (also referred to as core application) handles international data such as writing scripts, calendars, time and date format, numeric separators, currencies etc. This is usually the first step that needs to happen for an application so that this application can be used in different markets. For instance, an application developed in the US (or developed with just US in mind), that is not properly globalized, will not generally provide an adequate user experience for a user in UK, even though the language is (arguably) the same. The very fact that the date format (month/day/year in the US vs. day/month/year in the UK) and the currency symbol are different, may be enough to render the application completely useless – even though the user is very capable of reading and understanding the language the application is in. Localizability Localizability is readying software to be translated for different culture or language. In other terms, this means that there are no dependencies in the core application upon a specific language or culture. Effectively, in this step you need to ensure that you have separated the application’s resources that require translation from rest of the application’s code. This may sound simple but this is usually a task that is time consuming and hard to get right Localization Localization is the actual translation of the resources provided by the application. This is pretty much the ideal scenario, in the sense that it implies that both proper globalization and localizability efforts have been performed. In reality, localization is more often than not the step where globalization and localizability issues are still found and such clear cut distinctions are often blurred. Resources Application elements (typically error messages and user interface elements such as menus, dialogs, controls..) that are to be translated in localized versions. If you address Globalization, Localizability and Localization requirements early on in the design phase, you’ll minimize the amount of time and money required to produce quality localized applications for the languages that you intend to support.

6 One Code Base Wanted design: US PC there, appear on click: US date, Japanese PC, Japanese date, double arrow, triple arrow & server

7 .NET Framework Internationalization
Built-in data and functionality for many different cultures Best practices How to exchange data How to customize and extend .Net Framework cultures drop sub-bullets to talking pointBuilt-in data and functionality for many different Data formats Writing systems (scripts) Cultures Customizable and extensible Best practices Verifiable Interoperable

8 03/01/2005 Quick Quiz In what month does the following day fall?
March? January? None of the above. Not enough info.

9 Culture-Dependent Data
API supported Numeric formats Currencies Measurement systems Date/Time formats Time Zones (limited) Calendars Character encoding Capitalization Collation (Sorting) Word breaking (limited) Character output/fonts Character input/ keyboard layouts Bi-Directional layout Multi-lingual UI not API supported Paper sizes Address formats Phone number formats Measurement conversion Exchange rates Taxation Compliance with local laws Business conventions yellow = covered in talk

10 CultureInfo and RegionInfo
In the .Net Framework, culture-dependent data is managed by the CultureInfo and RegionInfo classes CultureInfo is used to Format data Load resources Set rules for comparing strings Thread settings CurrentCulture CurrentUICulture Will mention difference between CurrentThreadCulture & CurrentUICulture Compare to locales CultureInfo is who you are, RegionInfo is where you are?

11 Culture Names Culture Names RFC 1766 standard
<languagecode2>[-<country/regioncode2>] languagecode2 – two letter ISO (lowercase) Country/regioncode – two/three letter ISO 3166 (uppercase) Examples: kn-IN, ma-IN, ta-IN, hi-IN The culture names follow the RFC 1766 standard in the format “<languagecode2>[-<country/regioncode2>]”, where <languagecode2> is a two letter code derived from ISO and <country/regioncode2> is an uppercase two letter (sometimes three letter) code derived from ISO e.g. US English is known as “en-US” A culture may or may not contain the country/regioncode2 information in its name and it is possible to have cultures whose names are only specified by <languagecode2>. For instance Japanese (as a language) is specified as “ja” Besides some culture names have prefixes that specify the script; e.g. “Cy-” specifies the Cyrillic script, “Lt-” specifies the Latin script

12 Types of Cultures Different Types Of Cultures Invariant Culture
Neutral Cultures Specific Cultures While .NET framework implements over 200 cultures, these cultures can be divided into three groups: The invariant culture which is unique The neutral cultures The specific cultures

13 Culture Tree The invariant culture is a unique culture that is the root of the culture tree implemented by .NET Framework. It is associated with the English language but not with a country or region and is a culture that does not exist in the real world. It is really meant to be a completely culture-insensitive culture. This may sound quite weird, but there is some logic to it as there are often processes that require culture insensitive results such as system services. Typical applications of the invariant culture are for instance, dealing with date and time storage for a web service, capitalization of file names that are to be passed to the OS… The invariant culture is useful for storing data that will not be displayed directly to end users. Storing data in a culture-independent format guarantees a format that does not change. When users from different cultures need to access data that are stored using the invariant culture format, these data can be formatted appropriately based on the user by converting from the Invariant culture to a culture that is appropriate for user interface operations for each of these users. In other cases, such as used directly for interface elements, the invariant culture produces results that might be linguistically incorrect or culturally inappropriate. It is therefore recommended to avoid using the invariant culture for any of the user interface item.

14 Invariant Culture Culture Agnostic
Happens to be associated with English Has no country/region Should be used for storing data in a culture independent way Should not be used for User Interface elements

15 Invariant Culture VB.NET C#
Dim ci As CultureInfo = CultureInfo.InvariantCulture C# CultureInfo ci = CultureInfo.InvariantCulture Another option which is somewhat more efficient as it does not entail the creation of a new instance of the invariant culture, is to use InvariantCulture static member function provided by the CultureInfo class. The code on this slide does exactly that.

16 Neutral Culture Associated with a language not with country/region
Can be used for UI related options Cannot be used for retrieving information such as date/time formatting Specified using <languagecode2> format: Arabic – “ar” Exceptions – zh-CHT, zh-CHS A Neutral culture is a culture that is associated with a language but not with a country/region. As such, a neutral culture is very useful for language-only related operations, but cannot be used for retrieving information such as date/time formatting as these are very much country/region dependent and vary within the same language. For instance, date and time formats are different between the United States and United Kingdom where as the language is (arguably) the same. Names for neutral cultures are specified using the <languagecode2> format. For instance Arabic is specified as “ar”. There are a couple of exceptions to this rule: “zh-CHS” (Simplified Chinese) and “zh-CHT” (Traditional Chinese) are neutral cultures but their names look very much like specific culture names. The reason why this is has to do with the fact that the ISO standard only references zh for Chinese. However, since the scripts are really different between Traditional Chinese and Simplified Chinese, there is a need to provide a differentiation, which is done through the names zh-CHT and zh-CHS

17 Neutral Culture VB.NET C# Imports System.Globalization …
Dim ci As CultureInfo = New CultureInfo(“fr”) C# using System.Globalization; CultureInfo ci = new CultureInfo(“fr”);

18 Specific Culture Associated with Language and a Country/Region
fr  Neutral Culture fr-FR  Specific Culture Provides additional information about the date, time, currency and number formatting options Can be used wherever a Neutral culture is used, the opposite is not true A specific culture is a culture that is associated with a language and a country/region. For example, “fr” is a neutral culture and “fr-FR” is a specific culture. The main difference between a neutral culture and a specific one is that a specific one provides additional information about the date, time, currency and number formatting options that are used for that culture. A Specific culture can be used wherever a neutral culture is used, but the opposite is not true. A specific culture has a parent culture that is a neutral culture. e.g. “en” (English) is the neutral culture parent of the specific culture “en-US” (English – United States). Retrieving the neutral culture parent of a specific culture is very simple as the CultureInfo class provides the Parent member that provides the neutral culture parent of a specific CultureInfo object.

19 Specific Culture VB.NET C# Imports System.Globalization …
Dim ci As CultureInfo = New CultureInfo(“fr-FR”) C# using System.Globalization; CultureInfo ci = new CultureInfo(“fr-FR”);

20 Formatting Principles
User Interface Layer 1. Parse and display data in format the user expects 2. Respect user preferences wherever possible Business Logic/Data Layer 1. Store and transmit the data in culture-invariant format Store as binary data where possible 3. Store additional meta information where necessary Wanted design: US PC there, appear on click: US date, Japanese PC, Japanese date, double arrow, triple arrow & server

21 Formatting and Parsing
Type Object Culture-appropriate String Parsing Formatting Standard formatting characters Custom formatting characters Parsing Configurable with styles TryParse – no conversion exceptions ParseExact for date/time values Deleted: Composite Formatting

22 Number Factors affecting number formats
The character used as the thousands separator US comma (1,025), Germany period (1.025), Sweden space (1 025) The character used as the decimal separator US period (1,025.7), Germany comma (1.025,7) The way negative numbers are displayed Negative sign can be used in the beginning or in the end of the number. The number can be displayed in parenthesis France -532, Netherlands 532-, US (532) Digit grouping This refers to the number of digits contained between each separator for all digit groups that appear to the left of the decimal separator United States: 123,456,789.00, India: 12,34,56,789.00 The placement of the percent sign (%) It can be written several ways: 98%, 98 %, 98 pct, %98 The shape of the numbers, or whether they have a one-to-one correspondence to the decimal set of digits (Indian languages don’t have this issue yet)

23 Numbers Numeric Formats
Culture Format Result en-US N 123,456.78 fr-FR 123 456,78 hi-IN 1,23,456.78 "" (invariant) R Store as binary data type if possible Integer, decimal, floating-point Invariant storage as text Format using CultureInfo.InvariantCulture Use standard format character “R” (reversible) for floating point numbers programming languages: invariant

24 Numbers “Non-English” Arabic-Indic Numerals
٤٣٢١ 1234 Indic (Telugu/Hindi) ౧౨౩౪౫/१२३४५ 12345 Ideographic 〧〥 75 Number symbols 0.25 Not supported by regular formatting and parsing yet Use new functions in CharUnicodeInfo GetDecimalDigitValue GetNumericValue GetDigitValue Recommended reading:

25 Numbers Currencies Preferably store as decimal with meta data
decimal dec = decimal.Parse("$ ", NumberStyles.Currency,CultureInfo.CurrentCulture); System.Console.WriteLine("{0:C}", dec); Output: $1,000,000.23 Preferably store as decimal with meta data Culture DateTime Use 3rd party service for conversion When storing as text use invariant culture Reversible text floating-point format Currency text format: ¤1,000,000.23

26 CharUnicodeInfo Formatting Numbers Inventing NumberFormatInfo

27 Numbers Measurement Systems
RegionInfo.IsMetric Metric vs. Imperial System Depends on application target space Recommendation: metric Invariant culture has no associated RegionInfo Store/transfer system with number Specific culture name Custom indicator Mars Climate Orbiter:

28 Dates and Times Formats
Dates – short date format 03/01/2005 in the United States 01/03/2005 in Ireland in Russia in Korea Times – short time format 2:30 PM in the United States 14:30 in Japan 오전 2:30 in Korea

29 Dates and Times What is a DateTime object?
Number of ticks (100 nanosecond units) since January 1, 0001 A.D. (Gregorian calendar) Time Zone – Local vs. UTC v1.x: No information about if DateTime is Local or UTC v2.0: Information intrinsic/definable No possibility yet to convert from one time zone to the other Use UTC for Arithmetic Storage Transmission Daylight saving time UTC = Coordinated Universal Time, also known as GMT = Greenwich Mean Time v1.x: No information about if DateTime is Local or UTC Store time zone info alongside Some APIs (System.XML.Serialization) require local time Issues when DST starts/ends Arithmetic on UTC times

30 Dates and Times DateTime Formatting/Parsing
Controlled by DateTimeFormatInfo Calendar Gregorian calendar is default for DateTime Invariant text formats R or r (RFC1123) Thu, 09 Jun :30:00 GMT s (ISO 8601) T13:30:00 yyyy-MM-ddTHH:mm:sszzzzz (XML) T13:30:00-07:00 Solar year: days Lunar phase: 29.5 days Calendars: GregorianCalendar JulianCalendar HebrewCalendar HijriCalendar UmAlQuraCalendar JalaaliCalendar JapaneseCalendar JapaneseLunisolarCalendar ChineseLunisolarCalendar TaiwanCalendar TaiwanLunisolarCalendar KoreanCalendar KoreanLunisolarCalendar EastAsianLunisolarCalendar ThaiBuddhistCalendar

31 Format Strings Format specifier Current culture Output d en-US
4/10/2001 en-NZ 10/04/2001 de-DE D hi-IN 10 अप्रैल 2001 Tuesday, April 10, 2001 T 3:51:24 PM es-ES 15:51:24 f Tuesday, April 10, :51 PM fr-FR mardi 10 avril :51 r Tue, 10 Apr :51:24 GMT zh-SG s T15:51:24 pt-BR

32 DateTime formatting

33 Text Sorting and Comparison
Comparison just a special case of sorting For culture-appropriate comparison use StringComparison.CurrentCulture For culture-agnostic comparison use StringComparison.Ordinal StringComparison.OrdinalIgnoreCase ToUpperInvariant for upper casing More performant Less likely to change over time

34 Extending the Framework
Over 6 billion people on the planet, even 200 cultures just isn’t enough You can expand cultures through User overrides Custom cultures Windows Data Derived cultures IFormattable, IFormatProvider, ICustomFormatter another option

35 User Overrides Per-user setting affecting the current default culture.
Set using regional options in Windows Limited set of customizable fields Only in effect for CurrentCulture w/ UseUserOverride = True Available in all versions of the .Net Framework

36 Custom cultures Are installed for all users on a machine
Allow you to set more fields than user overrides Can either replace a culture that ships with .Net Framework or add to the set of Framework cultures

37 Creating a custom culture
The old way – override CultureInfo Cumbersome Only works for a specific application Difficult to maintain

38 Creating a custom culture
The new way – use the CultureAndRegionInfoBuilder (CARIB) Portable Works for all users and all applications Creates a CultureInfo object that is the same as those that ship with the Framework

39 Supplemental Cultures
Use supplemental cultures to expand the set of cultures available in the .Net framework Some limitations Only Admin can register new cultures No custom collations or calendars

40 Replacement Cultures Used to replace an existing .Net Framework culture For example, en-US using a 24-hour clock Additional restrictions placed on replacement cultures: Cannot change the sorting Cannot change the LCID Must include the default calendar in available calendars

41 Important Note! If an admin replaces a culture, applications can not access the Microsoft definitions Use CultureInfo.CultureTypes property to determine if a CultureInfo represents a replacement culture If ((ci.CultureTypes & CultureTypes. ReplacementCultures) != 0) {…}

42 Windows Data Derived Cultures
Used when a culture does not exist in the .Net Framework but is available as a Windows Locale For example: zu-ZA, cy-GB, mt-MT The .Net Framework uses data from the Windows Locale to create a CultureInfo

43 Interoperability & Migration Non-Microsoft Platforms
Use CultureAndRegionInfoBuilder.Save to generate LDML files Use CultureAndRegionInfoBuilder.Load to read LDML files Note that most non-Microsoft LDML files will require some tweaking before calling Register()

44 In Short Create a Culture derived from existing culture(s) using CARIB
Customize specific parts of that culture Register the Culture on your system Use it on your machine from any app without adding any additional code! Persist it to XML and deploy it on your production environment!

45 Creating and using en-IN

46 SQL Server 2005 and International Data: Using Unicode with SQL
Use nchar, nvarchar and ntext data types to store Indic/Unicode data Prefix your string literals with N (capital N – case sensitive)

47 SQL Server Collation Support Collation basics
Provides an appropriate sort order German: a < ä, Swedish: z < ä French: x < y, Lithuanian: i < y Collations also define code pages for non-Unicode conversions 55 language collations – Updated to Microsoft Windows XP/Microsoft Windows Server 2003 data (plus Turkish i!) New Comparison Flag _BIN2 (Binary) Fastest – True Unicode Code Point Compare New Yukon collations are tagged _90

48 SQL Server Collation Support (cont’d) Technical details
Windows 55 language collations – Hindi now supported! Windows Locale + sort order Suffix meanings (comparison flag (sort order) _BIN (Binary) Fastest _BIN2 (Binary code Point) Fastest* _CI/_CS (Case sensitivity) (A == a) _AI/_AS (Accent sensitivity) (á == a) _KS - kanatype sensitivity (hiragana == katakana) _WS - width sensitivity (full width == half width) SQL Collations Provided for backwards compatibility with prior versions of SQL Server * Slightly slower on insert than _BIN, same speed otherwise

49 SQL Server Collation Support (cont’d) Technical details (cont’d)
What makes up the full set? All unique collations All unique ANSI code pages All new unique collations All SQL compatibility collations The full number of SQL Server collations Select * FROM ::fn_helpcollations()

50 SQL Server Collation Support (cont’d) A four-layer cake
Collation can be specified at four levels Server Database Column Expression

51 SQL Server Collation Support (cont’d) At the server level
Acts as a default for all databases Can be changed with RebuildM.exe in the tools\BINN dir (or unattended setup) Querying the server collation: SELECT CONVERT(char, SERVERPROPERTY('collation'))

52 SQL Server Collation Support (cont’d) At the database level
Every database has a collation (default is the server collation) Collation can be changed using ALTER DATABASE Create database db_test collate Latin1_General_CI_AI ALTER DATABASE CONVERT(char, DATABASEPROPERTYEX(‘db_test', 'collation'))

53 SQL Server Collation Support (cont’d) At the column level
Overrides database level collation CREATE TABLE jobs ( job_id smallint IDENTITY(1,1) PRIMARY KEY CLUSTERED, job_desc nvarchar(50) COLLATE Arabic_CI_AI_KS NOT NULL DEFAULT 'New Position - title not formalized yet', )

54 SQL Server Collation Support (cont’d) At the expression level
Regular syntax SELECT * FROM tblCustomers ORDER BY LastName, FirstName Collation-aware syntax SELECT * FROM tblCustomers ORDER BY LastName COLLATE Lithuanian_AI_CI, FirstName COLLATE Lithuanian_AI_CI

55 SQL Server Collation Support (cont’d) Collation example
Inherits collation from Name column (French_CS_AS) Forced collation/ordering SELECT * FROM PRODUCTS ORDER BY Name, Description SELECT * FROM PRODUCTS ORDER BY Name COLLATE French_CI_AI, Description

56 SQL Server Collation Support (cont’d) The rules of precedence
Explicit B Expression Implicit B Column Default Database No Collation Explicit A Runtime Error Implicit A

57 SQL Server Collation Support (cont’d) Precedence example
CREATE TABLE TestTab (id int, GreekCol nvarchar(10) collate greek_ci_as, LatinCol nvarchar(10) collate latin1_general_cs_as) INSERT TestTab VALUES (1, N'A', N'a') This query will return the following error: Msg 446, Level 16, State 9, Server cpsqlintl3, Line 1 Cannot resolve collation conflict for equal to operation This query will work properly and return one row: SELECT * FROM TestTab WHERE GreekCol = LatinCol SELECT * FROM TestTab WHERE GreekCol = LatinCol COLLATE greek_ci_as

58 SQL Server: Storing Unicode Data Collations

59 Localization Features in 2.0
New Calendars RightToLeftLayout property in WinForms Web Forms resource generator Localization expressions Strongly-typed resources Improved Resource Editor ResourceManager lifetime management Automatic culture selection New Microsoft ASP.NET deployment options New resource provider model

60 ASP.NET 2.0 and Resources XML Resources (*.resx)
Generated for master pages, content pages, and user controls Accessible through page or control properties, declarative expressions, or other APIs Type-safe global resources Set multiple localized control properties in a single command

61 ASP.NET 2.0 and Resources (cont’d)
App_LocalResources Generated automatically or by hand Per page, control App_GlobalResources Manual generation Shared, strongly-typed Pre-compile or deploy source files and let the resource build provider handle the rest

62 ASP.NET 2.0 and Resources (cont’d)
ResourceManager lifecycle is handled automatically Resource providers are cached along with specific resource manager instances per local or global resource Default resource and satellite assemblies are loaded into application domain, like providers, and readily accessible ResourceManager is still thread-safe

63 Generating Resources From Design View, select Generate Local Resource from the Tools menu Localizable properties for server controls are stuffed into resources Non-localizable properties can be manually inserted Localization expressions are generated for each server control Page parser turns expressions into code to set properties from resources

64 Localizing Static Content
The <asp:Localize> control can isolate blocks of static text for localization Participates in resource generation Based on the <asp:Literal> control, but can directly edit text in Design View <asp:Localize id=”welcomeContent” runat="server">Welcome!</asp:Localize>


66 Localization Expressions
ASP.NET supports new declarative binding expressions for connection strings, application settings and resources Extensible for custom bindings Automatically applied when resources are generated for a page Can hand-edit to control where resources are drawn from

67 Implicit Expressions After generating resources, meta:resourcekey indicates the resource prefix for this control Resources are generated with this prefix for all localizable properties <asp:LinkButton id=lnkSelectCulture PostBackUrl="selectculture.aspx" runat="server" meta:resourcekey="LinkButtonResource1">Change Culture Settings</asp:LinkButton>’

68 Explicit Expressions Set a specific property to a specific resource entry Can come from local page resources: Or, from a global resource: <asp:ImageButton id="btnIDesign" Runat="server" ImageUrl="~/Images/idesignlogo.jpg" AlternateText='<%$ Resources: MissionStatement %>‘ PostBackUrl=" meta:resourcekey="ImageButtonResource1" /> <asp:ImageButton id="btnIDesign" Runat="server" ImageUrl="~/Images/idesignlogo.jpg" AlternateText='<%$ Resources: Glossary, MissionStatement %>‘ PostBackUrl=" meta:resourcekey="ImageButtonResource1" />

69 Creating Global Resources
Add a Resources file to the application Will be placed in a special App_GlobalResources directory

70 Creating Global Resources
Add resources through the integrated Resource Editor Apply them to server controls using explicit expressions Or, write custom code to retrieve them at runtime <asp:ImageButton id="btnIDesign" Runat="server" ImageUrl="~/Images/idesignlogo.jpg" AlternateText='<%$ Resources: Glossary, MissionStatement %>‘ PostBackUrl=" meta:resourcekey="ImageButtonResource1" />

71 Strongly-Typed Resources
Global resources generate a type-safe class accessible via global Properties object

72 class Resources { private static System.Resources.ResourceManager _resMgr; private static System.Globalization.CultureInfo _resCulture; /*FamANDAssem*/ internal Resources() {} [System.ComponentModel.EditorBrowsableAttribute(…)] public static System.Resources.ResourceManager ResourceManager {…} public static System.Globalization.CultureInfo Culture {…} public static System.Drawing.Bitmap flag { get { return ((System.Drawing.Bitmap)(ResourceManager.GetObject("flag", _resCulture))); }

73 Resources General guidelines on internationalization: Indian Language Globalization and Localization Issues: General questions:

74 Your Feedback is Important!
Please Fill Out Your Feedback Forms!

75 © 2005 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

Download ppt "Localization and Globalization in .NET Framework 2.0"

Similar presentations

Ads by Google