Most of us have often struggled and hacked our code to implement an assembly that we could use in different .NET target platforms. Portable libraries are here to help us to do exactly this.
Now there is an easy way to develop a portable assembly that works without modification in .NET Framework, Windows Store apps style, Silverlight, Windows Phone, and XBOX 360 applications.
The trick is that the Portable Class Library project supports a subset of assemblies from these platforms, providing us a Visual Studio template.
This recipe will show you how to implement a basic application and help you get familiar with Visual Studio 2012.
In order to use this recipe you should have Visual Studio 2012 installed. Note that you will need a Visual Studio 2012 SKU higher than Visual Studio Express for it to fully support portable library projects.
Here we will create a portable library and see how it works:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace pcl_myFirstPcl { public static class MyPortableClass { public static string GetSomething() { return "I am a portable class library"; } } }
using
reference to our portable library namespace.using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using pcl_myFirstPcl; namespace SilverlightApplication_testPCL { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Button_Click_1(object sender, RoutedEventArgs e) { String something = MyPortableClass.GetSomething(); MessageBox.Show("Look! - I got this string from my portable class library: " + something); } } }
We created a portable library from the Portable Class Library project template and selected the target frameworks.
We saw the references; note that it reinforces the visibility of the assemblies that break the compatibility with the targeted platforms, helping us to avoid mistakes.
Next we added some code, a target reference application that referenced the portable class, and used it.
We should be aware that when deploying a .NET app that references a Portable Class Library assembly, we must specify its dependency to the correct version of the .NET Framework, ensuring that the required version is installed.
A very common and interesting usage of the Portable Class Library would be to implement MVVM. For example, we could put the View Model and Model classes inside a portable library and share it with Windows Store apps, Silverlight, and Windows Phone applications. The architecture is described in the following diagram, which has been taken from MSDN (http://msdn.microsoft.com/en-us/library/hh563947%28v=vs.110%29.aspx):
It is really interesting that the list of target frameworks is not limited and we even have a link to install additional frameworks, so I guess that the number of target frameworks will eventually grow.