Just to be clear, this is not a necessary step for us to take in our conversion process. But it’s a step that spreads some light on some of the differences regarding how you write code for Windows Phone and Windows 8. You can even say that it will show how much easier life gets with C#5 and .NET 4.5.

We’ll take a look a the heart of the application – where the data is fetched from the server. Usually, I prefer to do a web request using HttpWebRequest instead of WebClient. Mostly because a callback from a HttpWebRequest is not executed on the UI thread (explained here by Andreas). This gives us the opportunity to do some heavy lifting on a background thread (such as parsing JSON or XML) not ruining the user experience.

But now – the much loved HttpWebRequest, must step aside for HttpClient that came with .NET 4.5.

This post is a part in a series – you can find the full index here.

Using HttpWebRequest

This code is more or less directly copied from our Windows Phone application. As you can see we do a simple web request.

We also send in two actions with the request, that handles either a successful response or a failure. This pattern has worked well for us, but as you can see the code is quite messy. Much of that comes from having to handle the callback (and it gets even worse if we want to do a POST) in a different method.

Using HttpClient

One big reason that HttpClient is so nice to use has actually more to do with language features than HttpClient itself. Let’s take a look on how we can rewrite or web request using HttpClient, async and await.

Much nicer isn’t it? We can still do everything that we could do before, the difference is that we can get rid of the callback thus making the code more readable. In fact, we can make it even slimmer!

Very nice indeed. So we have actually replace two methods and 20 lines of code with a single method with 3 lines of code. It’s stuff like this that makes it hard to keep a common codebase between Windows Phone 7 and Windows 8. There are just too many goodies in Windows 8 that you want to use.

Thoughts

We think that it’s ok to just go wild and do any changes to you want in your Windows 8 project. You can just ignore that it looks different from your Windows Phone project. Later, when Windows Phone 8 arrives you already have a solid foundation that you can re-use when updating your Windows Phone application.

So don’t be afraid of refactoring and improving your existing code. You’ll be able to use it later on.