When you are developing a web site and want to use a custom font, via font-face, you might find that IE on Windows Phone refuses to use it. Turns out that IIS doesn’t include the mime-type by default so you need to add it. If you don’t have access to the site directly (maybe Azure web site or a shared server) you can add it in your site’s web.config webserver section;

<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
    </staticContent>
</system.webServer>

1080p 6 inch Silverlight vs. Jupiter

Anyone know how to resolve this? Given the simple XAML;

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="3*"/>
        </Grid.RowDefinitions>

        <Border Background="Red"  Grid.Row="0" >
            <TextBlock Text="Silverlight"  />
        </Border>

        <Rectangle Fill="Blue" Grid.Row="1" />
        <Rectangle Fill="Green" Grid.Row="2" />

    </Grid>

This results in some very different results;

Silverlight Jupiter
image image

The Silverlight version scales nicely with the phone, whereas the Jupiter version renders the text without scaling it. How do you resolve this?

HttpClient redirect gotcha

Just a quick post as I’ve just fallen foul of this.

Recently I changed by web-client to use the nice await/async HttpClient, e.g.

   
  HttpClient client = new HttpClient();   
  string result = await webClient.GetStringAsync(serviceRequest); 

The problem is that my service decided to be a good web citizen and change their API by sending a redirect. Unfortunatley the above code simple fell over…legs in the air.

The trick is to configure the HttpClient to allow redirects;

   
  HttpClientHandler handler = new HttpClientHandler();   
  handler.AllowAutoRedirect = true;   
  HttpClient webClient = new HttpClient(handler);            
  string result = await webClient.GetStringAsync(serviceRequest); 

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; } }
    }

Automatic text hyphenation for Windows Phone

Recently the topic of text hyphenation for Windows Phone has cropped up. So I thought I’d give it a quick go. Note, this is an initial stab at a solution, I’m not suggesting it’s fully functional but certainly could be built upon.

The problem

image

 <TextBox> 
      FontSize="40"                     
      Width="170"
      TextWrapping="Wrap"
      Text="Hello world combinations can be extremely worrying" />                

Possible Solution

The design is pretty simple (although is it Right-To-Left compatible?), check when the text moves from one line to the next. When it does, check to see if the last character is part of a word. It it is, the add a hyphen.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Pauliom.Behaviors
{
    public class HyphenationBehavior : Behavior<TextBox>
    {
        private int lastLength = 0;
        protected override void OnAttached()
        {

            var textBox = this.AssociatedObject;
            textBox.TextChanged += textBox_TextChanged;
            textBox.Loaded += textBox_Loaded;
            base.OnAttached();
        }

        void textBox_Loaded(object sender, RoutedEventArgs e)
        {
            Hyphenate(sender);
        }

        void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Hyphenate(sender);
        }

        private void Hyphenate(object sender)
        {
            TextBox textBox = sender as TextBox;
            if (this.lastLength != textBox.Text.Length)
            {
                this.lastLength = textBox.Text.Length;
                Rect lastRectange = textBox.GetRectFromCharacterIndex(1);
                int x = 0;
                while (x < textBox.Text.Length)
                {
                    Rect r = textBox.GetRectFromCharacterIndex(x);
                    if (lastRectange.Top != r.Top)
                    {
                        lastRectange = r;
                        char endChar = textBox.Text[x - 1];
                        if (endChar != ' ' && endChar != '-')
                        {
                            textBox.Text = textBox.Text.Substring(0, x - 1) + "-" + textBox.Text.Substring(x - 1);
                        }
                    }                    
                    x++;
                }
            }
        }

        protected override void OnDetaching()
        {
            var textBox = this.AssociatedObject;
            textBox.TextChanged -= textBox_TextChanged;
            base.OnDetaching();
        }
    }
}

image

 <TextBox> 
      FontSize="40"                     
      Width="170"
      TextWrapping="Wrap"
      Text="Hello world combinations can be extremely worrying">    
      <i:Interaction.Behaviors>
         <pauliom:HyphenationBehavior />
      </i:Interaction.Behaviors>                
 </TextBox>            

As I said, it probably is not production ready code but could be built upon.

Microsoft Visual Studio XAML UI Designer – kill, kill, kill

I’ve blogged before that in solutions that share xaml between DLLs the XAML UI Designer can cause problems by locking files and blocking builds. The fastest solution is usually to kill off the designer process. Here is a bit of powershell to do just that;

Get-Process -Name XDesProc | Stop-Process

Workaround for ListPicker missing writable ItemCountThreshold

The ListPicker in Wp7 Toolkit allowed you to specify how many items could be shown before it went into full-screen mode. Quite correctly that has been removed and is now hardcoded to 5. Well, rules are there to be broken, and if you *really* need to workaround the problem then you can try the following (it works at the moment, may not work in the future)

Type type = MyListPicker.GetType();
PropertyInfo itemCountThreshold = type.GetProperty("ItemCountThreshold");
itemCountThreshold.SetValue(MyListPicker, 20);

Looking at the reflection code I released that I hadn’t actually done anything sneaky. So I replaced it with the following…more graceful code;

MyListPicker.SetValue(Microsoft.Phone.Controls.ListPicker.ItemCountThresholdProperty, 20);

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