Showing posts with label Culture. Show all posts
Showing posts with label Culture. Show all posts

Simple way to create a Culture in .NET

Here is the simplest way to create a new culture in .NET, from an existing culture.

I needed a way to have french format dates (YYYY-MM-DD) and dot symbol (.) as decimal separator in an web application. Since javascript only recognize dot as decimal separator, having to use french cultures, either "fr-FR" or "fr-CA", is a pain because the decimal specified in theese is the coma. I wanted everything from the french culture, but a dot as decimal separator, and there is no way to do this without creating a new culture.

A new culture can be created from scratch. Here is a detailed article about this.

However, the following code simply copy an existing culture, changes it, and register in with a new name ("fr-CA-QC").

The process of revistering required administrator privilege on the machine where the code is running. The code below only have to be run once.



/// Original culture
CultureInfo cultureInfo = new CultureInfo("fr-CA");
RegionInfo regionInfo = new RegionInfo(cultureInfo.Name);

/// New Culture, with a new name ("fr-CA-QC")
/// if culture already exists, we need to unregister it for overwriting:
/// CultureAndRegionInfoBuilder.Unregister("fr-CA-QC");
CultureAndRegionInfoBuilder builder =
new CultureAndRegionInfoBuilder("fr-CA-QC",
CultureAndRegionModifiers.None);

// load in the data from the original culture and region
builder.LoadDataFromCultureInfo(cultureInfo);
builder.LoadDataFromRegionInfo(regionInfo);

// make custom changes to the culture
builder.NumberFormat.NumberDecimalSeparator = ".";
builder.NumberFormat.CurrencyDecimalSeparator = ".";

/// Create this culture on this computer (NEED ADMINISTRATOR PRIVILEGES)
builder.Register();



This can be executed in a simple windows or console application. After that, any application running on the same computer or server can use this new culture with the name defined above.


Now, I just have to include theese attributes in my web.config files and I will no more have culture problems:


<globalization culture="fr-CA-QC" uiCulture="fr-CA-QC" ...