Using Portable Class Library to write for both Windows 8 and Windows Phone

[This post is a part of a series of post about the Social Media Dashboard Sample. This post was written by Peter Bryntesson. For an introductory blog post, click here]

Portable Class Library is a great feature for writing cross platform code in .NET. Since the Social Media Dashboard Sample targets both Windows 8 and Windows Phone, we could put a lot of code in the Portable Class Library so we didn’t have to duplicate that code. So how do you create a portable class library?

First you need a non-express version of Visual Studio 2012. Since all the express versions target one Environment (Windows 8, Windows Phone etc), Portable Class Libraries just doesn’t make sense there. So you need Premium, Pro, Ultimate version of Visual Studio. Once you have that, do Add –> New Project and select as below:

image

 

Set the correct name and click OK. A new dialog comes up:

image

Here you can choose which frameworks you want to target. Based on that selection the Portable Class Library will automatically limit the .NET namespace available to what is common on all the target frameworks you choose. This will work with IntelliSense, compile as you go etc. The resulting assembly will be a single binary that runs on all those platforms.

It’s an excellent way of sharing code between platforms when your solution targets multiple devices. Projects implementing the MVVM (Model – View – ViewModel) pattern fits exceptionally well with Portable Class Libraries, although this sample doesn’t implement MVVM. For more information about Portable Class Libraries, click here. For more information about MVVM, click here.

So what is inside the Portable Class Library for the Social Media Dashboard? Well, basically three things:

  • Some base classes that others derive from. This includes HubDataCommon and BindableBase.
  • Data entity class describing the different types of data this app can show.
  • Helper classes to access these services and generate the content for this app.

So this was a short primer on Portable Class Libraries and how it is used in the Social Media Dashboard Sample.

For more information about Windows 8 app development, go here.

For more information about Windows Phone development, go here.