Testing localisation on Windows Phone

Localising (or localizing) a Windows Phone application is straightforward, however, testing that you have correctly localised the text is harder. One method is to use a pseudo language but I found that has a couple of problems; you need to overwrite a locale (although you can use my previous posts to create a new ‘unsupported’ language), you need to maintain that language with your default language, and…I just find it over noisy. So I present an alternative.

 

Here is an example of an application I am working on;

image

If I switch on the ‘test localisation’ then the page looks like;

image

Argh, I’ve not localised ‘save’! The idea is that all the localised strings show up as their resource name surrounded by a ‘%’. I think this makes it easier to spot the non-localised text, plus you could turn it on during a test session therefore allowing you to report the resource id that is incorrectly localised for a specific language.

The code is based on a previous post but I’ll show the code again with the slight adjustments;

Note, if you want to dynamically support switching between a language and testing it, then you need to change the GetString to call the base class

public class TestResourceManager : ResourceManager
{
    public TestResourceManager()
        : base("MyApp.Localisation.StringLibrary", typeof(StringLibrary).Assembly)
    {
    }

    public override string GetString(string name, System.Globalization.CultureInfo culture)
    {
        return "%" + name + "%";
    }
}

Then add a constructor to the default string library.

    public class LocalisedStrings
    {
        private static readonly StringLibrary _localizedResources = new StringLibrary();

#if DEBUG_LOCALE
        static LocalisedStrings()
       {
           Type type = _localizedResources.GetType();
           FieldInfo info = type.GetField("resourceMan", BindingFlags.NonPublic | BindingFlags.Static);
           info.SetValue(null, new TestResourceManager());
       }
#endif

        public StringLibrary LocalizedResources { get { return _localizedResources; } }
    }

Klingon language on Window Phone

After a recent post about how to allow the Resource Manager to use a non-supported culture I wondered how difficult it would be to support the usual  localisation binding. So, in the great tradition of computer science I wanted to bind to Klingon. Whilst I can see that the correct solution would involve writing a custom tool I wanted a quick ‘hack’ and this is what I’m presenting here. To keep the post size down, I’m assuming you’ve followed the previous project and have that project available.

  1. Create the Klingon resx. Copy AppResource.en-GB.resx over to AppResources.klingon.resx
  2. Add the custom tool PublicResXFileCodeGenerator to AppResources.klingon.resx (see the properties of the file)
  3. Write some klingon – open the resx and change the ApplicationTitle to the following Klingon (it’s not rude) – TLHO’
  4. Create a new String Library class;
  5.  public class AlienLocalizedStrings
        {
            private static AppResources_klingon _localizedResources; 
            static AlienLocalizedStrings()
            {
                _localizedResources =  new AppResources_klingon();
                Type type = _localizedResources.GetType();
                FieldInfo info = type.GetField("resourceMan", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.SetField);
                info.SetValue(null, new AlienResourceManager("klingon"));
            }
            public AppResources_klingon LocalizedResources { get { return _localizedResources; } }
        }
    

  6. Add the resource to App.xaml
  7.     <Application.Resources>
            <local:LocalizedStrings  x:Key="LocalizedStrings"/>
            <local:AlienLocalizedStrings x:Key="AlienLocalizedStrings"/>
        </Application.Resources>
    

  8. Now you can bind to Klingon, e.g.

 <TextBlock Text="{Binding Path=LocalizedResources.ApplicationTitle , Source={StaticResource AlienLocalizedStrings}}" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>

image

The solution works pretty well, obviously the string component is hardcoded to ‘klingon’ which isn’t ideal but I’m sure that can also be resolved with a little more effort. Enjoy Klingon on the phone Smile

Using a resource for an unsupported culture in Windows Phone

I was talking to a fellow dev about why the Resource Manager cannot support languages that the phone platform itself does not support. However, I thought that there probably would be a workaround…and here it is.

Step 1 – Create your basic project

Create phone project, by default this will create;

Resources\AppResources.resx

Step 2 – Add a test resource

Open the AppResources and add a new string called ‘ColourLabel’. I’m making the horrible assumption that you have defaulted to en-US so please enter the value of ‘Color’.

Step 3 – Add a new resource culture

Project->Add->Resource, e.g. AppResources.en-GB.resx

This should have copied our resource string from the master resource, so please change ‘ColourLabel’ to the correct spelling of ‘Colour’ Winking smile

Step 4 – Add a new unknown resource culture

Copy AppResource.en-GB.resx over to AppResources.en-XX.resx

Change ‘ColourLabel’ value from ‘Colour’ to our alien value of ‘ColourXX’

Step 5 – Change Build Action

If you try to use the ResourceManager to access en-XX it will fail because the culture is alien to the platform. So starts the workaround, change the BuildAction of en-XX to ‘Content’

Step 6 – Execute the resource manager

Running the following code…

 
AlienResourceManager britishResourceManager = new AlienResourceManager("en-GB");  
System.Diagnostics.Debug.WriteLine("en-GB: " + britishResourceManager.GetString("ColourLabel")); 
AlienResourceManager alienResourceManager = new AlienResourceManager("en-XX");  
System.Diagnostics.Debug.WriteLine("en-XX: " + alienResourceManager.GetString("ColourLabel"));  

results in the following output;

 
en-GB: Colour  
en-XX: ColourXX  

all done?

It’s fairly obvious that isn’t standard code, but it’s actually just a little over-riding of the standard ResourceManager. Here is my quick version, hope you find it useful.

  
public class AlienResourceManager : ResourceManager     
{         
  private string alienCultureName;         
  private Dictionary alienStrings = null;         
  private CultureInfo currentCulture;         
  public AlienResourceManager(string alienCultureName) :  base("MyPhoneApp.Resources.AppResources", typeof(AppResources).Assembly)         
  {             
    this.alienCultureName = alienCultureName;              
    try             
    {                 
      CultureInfo ci = new CultureInfo(alienCultureName);                 
      this.currentCulture = ci;             
    }             
    catch (Exception)             
    {                 
      LoadAlienStrings(alienCultureName);                 
      this.IsAlienCulture = true;             
    }         
  }          

  private void LoadAlienStrings(string alienCultureName)         
  {             
    var localisation = Application.GetResourceStream(new Uri("Resources/AppResources." + alienCultureName + ".resx", UriKind.Relative));             
    StreamReader resx = new StreamReader(localisation.Stream);             
    string resXml = resx.ReadToEnd();             
    XElement resourceFile = XElement.Parse(resXml);             
    this.alienStrings = new Dictionary();             
    var resourceStrings =              
      (from r in resourceFile.Descendants("data")              
      select new  { Name= r.Attribute("name").Value, Value = r.Element("value").Value}).ToList();              

    resourceStrings.ForEach(r => this.alienStrings.Add(r.Name, r.Value));          
  }           

  public bool IsAlienCulture { get; set; }          
  
  public override string GetString(string name)         
  {             
    if (this.IsAlienCulture)             
    {                 
      return this.alienStrings[name];             
    }             
    else             
    {                 
      return base.GetString(name, currentCulture);             
    }         
  }     
} 

Windows Phone 7 LongListSelector Sample with Accents and Culture support

Recently I’ve made a few posts about how to support different cultures and accents when using the Windows Phone 7 Long List Selector from the Windows Phone Toolkit. So rather than try and explain each bit I decided to finally publish the code showing how the MSDN sample can be altered to support both accented groupings and cultures;

https://wp7llssample.codeplex.com/

The sample is provided as-is, the code is mostly from MSDN with a few tweaks. You should not accept this as production ready code, please carry out your own tests.

Accented grouping

Capture

Japanese grouping

JapaneseGrouping

Japanese Jump List

JapaneseJumpList

Windows Phone Jump List groupings

In a recent post about displaying a longlistselector in wp7 I eluded to code that would need to be correctly localised. Whilst I haven’t had the time to produce the code, I thought this may prove useful in the meantime (Note: the cultures are from wp8 and may change in future releases);
(Edit) – made it a bit easier to consume, shows phonetic support and corrected issue with the a poor cut that chopped the last character

{“sq-AL”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“ar-SA”,”ابتثجحخدذرزسشصضطظعغفقكلمنهوي…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“Az-Latn-AZ”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“be-BY”,”абвгѓґдђеёєжзѕиїјкќлљмнњопрстћуўфхцччџшщъыьэюя…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“bg-BG”,”абвгѓґдђеёєжзѕиїјкќлљмнњопрстћуўфхцччџшщъыьэюя…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“ca-ES”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“zh-CN”,”#ABCDEFGHIJKLMNOPQRSTUVWXYZ…”}, \\ SupportsPhonetics False
{“zh-TW”,”ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩ…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“hr-HR”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“cs-CZ”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“da-DK”,”#abcdefghijklmnopqrstuvwxyzæøå…”}, \\ SupportsPhonetics False
{“nl-NL”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“en-US”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“en-GB”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“et-EE”,”#abcdefghijklmnopqrsšzžtuvwõäöũxy…”}, \\ SupportsPhonetics False
{“fil-PH”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“fi-FI”,”#abcdefghijklmnopqrstuvwxyzåäö…”}, \\ SupportsPhonetics False
{“fr-FR”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“de-DE”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“el-GR”,”αβγδεζηθικλμνξοπρστυφχψω…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“he-IL”,”אבגדהוזחטיכלמנסעפצקרשת…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“hi-IN”,”अआइईउऊऋएऐऑओऔकखगघचछजझटठडढणतथदधनपफबभमयरलवशषसह…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“hu-HU”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“id-ID”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“it-IT”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“ja-JP”,”アカサタナハマヤラワ…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics True
{“kk-KZ”,”абвгѓґдђеёєжзѕиїјкќлљмнњопрстћуўфхцччџшщъыьэюя…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“ko-KR”,”ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“lv-LV”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“lt-LT”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“mk-MK”,”абвгѓґдђеёєжзѕиїјкќлљмнњопрстћуўфхцччџшщъыьэюя…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“ms-MY”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“nb-NO”,”#abcdefghijklmnopqrstuvwxyzæøå…”}, \\ SupportsPhonetics False
{“fa-IR”,”ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“pl-PL”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“pt-BR”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“pt-PT”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“ro-RO”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“ru-RU”,”абвгдеёжзийклмнопрстуфхцчшщъыьэюя…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“sr-Latn-CS”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“sk-SK”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“es-ES”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“es-MX”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“sv-SE”,”#abcdefghijklmnopqrstuvwxyzåäö…”}, \\ SupportsPhonetics False
{“th-TH”,”กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“tr-TR”,”#abcçdefgğhıijklmnoöprsştuüvyz…”}, \\ SupportsPhonetics False
{“uk-UA”,”абвгѓґдђеёєжзѕиїјкќлљмнњопрстћуўфхцччџшщъыьэюя…#abcdefghijklmnopqrstuvwxyz”}, \\ SupportsPhonetics False
{“uz-Latn-UZ”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False
{“vi-VN”,”#abcdefghijklmnopqrstuvwxyz…”}, \\ SupportsPhonetics False