View
235
Download
6
Category
Preview:
Citation preview
Localization and Globalization Localization and Globalization in .NET Framework 2.0in .NET Framework 2.0
ದೀ�ದೀ�பபക ക गु�गु�લા�લા�టీటీISV Developer EvangelistISV Developer EvangelistMicrosoftMicrosoft
The Global Software MarketThe Global Software MarketGlobal PC Market in 2010?Global PC Market in 2010?
Source: Source: http://news.com.com/Global+PC+market+to+double+by+2010/2100-1042_3-5490500.html
0
200
400
600
800
1000
1200
1400
2004 2010
Number of PCs in
millions
Emerging Markets
US, Europe, Asia-PacificCurrent Install Base
Reasons to Go GlobalReasons to Go Global
Increasing marketIncreasing marketLocal Indian market largely untapped!Local Indian market largely untapped!
Multinational enterprisesMultinational enterprises
FlexibilityFlexibilityWeb-based applications or distributionWeb-based applications or distribution
International data exchangeInternational data exchange
InternationalizationInternationalizationGlobal user expectationsGlobal user expectations
World ReadyWorld Ready
LocalizedLocalized
Text and data are stored in aText and data are stored in aculture-neutral formatculture-neutral format
Market SpecificMarket Specific
The User Interface is translatedThe User Interface is translated
Features are added that areFeatures are added that arespecific to a given culturespecific to a given culture
DefinitionsDefinitions
DefinitionsDefinitionsGlobalizationGlobalization
LocalizabilityLocalizability
LocalizationLocalization
ResourcesResources
One Code BaseOne Code Base
.NET Framework.NET FrameworkInternationalizationInternationalization
Built-in data and functionality for many Built-in data and functionality for many different culturesdifferent cultures
Best practicesBest practices
How to exchange dataHow to exchange data
How to customize and extend .Net How to customize and extend .Net Framework culturesFramework cultures
Quick QuizQuick Quiz
In what month does the following day fall?In what month does the following day fall?
03/01/200503/01/2005a.a. March?March?
b.b. January?January?
c.c. None of the above.None of the above.
d.d. Not enough info.Not enough info.
Culture-Dependent DataCulture-Dependent Data
API supportedAPI supportedNumeric formatsNumeric formatsCurrenciesCurrenciesMeasurement systemsMeasurement systemsDate/Time formatsDate/Time formatsTime Zones (limited)Time Zones (limited)CalendarsCalendarsCharacter encodingCharacter encodingCapitalizationCapitalizationCollation (Sorting)Collation (Sorting)Word breaking (limited)Word breaking (limited)Character output/fontsCharacter output/fontsCharacter input/Character input/keyboard layoutskeyboard layoutsBi-Directional layoutBi-Directional layoutMulti-lingual UIMulti-lingual UI
not API supportednot API supportedPaper sizesPaper sizesAddress formatsAddress formatsPhone number formatsPhone number formatsMeasurement conversionMeasurement conversionExchange ratesExchange ratesTaxationTaxationCompliance with local Compliance with local lawslawsBusiness conventionsBusiness conventions
CultureInfo and RegionInfoCultureInfo and RegionInfo
In the .Net Framework, culture-In the .Net Framework, culture-dependent data is managed by the dependent data is managed by the CultureInfo and RegionInfo classesCultureInfo and RegionInfo classes
CultureInfo is used toCultureInfo is used toFormat dataFormat data
Load resourcesLoad resources
Set rules for comparing stringsSet rules for comparing strings
Thread settingsThread settingsCurrentCultureCurrentCulture
CurrentUICultureCurrentUICulture
Culture NamesCulture Names
Culture NamesCulture NamesRFC 1766 standard RFC 1766 standard <languagecode2>[-<country/regioncode2>]<languagecode2>[-<country/regioncode2>]
languagecode2 – two letter ISO-639-1 (lowercase) languagecode2 – two letter ISO-639-1 (lowercase) Country/regioncode – two/three letter ISO 3166 (uppercase)Country/regioncode – two/three letter ISO 3166 (uppercase)
Examples: kn-IN, ma-IN, ta-IN, hi-INExamples: kn-IN, ma-IN, ta-IN, hi-IN
Types of CulturesTypes of Cultures
Different Types Of CulturesDifferent Types Of CulturesInvariant CultureInvariant CultureNeutral CulturesNeutral CulturesSpecific CulturesSpecific Cultures
Culture TreeCulture Tree
Invariant CultureInvariant Culture
de (German Neutral Culture)de (German Neutral Culture)
en (English Neutral Culture)en (English Neutral Culture)
de-AT (German-Austria)de-AT (German-Austria)
de-CH (German-Switzerland)de-CH (German-Switzerland)
de-DE (German-Germany)de-DE (German-Germany)
de-LI (German-Liechtenstein)de-LI (German-Liechtenstein)
de-LU (German-Luxembourg)de-LU (German-Luxembourg)
en-US (English-United States)en-US (English-United States)
en-GB (English-United Kingdom)en-GB (English-United Kingdom)
Invariant CultureInvariant Culture
Culture AgnosticCulture AgnosticHappens to beHappens to be associated with English associated with English
Has no country/regionHas no country/region
Should be used for storing data in a Should be used for storing data in a culture independent wayculture independent way
Should not be used for User Interface Should not be used for User Interface elementselements
Invariant CultureInvariant Culture
VB.NETVB.NETDim ci As CultureInfo = Dim ci As CultureInfo =
CultureInfo.InvariantCultureCultureInfo.InvariantCulture
C#C#CultureInfo ci = CultureInfo ci =
CultureInfo.InvariantCultureCultureInfo.InvariantCulture
Neutral CultureNeutral Culture
Associated with a language not with Associated with a language not with country/regioncountry/region
Can be used for UI related optionsCan be used for UI related options
Cannot be used for retrieving Cannot be used for retrieving information such as date/time information such as date/time formattingformatting
Specified using <languagecode2> Specified using <languagecode2> format:format:
Arabic – “ar”Arabic – “ar”
Exceptions – zh-CHT, zh-CHSExceptions – zh-CHT, zh-CHS
Neutral CultureNeutral Culture
VB.NETVB.NETImports System.GlobalizationImports System.Globalization
……
Dim ci As CultureInfo = New Dim ci As CultureInfo = New CultureInfo(“fr”)CultureInfo(“fr”)
C#C#using System.Globalization;using System.Globalization;
……
CultureInfo ci = new CultureInfo(“fr”);CultureInfo ci = new CultureInfo(“fr”);
Specific CultureSpecific Culture
Associated with Language Associated with Language andand a a Country/RegionCountry/Region
fr fr Neutral Culture Neutral Culture
fr-FR fr-FR Specific Culture Specific Culture
Provides additional information about Provides additional information about the date, time, currency and number the date, time, currency and number formatting optionsformatting options
Can be used wherever a Neutral culture Can be used wherever a Neutral culture is used, the opposite is not trueis used, the opposite is not true
Specific CultureSpecific Culture
VB.NETVB.NETImports System.GlobalizationImports System.Globalization
……
Dim ci As CultureInfo = New CultureInfo(“fr-Dim ci As CultureInfo = New CultureInfo(“fr-FR”)FR”)
C#C#using System.Globalization;using System.Globalization;
……
CultureInfo ci = new CultureInfo(“fr-FR”);CultureInfo ci = new CultureInfo(“fr-FR”);
Formatting PrinciplesFormatting Principles
Business Logic/Data LayerBusiness Logic/Data Layer
1. Store and transmit the data in culture-invariant format1. Store and transmit the data in culture-invariant format2.2. Store as binary data where possibleStore as binary data where possible3. Store additional meta information where necessary3. Store additional meta information where necessary
User Interface LayerUser Interface Layer
1. Parse and display data in format the user expects1. Parse and display data in format the user expects2. Respect user preferences wherever possible2. Respect user preferences wherever possible
Formatting and ParsingFormatting and Parsing
FormattingFormattingStandard formatting charactersStandard formatting characters
Custom formatting charactersCustom formatting characters
ParsingParsingConfigurable with stylesConfigurable with styles
TryParse – no conversion exceptionsTryParse – no conversion exceptions
ParseExact for date/time valuesParseExact for date/time values
Type ObjectType ObjectCulture-appropriateCulture-appropriate
StringString
FormattingFormatting
ParsingParsing
NumberNumberFactors affecting number formatsFactors affecting number formats
The character used as the thousands separatorThe character used as the thousands separator US comma (1,025), Germany period (1.025), Sweden space (1 025)US comma (1,025), Germany period (1.025), Sweden space (1 025)
The character used as the decimal separatorThe character used as the decimal separatorUS period (1,025.7), Germany comma (1.025,7)US period (1,025.7), Germany comma (1.025,7)
The way negative numbers are displayedThe way negative numbers are displayedNegative sign can be used in the beginning or in the end of the number. Negative sign can be used in the beginning or in the end of the number. The number can be displayed in parenthesisThe number can be displayed in parenthesisFrance -532, Netherlands 532-, US (532)France -532, Netherlands 532-, US (532)
Digit groupingDigit grouping This refers to the number of digits contained between each separator for This refers to the number of digits contained between each separator for all digit groups that appear to the left of the decimal separatorall digit groups that appear to the left of the decimal separatorUnited States: 123,456,789.00, India: 12,34,56,789.00 United States: 123,456,789.00, India: 12,34,56,789.00
The placement of the percent sign (%)The placement of the percent sign (%)It can be written several ways: 98%, 98 %, 98 pct, %98It can be written several ways: 98%, 98 %, 98 pct, %98
The shape of the numbers, or whether they have a one-to-one The shape of the numbers, or whether they have a one-to-one correspondence to the decimal set of digitscorrespondence to the decimal set of digits (Indian languages don’t have (Indian languages don’t have this issue yet)this issue yet)
NumbersNumbersNumeric FormatsNumeric Formats
Store as binary data type if possibleStore as binary data type if possibleInteger, decimal, floating-pointInteger, decimal, floating-point
Invariant storage as textInvariant storage as textFormat using CultureInfo.InvariantCultureFormat using CultureInfo.InvariantCulture
Use standard format character “R” (reversible) Use standard format character “R” (reversible) for floating point numbers for floating point numbers
CultureCulture FormatFormat ResultResult
en-USen-US NN 123,456.78123,456.78
fr-FRfr-FR NN 123 456,78123 456,78
hi-INhi-IN NN 1,23,456.781,23,456.78
"" (invariant)"" (invariant) RR 123456.78123456.78
NumbersNumbers“Non-English” Arabic-Indic Numerals“Non-English” Arabic-Indic Numerals
Not supported by regular formatting and Not supported by regular formatting and parsing yetparsing yet
Use new functions in CharUnicodeInfoUse new functions in CharUnicodeInfoGetDecimalDigitValueGetDecimalDigitValue
GetNumericValueGetNumericValue
GetDigitValueGetDigitValue
ArabicArabic ٤٣٢١٤٣٢١ 12341234Indic (Telugu/Hindi)Indic (Telugu/Hindi) ౧౨౩౪౫౧౨౩౪౫//१२३१२३
४५४५1234512345
IdeographicIdeographic 〧〥〧〥 7575Number symbolsNumber symbols ¼¼ 0.250.25……
NumbersNumbersCurrenciesCurrencies
Preferably store as decimal with meta dataPreferably store as decimal with meta dataCultureCulture
DateTimeDateTime
Use 3Use 3rdrd party service for conversion party service for conversion
When storing as text use invariant cultureWhen storing as text use invariant cultureReversible text floating-point formatReversible text floating-point format
Currency text format: ¤1,000,000.23Currency text format: ¤1,000,000.23
decimal dec = decimal.Parse("$1000000.23", decimal dec = decimal.Parse("$1000000.23", NumberStyles.Currency,CultureInfo.CurrentCulture);NumberStyles.Currency,CultureInfo.CurrentCulture);System.Console.WriteLine("{0:C}", dec);System.Console.WriteLine("{0:C}", dec);
Output: $1,000,000.23Output: $1,000,000.23
CharUnicodeInfoCharUnicodeInfoFormatting NumbersFormatting NumbersInventing NumberFormatInfoInventing NumberFormatInfo
NumbersNumbersMeasurement SystemsMeasurement Systems
RegionInfo.IsMetricRegionInfo.IsMetric
Metric vs. Imperial SystemMetric vs. Imperial SystemDepends on application target spaceDepends on application target space
Recommendation: metricRecommendation: metric
Invariant culture has no associated Invariant culture has no associated RegionInfoRegionInfo
Store/transfer system with numberStore/transfer system with numberSpecific culture nameSpecific culture name
Custom indicatorCustom indicator
Dates and TimesDates and TimesFormatsFormats
Dates – short date formatDates – short date format03/01/2005 in the United States03/01/2005 in the United States
01/03/2005 in Ireland01/03/2005 in Ireland
01.03.2005 in Russia01.03.2005 in Russia
2005-03-01 in Korea2005-03-01 in Korea
Times – short time formatTimes – short time format2:30 PM in the United States2:30 PM in the United States
14:30 in Japan14:30 in Japan
오전 오전 2:30 in Korea2:30 in Korea
Dates and TimesDates and TimesWhat is a DateTime object?What is a DateTime object?
Number of ticks (100 nanosecond units) Number of ticks (100 nanosecond units) since January 1, 0001 A.D. (Gregorian since January 1, 0001 A.D. (Gregorian calendar)calendar)Time Zone – Local vs. UTCTime Zone – Local vs. UTC
v1.x: No information about if DateTime is Local or v1.x: No information about if DateTime is Local or UTCUTCv2.0: Information intrinsic/definablev2.0: Information intrinsic/definableNo possibility yet to convert from one time zone No possibility yet to convert from one time zone to the otherto the otherUse UTC forUse UTC for
ArithmeticArithmeticStorageStorageTransmissionTransmission
Daylight saving timeDaylight saving time
Dates and TimesDates and TimesDateTime Formatting/ParsingDateTime Formatting/Parsing
Controlled by Controlled by DateTimeFormatInfo DateTimeFormatInfo
CalendarCalendarGregorian calendar is default for DateTimeGregorian calendar is default for DateTime
Invariant text formatsInvariant text formatsR or r (RFC1123)R or r (RFC1123)
Thu, 09 Jun 2005 20:30:00 GMTThu, 09 Jun 2005 20:30:00 GMT
s (ISO 8601)s (ISO 8601)2005-06-09T13:30:002005-06-09T13:30:00
yyyy-MM-ddTHH:mm:sszzzzzyyyy-MM-ddTHH:mm:sszzzzz (XML) (XML)2005-06-09T13:30:00-07:002005-06-09T13:30:00-07:00
Format StringsFormat Strings
Format specifierFormat specifier Current cultureCurrent culture OutputOutput
dd en-USen-US 4/10/20014/10/2001
dd en-NZen-NZ 10/04/200110/04/2001
dd de-DEde-DE 10.04.200110.04.2001
DD hi-INhi-IN 10 10 अप्रै�ल अप्रै�ल 20012001
DD en-USen-US Tuesday, April 10, 2001Tuesday, April 10, 2001
TT en-USen-US 3:51:24 PM3:51:24 PM
TT es-ESes-ES 15:51:2415:51:24
ff en-USen-US Tuesday, April 10, 2001 3:51 PMTuesday, April 10, 2001 3:51 PM
ff fr-FRfr-FR mardi 10 avril 2001 15:51mardi 10 avril 2001 15:51
rr en-USen-US Tue, 10 Apr 2001 15:51:24 GMTTue, 10 Apr 2001 15:51:24 GMT
rr zh-SGzh-SG Tue, 10 Apr 2001 15:51:24 GMTTue, 10 Apr 2001 15:51:24 GMT
ss en-USen-US 2001-04-10T15:51:242001-04-10T15:51:24
ss pt-BRpt-BR 2001-04-10T15:51:242001-04-10T15:51:24
DateTime formattingDateTime formatting
TextTextSorting and ComparisonSorting and Comparison
Comparison just a special case of Comparison just a special case of sortingsorting
For culture-appropriate comparison For culture-appropriate comparison useuse
StringComparison.CurrentCultureStringComparison.CurrentCulture
For culture-agnostic comparison useFor culture-agnostic comparison useStringComparison.OrdinalStringComparison.Ordinal
StringComparison.OrdinalIgnoreCaseStringComparison.OrdinalIgnoreCase
ToUpperInvariant for upper casingToUpperInvariant for upper casing
More performantMore performant
Less likely to change over timeLess likely to change over time
Extending the FrameworkExtending the Framework
Over 6 billion people on the planet, Over 6 billion people on the planet, even 200 cultures just isn’t enougheven 200 cultures just isn’t enough
You can expand cultures throughYou can expand cultures throughUser overrides User overrides
Custom culturesCustom cultures
Windows Data Derived culturesWindows Data Derived cultures
User OverridesUser Overrides
Per-user setting affecting the current Per-user setting affecting the current default culture.default culture.
Set using regional options in WindowsSet using regional options in Windows
Limited set of customizable fieldsLimited set of customizable fields
Only in effect for CurrentCulture w/ Only in effect for CurrentCulture w/ UseUserOverride = TrueUseUserOverride = True
Available in all versions of the .Net Available in all versions of the .Net FrameworkFramework
Custom culturesCustom cultures
Are installed for all users on a machineAre installed for all users on a machine
Allow you to set more fields than user Allow you to set more fields than user overridesoverrides
Can either replace a culture that ships Can either replace a culture that ships with .Net Framework or add to the set with .Net Framework or add to the set of Framework culturesof Framework cultures
Creating a custom cultureCreating a custom culture
The old way – override CultureInfoThe old way – override CultureInfoCumbersomeCumbersome
Only works for a specific applicationOnly works for a specific application
Difficult to maintainDifficult to maintain
Creating a custom cultureCreating a custom culture
The new way – use the The new way – use the CultureAndRegionInfoBuilder (CARIB)CultureAndRegionInfoBuilder (CARIB)
PortablePortable
Works for all users and all applicationsWorks for all users and all applications
Creates a CultureInfo object that is the Creates a CultureInfo object that is the same as those that ship with the same as those that ship with the FrameworkFramework
Supplemental CulturesSupplemental Cultures
Use supplemental cultures to expand Use supplemental cultures to expand the set of cultures available in the .Net the set of cultures available in the .Net frameworkframework
Some limitationsSome limitationsOnly Admin can register new culturesOnly Admin can register new cultures
No custom collations or calendarsNo custom collations or calendars
Replacement CulturesReplacement Cultures
Used to replace an existing .Net Used to replace an existing .Net Framework cultureFramework culture
For example, en-US using a 24-hour For example, en-US using a 24-hour clockclock
Additional restrictions placed on Additional restrictions placed on replacement cultures:replacement cultures:
Cannot change the sortingCannot change the sorting
Cannot change the LCIDCannot change the LCID
Must include the default calendar in Must include the default calendar in available calendarsavailable calendars
Important Note!Important Note!
If an admin replaces a culture, If an admin replaces a culture, applications applications can notcan not access the access the Microsoft definitionsMicrosoft definitions
Use CultureInfo.CultureTypes property Use CultureInfo.CultureTypes property to determine if a CultureInfo represents to determine if a CultureInfo represents a replacement culturea replacement culture
If ((ci.CultureTypes & CultureTypes. If ((ci.CultureTypes & CultureTypes. ReplacementCultures) != 0) {…}ReplacementCultures) != 0) {…}
Windows Data Derived CulturesWindows Data Derived Cultures
Used when a culture does not exist in Used when a culture does not exist in the .Net Framework but is available as a the .Net Framework but is available as a Windows LocaleWindows Locale
For example: zu-ZA, cy-GB, mt-MTFor example: zu-ZA, cy-GB, mt-MT
The .Net Framework uses data from the The .Net Framework uses data from the Windows Locale to create a CultureInfoWindows Locale to create a CultureInfo
Interoperability & MigrationInteroperability & MigrationNon-Microsoft PlatformsNon-Microsoft Platforms
Use CultureAndRegionInfoBuilder.Save Use CultureAndRegionInfoBuilder.Save to generate LDML filesto generate LDML files
Use CultureAndRegionInfoBuilder.Load Use CultureAndRegionInfoBuilder.Load to read LDML filesto read LDML files
Note that most non-Microsoft LDML Note that most non-Microsoft LDML files will require some tweaking before files will require some tweaking before calling Register()calling Register()
In ShortIn Short
Create a Culture derived from existing Create a Culture derived from existing culture(s) using CARIBculture(s) using CARIB
Customize specific parts of that cultureCustomize specific parts of that culture
Register the Culture on your systemRegister the Culture on your system
Use it on your machine from any app Use it on your machine from any app without adding any additional code!without adding any additional code!
Persist it to XML and deploy it on your Persist it to XML and deploy it on your production environment!production environment!
Creating and using en-INCreating and using en-INCultureTypesCultureTypes
SQL Server 2005 and International SQL Server 2005 and International Data: Using Unicode with SQLData: Using Unicode with SQL
Use nchar, nvarchar and ntext data Use nchar, nvarchar and ntext data types to store Indic/Unicode data types to store Indic/Unicode data
Prefix your string literals with N (capital Prefix your string literals with N (capital N – case sensitive)N – case sensitive)
SQL Server Collation SupportSQL Server Collation SupportCollation basicsCollation basics
Provides an appropriate sort orderProvides an appropriate sort orderGerman: a < ä, Swedish: z < äGerman: a < ä, Swedish: z < äFrench: x < y, Lithuanian: i < yFrench: x < y, Lithuanian: i < y
Collations also define code pages for non-Collations also define code pages for non-Unicode conversionsUnicode conversions
55 language collations 55 language collations – – Updated to Updated to Microsoft Windows XP/Microsoft Windows Microsoft Windows XP/Microsoft Windows Server 2003 data (plus Turkish i!)Server 2003 data (plus Turkish i!)
New Comparison FlagNew Comparison Flag_BIN2 (Binary) Fastest – True Unicode Code Point _BIN2 (Binary) Fastest – True Unicode Code Point CompareCompare
New Yukon collations are tagged _90New Yukon collations are tagged _90
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)Technical detailsTechnical details
Windows Windows 55 language collations – Hindi now supported!55 language collations – Hindi now supported!Windows Locale + sort orderWindows Locale + sort orderSuffix meanings (comparison flag (sort order)Suffix meanings (comparison flag (sort order)
_BIN (Binary) _BIN (Binary) FastestFastest _BIN2 (Binary code Point) _BIN2 (Binary code Point) Fastest*Fastest*_CI/_CS (Case sensitivity) _CI/_CS (Case sensitivity) (A == a)(A == a)_AI/_AS (Accent sensitivity) _AI/_AS (Accent sensitivity) (á == a)(á == a)_KS - kanatype sensitivity _KS - kanatype sensitivity (hiragana == katakana)(hiragana == katakana) _WS - width sensitivity _WS - width sensitivity (full width == half width)(full width == half width)
SQL CollationsSQL CollationsProvided for backwards compatibility with prior Provided for backwards compatibility with prior versions of SQL Serverversions of SQL Server
* Slightly slower on insert than _BIN, same speed otherwise* Slightly slower on insert than _BIN, same speed otherwise
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)Technical details (cont’d)Technical details (cont’d)
What makes up the full set?What makes up the full set?All unique collationsAll unique collations
All unique ANSI code pagesAll unique ANSI code pages
All new unique collationsAll new unique collations
All SQL compatibility collationsAll SQL compatibility collations
The full number of SQL Server The full number of SQL Server collationscollations
Select * FROM ::fn_helpcollations()Select * FROM ::fn_helpcollations()
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)A four-layer cakeA four-layer cake
Collation can be specified at four levelsCollation can be specified at four levelsServerServer
DatabaseDatabase
ColumnColumn
ExpressionExpression
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)At the server levelAt the server level
Acts as a default for all databasesActs as a default for all databases
Can be changed with RebuildM.exe in Can be changed with RebuildM.exe in the tools\BINN dir (or unattended the tools\BINN dir (or unattended setup)setup)
Querying the server collation:Querying the server collation:SELECT CONVERT(char, SERVERPROPERTY('collation'))SELECT CONVERT(char, SERVERPROPERTY('collation'))
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)At the database levelAt the database level
Every database has a collation Every database has a collation (default is the server collation)(default is the server collation)
Collation can be changed using Collation can be changed using ALTER DATABASE ALTER DATABASE
Create database db_test collate Latin1_General_CI_AICreate database db_test collate Latin1_General_CI_AI
ALTER DATABASE ALTER DATABASE CONVERT(char, CONVERT(char, DATABASEPROPERTYEX(‘db_test', 'collation')) DATABASEPROPERTYEX(‘db_test', 'collation'))
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)At the column levelAt the column level
Overrides database level collationOverrides 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',)
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)At the expression levelAt the expression level
SELECT * FROM tblCustomers ORDER BY LastName COLLATE Lithuanian_AI_CI,FirstName COLLATE Lithuanian_AI_CI
SELECT * FROM tblCustomers ORDER BY LastName, FirstName
Collation-aware syntaxCollation-aware syntax
Regular syntaxRegular syntax
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)Collation exampleCollation example
Inherits collation from Name column Inherits collation from Name column (French_CS_AS)(French_CS_AS)
Forced collation/orderingForced collation/ordering
SELECT *FROM PRODUCTSORDER BY Name, Description
SELECT *FROM PRODUCTSORDER BY Name COLLATE French_CI_AI, Description
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)The rules of precedenceThe rules of precedence
Explicit BExplicit B
ExpressionExpression
Implicit BImplicit B
ColumnColumn
DefaultDefault
DatabaseDatabaseNo CollationNo Collation
Explicit AExplicit A
ExpressionExpressionRuntime ErrorRuntime Error Explicit AExplicit A Explicit AExplicit A Explicit AExplicit A
Implicit AImplicit A
ColumnColumnExplicit BExplicit B No CollationNo Collation Implicit AImplicit A No CollationNo Collation
DefaultDefault
DatabaseDatabaseExplicit BExplicit B Implicit BImplicit B DefaultDefault No CollationNo Collation
No CollationNo Collation Explicit BExplicit B No CollationNo Collation No CollationNo Collation No CollationNo Collation
SQL Server Collation Support (cont’d)SQL Server Collation Support (cont’d)Precedence examplePrecedence example
This query will return the following error:This query will return the following error:
Msg 446, Level 16, State 9, Server cpsqlintl3, Line 1Msg 446, Level 16, State 9, Server cpsqlintl3, Line 1Cannot resolve collation conflict for equal to operationCannot resolve collation conflict for equal to operation
This query will work properly and return one row:This query will work properly and return one row:
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')
SELECT * FROM TestTab
WHERE GreekCol = LatinCol
SELECT * FROM TestTab
WHERE GreekCol = LatinCol COLLATE greek_ci_as
SQL Server:SQL Server:Storing Unicode DataStoring Unicode DataCollationsCollations
Localization Features in 2.0Localization Features in 2.0
New CalendarsNew Calendars
RightToLeftLayout property in WinFormsRightToLeftLayout property in WinForms
Web Forms resource generatorWeb Forms resource generator
Localization expressions Localization expressions
Strongly-typed resourcesStrongly-typed resources
Improved Resource EditorImproved Resource Editor
ResourceManager lifetime managementResourceManager lifetime management
Automatic culture selectionAutomatic culture selection
New Microsoft ASP.NET deployment optionsNew Microsoft ASP.NET deployment options
New resource provider modelNew resource provider model
ASP.NET 2.0 and ResourcesASP.NET 2.0 and Resources
XML Resources (*.resx)XML Resources (*.resx)
Generated for master pages, content Generated for master pages, content pages, and user controlspages, and user controls
Accessible through page or control Accessible through page or control properties, declarative properties, declarative expressions, expressions, or other APIsor other APIs
Type-safe global resources Type-safe global resources
Set multiple localized Set multiple localized control control properties in a properties in a single single commandcommand
ASP.NET 2.0 and Resources (cont’d)ASP.NET 2.0 and Resources (cont’d)
App_LocalResourcesApp_LocalResourcesGenerated automatically or by handGenerated automatically or by handPer page, controlPer page, control
App_GlobalResources App_GlobalResources Manual generationManual generationShared, strongly-typedShared, strongly-typed
Pre-compile or deploy Pre-compile or deploy source source files and let the files and let the resource build resource build
provider handle provider handle the rest the rest
ASP.NET 2.0 and Resources (cont’d)ASP.NET 2.0 and Resources (cont’d)
ResourceManager lifecycle is handled ResourceManager lifecycle is handled automaticallyautomatically
Resource providers are cached along Resource providers are cached along with specific resource manager with specific resource manager instances per local or global resourceinstances per local or global resource
Default resource and satellite Default resource and satellite assemblies are loaded into application assemblies are loaded into application domain, like providers, and readily domain, like providers, and readily accessibleaccessible
ResourceManager is still thread-safeResourceManager is still thread-safe
Generating ResourcesGenerating Resources
From Design View, select Generate From Design View, select Generate Local Resource from the Tools menuLocal Resource from the Tools menu
Localizable properties for server Localizable properties for server controls are stuffed into resourcescontrols are stuffed into resources
Non-localizable properties can be Non-localizable properties can be manually insertedmanually inserted
Localization expressions are generated Localization expressions are generated for each server controlfor each server control
Page parser turns expressions into code Page parser turns expressions into code to set properties from resourcesto set properties from resources
Localizing Static ContentLocalizing Static Content
The <asp:Localize> control can isolate The <asp:Localize> control can isolate blocks of static text for localizationblocks of static text for localization
Participates in resource generationParticipates in resource generation
Based on the <asp:Literal> control, but Based on the <asp:Literal> control, but can directly edit text in Design Viewcan directly edit text in Design View
<asp:Localize id=”welcomeContent” runat="server">Welcome!</asp:Localize>
Localization ExpressionsLocalization Expressions
ASP.NET supports new declarative ASP.NET supports new declarative binding expressions for connection binding expressions for connection strings, application settings and strings, application settings and resourcesresources
Extensible for custom bindingsExtensible for custom bindings
Automatically applied when resources Automatically applied when resources are generated for a pageare generated for a page
Can hand-edit to control where resources Can hand-edit to control where resources are drawn fromare drawn from
Implicit ExpressionsImplicit Expressions
After generating resources, After generating resources, meta:resourcekey indicates the meta:resourcekey indicates the resource prefix for this controlresource prefix for this control
Resources are generated with this Resources are generated with this prefix for all localizable propertiesprefix for all localizable properties
<asp:LinkButton id=lnkSelectCulture PostBackUrl="selectculture.aspx" runat="server" meta:resourcekey="LinkButtonResource1">Change Culture Settings</asp:LinkButton>’
Explicit ExpressionsExplicit Expressions
Set a specific property to a specific Set a specific property to a specific resource entryresource entry
Can come from local page resources:Can come from local page resources:
Or, from a global resource:Or, from a global resource:
<asp:ImageButton id="btnIDesign" Runat="server" ImageUrl="~/Images/idesignlogo.jpg" AlternateText='<%$ Resources: MissionStatement %>‘ PostBackUrl="http://www.idesign.net" meta:resourcekey="ImageButtonResource1" />
<asp:ImageButton id="btnIDesign" Runat="server" ImageUrl="~/Images/idesignlogo.jpg" AlternateText='<%$ Resources: Glossary, MissionStatement %>‘ PostBackUrl="http://www.idesign.net" meta:resourcekey="ImageButtonResource1" />
Creating Global ResourcesCreating Global Resources
Add a Resources file to the applicationAdd a Resources file to the application
Will be placed in a special Will be placed in a special App_GlobalResources directoryApp_GlobalResources directory
Creating Global ResourcesCreating Global Resources
Add resources through the integrated Add resources through the integrated Resource EditorResource Editor
Apply them to server controls using Apply them to server controls using explicit expressionsexplicit expressions
Or, write custom code to retrieve them Or, write custom code to retrieve them at runtimeat runtime
<asp:ImageButton id="btnIDesign" Runat="server" ImageUrl="~/Images/idesignlogo.jpg" AlternateText='<%$ Resources: Glossary, MissionStatement %>‘ PostBackUrl="http://www.idesign.net" meta:resourcekey="ImageButtonResource1" />
Strongly-Typed ResourcesStrongly-Typed Resources
Global resources generate a type-safe Global resources generate a type-safe class accessible via global Properties class accessible via global Properties objectobject
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 {…}
[System.ComponentModel.EditorBrowsableAttribute(…)]
public static System.Globalization.CultureInfo Culture {…}
public static System.Drawing.Bitmap flag { get { return ((System.Drawing.Bitmap)(ResourceManager.GetObject("flag", _resCulture))); } } }
ResourcesResources
General guidelines on internationalization:General guidelines on internationalization: http://www.microsoft.com/globaldev
Indian Language Globalization and Localization Issues:
http://www.bhashaindia.com/
General questions:General questions: drintl@microsoft.com
Your FeedbackYour Feedbackis Important!is Important!Please Fill Out Please Fill Out Your Feedback Forms!Your Feedback Forms!
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
Recommended