Tuesday, March 10, 2009

How to use Cultures in Microsoft .NET Micro Framework

I’m currently working on a .NET MF device that should support several languages. The problem I noticed was the missing support of mscorlib culture depending formatting. Well, you’ll find the solution how to get i.e. the correct DecimalSeparator for German in Jens Kühner’s book.

What you have to do is a simple library project that contains a single embedded resource with all the separator / patterns inside. The root namespace of the project files must be System.Globalization.Resources.CultureInfo. That’s the trick!

Next you have to add a reference to this file and you’re able to switch the culture:

public class Program
{
    public static void Main()
    {
        Debug.Print((1.23456).ToString());    // 1.23456
        SetCulture("de-DE");
        Debug.Print((1.23456).ToString());    // 1,23456 comma instead of dot
    }

    static void ResetResourceManager()
    {
        FieldInfo fieldInfo = typeof(Resources).GetField("manager",
                                                BindingFlags.NonPublic | BindingFlags.Static);
        fieldInfo.SetValue(null, null);
    }

    static void SetCulture(string cultureName)
    {
        ResourceUtility.SetCurrentUICulture(new CultureInfo(cultureName));
        ResetResourceManager();
        // render screen with new culture
    }
}

I have created a very simple application that is creating those project files. You can download the mscorlibculturepack.zip containing all the project files.

2 comments:

florian said...

the simple library project creates a csproj file that is incorrect and the new culture is not recognized.
The simple "change the standard namespace of a project on the Application tab page in the project properties to System.Globalization.Resources.CultureInfo" is not enough. This doesn't really change the namespace. I had to edit the csproj file to change that, to add ?xml version="1.0" encoding="utf-8"? at the beginning of file, to add TinyCLR_ClientOnly true /TinyCLR_ClientOnly after the ProjectGuid, etc.
In short the instructions are useless.

Mike Cley said...

Links down.