#GIS from a .NET developer's perspective

WinRT vs. Silverlight - Part 5 - Defining default style template

See intro blogpost here.

Here's something that's actually NOT different in Silverlight (but it's different from WPF as it has always been).
You declare your style using DefaultStyleKey. This means the code looks like this for Silverlight, WPF and Windows Runtime:

public class MyControl : Control
    public MyControl()
        this.DefaultStyleKey = typeof(MyControl);
    static MyControl() {
            new FrameworkPropertyMetadata(

Here is what IS different though: You need to set the build action of \Themes\Generic.xaml to "Content". It won't work without it.
Also note that when you add Generic.xaml to your project, it will also get added to App.Xaml. I assume this is a bug in the current release, but you will have to go and delete this entry, or it won't work.

WinRT vs. Silverlight - Part 4 - Dispatcher

See intro blogpost here.

In Silverlight and WPF you will often use the Dispatcher to return from a background thread to jump to the UI Thread. This is required when you need to update your UI, because you’re not allowed to touch the UI from anything but the UI Thread. The Dispatcher method has changed slightly in WinRT. It’s also now of type “CoreDispatcher”, instead of just “Dispatcher”.

           (s, a) => { ... }
      , this, null);

WinRT vs. Silverlight - Part 3 - Dependency Properties

See intro blogpost here.

UPDATE Feb. 29, 2012: As hinted at below that this would happen, this blogpost on dependency properties is now outdated. Since the Consumer Preview of Windows 8 released, dependency properties now work exactly like they do in Silverlight and WPF.


Declaration of dependency properties has changed in the WinRT. This is a temporary change and will go away when WinRT hits beta, but still good to know if you start prototyping on WinRT today. If you are a control developer this is probably one of the things you would have to change in the most places.

Here’s what the API looks like for Silverlight and WPF for registering a Dependency Property or an Attached Property:

public static DependencyProperty Register(
      string name, 
      Type propertyType, 
      Type ownerType,
      PropertyMetadata typeMetadata);
public static DependencyProperty RegisterAttached(
      string name, 
      Type propertyType,
      Type ownerType, 
      PropertyMetadata defaultMetadata);

And here’s what this currently looks like in WinRT CTP :

public static DependencyProperty Register(
      string name, 
      string propertyTypeName, 
      string ownerTypeName,
      PropertyMetadata typeMetadata);
public static DependencyProperty RegisterAttached(
      string name, 
      string propertyTypeName,
      string ownerTypeName, 
      PropertyMetadata defaultMetadata);

Notice how the PropertyType and PropertyOwnerType is now strings instead of types!

This means you would have to write your code like this to make it cross-compile:

        public double MyDoubleProperty
            get { return (double)GetValue(MyDoublePropertyProperty); }
            set { SetValue(MyDoublePropertyProperty, value); }

        public static readonly DependencyProperty MyDoublePropertyProperty =
             "Double", "MyNamespace.MyControl", 
                typeof(double), typeof(MyNamespace.MyControl), 
                 new PropertyMetadata(0d));

Also note that you don’t use the full type name for the system types. Ie. here you use “Double” and not “double” or “System.Double”.

You could create a few static methods to replace the Register/RegisterAttached methods that will make your code cross-platform, and switch it out just there when this changes. Here’s one example how this could be accomplished (the ‘ToRTString’ method isn’t fully tested though…):

    public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType, PropertyMetadata metadata)
        return DependencyProperty.RegisterAttached(name, 
            propertyType.ToRTString(), ownerType.ToRTString()
            propertyType, ownerType
            , metadata);
    public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata metadata)
        return DependencyProperty.Register(name,
            propertyType.ToRTString(), ownerType.ToRTString()
            propertyType, ownerType
            , metadata);
    private static string ToRTString(this Type type)
        string name = type.FullName;
            return name.Substring(7);
            return name;

WinRT vs. Silverlight - Part 2 - Code Namespace

See intro blogpost here.

The namespaces in WinRT has changed for all the UI related classes. Generally System.Windows has been replaced with Windows.UI.Xaml, and the rest is the same below that. If we to use the “NETFX_CORE” compiler directive that WinRT projects comes with, the typical default using statements that would compile on both Silverlight, WPF and WinRT would look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;

This is also described in greater detail here:

WinRT vs. Silverlight - Part 1 - XML Namespace

See intro blogpost here.

For the most part your XAML ports right over to WinRT. However an important change is how you register namespaces from your assemblies.

Here's how you do this in Silverlight and WPF for an assembly "MyAssembly.dll" and namespace MyAssembly.MyNamespace:


And similar for namespaces in the same assembly as where the XAML file lives (ie MyAssembly):


In WinRT, you only declare the namespace (never the assembly) and instead use "using" instead of "clr-namespace":


Unfortunately we don't have #if-def statements in XAML so you can just use compiler directives on your XAML and make it work on both platforms. So until we get that (or Microsoft reverts the above change) you are going to have to duplicate and maintain two sets of XAML. :-(

I actually do like this change, and this is probably how it should always have been, but it's a change that cause a lot of pain for developers trying to reuse their existing codebase. The benefit doesn't seem to pain (from what I understand the Windows team simply didn't like it said "clr" in there, plus they don't have the exact same concepts down in the runtime so the assembly part was left out.)

WinRT vs. Silverlight - Part 0

I recently wrote a blog post series on how to share your code between Silverlight and WPF.

With the announcements of Windows 8 at the //BUILD/ conference and the new Windows Runtime (WinRT) which can be built against using C# and XAML I thought it appropriate to start a new series on how to make your existing Silverlight/WPF code run on WinRT. I'm mostly writing this as notes to myself and hope you will also find them useful. Personally I've already found a lot of issues with porting code over. Not that there are significant changes, but the documentation is very limited at this point, and the gotchas enough to make you waste a lot of time on resolving this. Hopefully this will act as a resource to get it working for you as well. Keep an eye on this post. I'll post new links as I go along learning new things about WinRT.

Generally what I have found is that with respect to XAML WinRT is more compatible to Silverlight than WPF, so expect it easier to use your Silverlight knowledge, and don't try and use WPF XAML features at this point. Things like DataTriggers etc. are not supported, and for the most part, the UI related methods in code are more similar to Silverlight than .NET 4 (note however that non-UI code is closer to the "original" .NET, since this is essentially the same CLR and compiler used).

I won't go into too much detail about what this means for Silverlight and WPF. There's plenty of blogs and newssites that has their (over?)reactions described in detail. This series will really just focus on how to take your existing code and get it running on WinRT.

Click to select a topic below:

  1. WinRT vs. Silverlight - Part 1 - XML Namespace
  2. WinRT vs. Silverlight - Part 2 - Code Namespace
  3. WinRT vs. Silverlight - Part 3 - Dependency Properties
  4. WinRT vs. Silverlight - Part 4 - Dispatcher
  5. WinRT vs. Silverlight - Part 5 - Defining default style template
  6. WinRT vs. Silverlight - Part 6 - Using Tasks
  7. WinRT vs. Silverlight - Part 7 - Making WebRequests 
  8. WinRT vs. Silverlight - Part 8 - What other people are blogging
  9. Coming… WinRT vs. Silverlight - Part 9 - File IO
  10. Coming… WinRT vs. Silverlight - Part 10 – Various CTP bugs…
  11. More…

GZIP Compressed Web Requests in WP7 - Take 2

I earlier wrote about how .NET API in Windows Phone 7 doesn’t zip-compress it’s web requests, and how using Mango’s socket support allows you to circumvent that to get more efficient use of the limited data connection phones often have. The approach had some problems and limitations, and wouldn’t work in all scenarios. Even so, compressing your webrequests is very important on a phone since you can often save 50-80% of the data transmitted, and many people pay by the byte they transmit.

Since my blogpost Windows Phone 7 Mango has gone through a few iterations, and using a socket is no longer necessary, since the “accept-encoding” header needed to request GZIP compressed requests is no longer blocked (thank you to those who voted for getting this unblocked). However, GZIP compression is still not a built in feature (Why not Microsoft?!?). If you set this header, you are still in charge of uncompressing the content. I’ve updated my GZipWebClient class to take advantage of the new allowed header. It simplifies the class quite a lot, as well as made it more stable.

Also I “forked” the DotNetZip library and included in this project, so you don’t need to go find 3rd party dependencies, and in the process removed all parts of the library that is not needed to keep the assembly as compass as possible. So here’s what the client now basically looks like:

public class GZipWebClient : WebClient
    public GZipWebClient()
    protected override WebRequest GetWebRequest(Uri address)
        var req = base.GetWebRequest(address);
        req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip"; //Set GZIP header
        return req;
    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
        WebResponse response = null;
            response = base.GetWebResponse(request, result);
            if (response.Headers[HttpRequestHeader.ContentEncoding] == "gzip")
                return new GZipWebResponse(response); //If gzipped response, uncompress
                return response;
            return null;

The key here is adding the header that tells the server “Hey I understand GZipped responses as well”. When the response comes back and the header says “Hey here’s some gzipped content”, I use a custom GzipWebResponse class that uses the DotNetZip library to uncompress the stream. Apart from some trivial code, this is the meat of that class:

internal class GZipWebResponse : WebResponse
    WebResponse response;
    internal GZipWebResponse(WebResponse resp)
        response = resp;
    public override System.IO.Stream GetResponseStream()
        return new SharpGIS.ZLib.GZipStream(response.GetResponseStream()); //Uncompress

You use it exactly like the normal “WebClient” class, except you instantiate the GZipWebClient instead. The rest of your existing code doesn’t change at all. Example:

WebClient client = new SharpGIS.GZipWebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;

You can download the source code below, and you can also get it on NuGet/SymbolSourceusing command “Install-Package SharpGIS.GZipWebClient”

Download source

I also rely heavily on this in my WinPhone Twitter client ‘Peregrine’ and have seen quite a performance improvement when updating your twitter timeline. You can download Peregrine for free here:


With the latest v1.1 update on nuget (source also updated here), you don’t have to do the above. All you need to write is the following two lines of code and put it in your app.xaml.cs startup file. After this ALL existing code (including 3rd party libraries you don’t have control over) will start using GZIP compression!

WebRequest.RegisterPrefix("http://", SharpGIS.WebRequestCreator.GZip);
WebRequest.RegisterPrefix("https://", SharpGIS.WebRequestCreator.GZip);

If you just want to do this for some domains, only register that prefix part. So no need to go replace all your WebClient as mentioned above. More on how this work in this blogpost.


Note that using RegisterPrefix causes this to use an internal custom HttpWebRequest class and that can have some serious effects on your app. Unfortunately Microsoft ‘forgot’ to unlock the Get/Set UserAgent property when they ported from Silverlight (there the user agent was always the browser), and many 3rd party libraries  tries to set this property, which will throw a NotImplementedException. Also note that cookies are not supported either (some libraries use that). They should of course be checking the “SupportsCookieContainer” property before using it, but not all do (I’m looking at you RestSharp), and will therefore throw an exception. However for almost all the simpler scenarios, the above register works like a charm.


Now also on GitHub:


Update 2 no longer applies :)

Windows Phone: Adding Mango features to a 7.0 WinPhone App

Microsoft just announced what happens to your non-Mango app (WP7.0) if you publish a Mango app (WP7.1) to the marketplace. Basically if you upgrade your app to 7.1, you will no longer be able to maintain the 7.0 app for people who still haven’t upgraded yet (and we know from the last update that that can take a while).

However, it is possible to make a 7.0 app that uses Mango features if the user has upgraded to Mango. That way you can continue to build a 7.0 app, and the moment the user upgrades to Mango, he will get additional features available. All this using a little “reflection magic”. The certification requirements does kind of hint at that this is not allowed, but some apps has already made it through certification, so this seems to be considered OK to do, and it also works great as well.

So how is this done? We can use the method of the Type object to get identifiers of methods, events, constructors, properties etc. by using their names. This way we will never write a piece of code that explicitly uses one of these (which the compiler would reject), but instead at runtime will attempt to locate them, and if successful execute/access it

But before we attempt doing that, we can perform a check for whether this is a mango device (or newer). Mango is v7.1, so it must be version 7.1 or newer:

bool IsMangoDevice = (Environment.OSVersion.Version >= new Version(7, 1));

We can also get access to types we don’t have yet in the 7.0 compiler but the 7.1 device has. For example, the StandardTileData class used to create secondary tiles for your app can be accessed using its full name and assembly:

Type t = Type.GetType("Microsoft.Phone.Shell.StandardTileData, Microsoft.Phone");

If we continue down this path, we can actually create a secondary tile on a mango device, and still have the app be 7.0. That means you can TODAY submit an app to the marketplace that uses mango features, and people with developer devices will get mango features now! (again note that this might cause problems during marketplace certification, but some apps has already made it through and is available today!)

Anyway… here’s the code that creates a secondary tile:

//get the constructor for the StandardTileData and create a new instance of it
var newTileData = t.GetConstructor(new Type[] { }).Invoke(null);
//Get the setter method for the title property
var setMethod = newTileData.GetType().GetProperty("Title").GetSetMethod();
//Set the tile title
setMethod.Invoke(newTileData, new object[] { "This is my new tile" });
//Get the create method for the shell tiles
Type shellTileType = Type.GetType("Microsoft.Phone.Shell.ShellTile, Microsoft.Phone");
var createMethod = shellTileType.GetMethod("Create");
//Create the tile, with the uri and tile data
Uri uri = new new Uri("/MainPage.xaml?Test=This_Came_From_A_Secondary_Tile", UriKind.Relative)
createMethod.Invoke(null, new object[] {  uri, newTileData});

Or how about setting the system tray color?

GetSetMethod().Invoke(null, new object[] { Colors.Red });

Of course you should only call these methods if the device is a mango device, so use the check shown first before executing this code. I created an extension class that neatly encapsulates this and only executes the code if it’s supported. Examples:

//Set tray color if supported

//Add hold event handler to a control (onHold is of type RoutedEventHandler delegate):

//Show "Create secondary tile" button if supported:
createTileButton.Visibility = MangoExtensions.IsMangoDevice ? Visibility.Visible : Visibility.Collapsed;

//Create/replace tile:
MangoExtensions.CreateTile("My Tile", new Uri("/MainPage.xaml?parameter1=value1", UriKind.Relative));

You can download the entire extension class here: Download

WPF vs. Silverlight - Part 11 - Silverlight on Phone vs. Browser

See intro blogpost here.

Well technically this is not a WPF vs Silverlight post, but a SL vs WP7, but it still kinda belongs in this series.

Generally the differences in the API’s between Browser Silverlight and Windows Phone Silverlight are pretty slim. However dealing with the phone can be quite different anyway. First there’s often less security restrictions on the phone to worry about. Secondly there’s a lot of phone specific APIs like sensor data, camera, contacts etc). The screen is also smaller so often some controls doesn’t make sense to have on the phone, or needs to have a separate layout to enhance the experience on this small touch-centric screen. Lastly (and very importantly) the small amount of memory, processing power and battery life means that performance is a concern. This often forces you to go down a slightly different avenue for your application, and for certain custom controls.

For the API differences I’m again going to be cheap and just point you to the main resource on MSDN that has some really good info on that matter:

Other notable things:

  • In Silverlight for Windows Phone, effects such as Blur and DropShadow are not supported.
  • Custom pixel shaders are not supported, so the PixelShader type is not supported.
  • Silverlight applications on Windows Phone are hosted on the client device and do not run inside of a browser. Silverlight features that are based on a browser host are not supported. These features include the HTML DOM bridge, JavaScript programmability, and the Silverlight plug-in object reference.
  • Isolated storage on Windows Phone does not enforce quotas to restrict the size of isolated storage for Silverlight-based applications. The default quota size of 1 MB does not apply. (however there’s still a 2Gb limit on Isolated Storage for WP7, or less if you run out of space).
  • Manipulation events that Silverlight doesn’t have (well technically they are there but throw a not supported exception), are the same as in WPF, so WP7 has better touch closer to WPF than Silverlight.

Next: WPF vs. Silverlight - Part 11– Silverlight on Phone vs. Browser

WPF vs. Silverlight - Part 10 - XAML Parser Differences

See intro blogpost here.

The XAML parser for WPF and Silverlight are not one and the same, and this also means that there (for whatever reason) are differences in how they interpret the xaml (as kinda hinted at in part 7).

MSDN has a pretty good description on those differences, so I won’t repeat the entire thing (please go read it!), other than point to a couple of important items:

  • Silverlight 4 introduces a XAML parser that behaves differently than Silverlight version 3 and is closer to the WPF XAML parser implementation.  Silverlight includes a XAML parser that is part of the Silverlight core install. Silverlight uses different XAML parsers depending on whether your application targets Silverlight 3 or Silverlight 4. The two parsers exist side-by-side in Silverlight 4 for compatibility. (read: You are more likely to hit issues porting an SL3 app to WPF than from SL4)
  • In some cases, the XAML parsing behavior in Silverlight differs from the parsing behavior in Windows Presentation Foundation (WPF). WPF has its own XAML parser (read: We made a new XAML parser for Silverlight, and cut some corners...)
  • Object elements inside a ResourceDictionary in Silverlight may have an x:Name instead of or in addition to an x:Key. If x:Key is not specified, the x:Name is used as the key. (read: Always use x:Key since this works in both)

Most of the other differences are things supported only in WPF, which is to be expected since Silverlight is a subset. Again this is why I recommend starting with Silverlight and then porting to WPF.

Other things worth noting:

WPF v3.5 does not have a VisualStateManager. Silverlight “invented” this and WPF 4 added it. If you build for WPF 3.5, you can use the WPFToolkit, which adds this support to 3.5.

Compiler conditionals in XAML

As demonstrated in many of the previous parts, you can use compiler conditionals in code-behind (ie. #if SILVERLIGHT...) to write code specific to the platform. Unfortunately you don’t have that luxury in XAML. If you need to have different xaml for the different platforms, I haven’t found a way around duplicating the entire piece of XAML in each project. So no, this won’t work Sad smile :


Next: WPF vs. Silverlight - Part 11 - Silverlight on Phone vs. Browser