23 May 2008

Don't ever use backslashes in Silverlight 2 image URLS!

I had a great time today and yesterday at the Microsoft Developer Days 2008 in Amsterdam, where they shared quite a bit of data on Silverlight 2.0. I have been hacking along with it for some time now and I would like to share a bit of hard-won information I stumbled across. That piece of information is quite simple: If you programmatically set an URL to an Image, do not ever let the URL contain a backslash, not even when it is URLEncoded So, suppose your XAML looks like this:
<usercontrol class="SilverMapLoader.Page" 
  width="700" height="500">
  <canvas name="LayoutRoot" background="Gray">
    <img height="460" src="" width="700" name="map" top="0" left="0" />
You can set the URL to the image in your Page.xaml.cs like this:
string URL = "http://www.someadress.org/image.jpg";
map.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(URL));
Now I was trying to show images that came from some cache mechanisme that effectively needed URLs like this:
Silverlight simply does not show the image. It does not even give an error message. I suppose this is a bug, but this is more or less how I programmed around it:
string newURL = URL.Replace("\\", "/").Replace("%5c", "%2f").Replace("%5C", "%2F");
Effectively I am replacing all backslashes by forward slashes. And modified the page that actually loads the images so that it understands that forward slashes need to be translated into back slashes before the actual path is picked. It does not win a beauty contest, but it works, and in the end, that's all that counts It took me the better part of a rainy Saturday to find this out, while I was actually on planning on finding out a lot of Silverlight, and I reported it as a bug on Silverlight.net. Maybe this post will save some poor sod from repeating my experience ;-) Update: obviously my report helped, since I just installed SilverLight 2.0 release, upgraded and recompiled the project, deleted the workaround code, and it still works as a charm.