Monday, January 14, 2013

Put all your POCO’s in a PCL

We recently introduced a small, but useful, change to our Windows 8 solution.

We put all our POCS’s in a PCL.

POCO = Plain Old CLR Objects (POCOs)

PCL = Portable Class Library

Windows 8 Store Apps can leverage only a subset of the .Net framework.  Same applies for Silverlight or Windows Phone projects.  Which means that we cannot reference a regular .Net Assembly from a Windows 8 App, as the .Net assembly could be using classes which are not available to Windows 8 Apps.

In Visual Studio, if you try to refer a .Net class library project from Windows Store App project, you will get an error: Unable to add a reference to project 'ClassLibrary1'. The error message is not very useful. The error message when you try to reference an .Net assembly instead of a Visual Studio Project is more informative: A reference to 'ClassLibrary1.dll' could not be added. The project targets '.NETCore' while the file reference targets '.NETFramework'. This is not a supported scenario.

Multiple Copies of Code:

Without Portable Class Library (PCL), if you are developing an Application which needs to be supported on different Microsoft frameworks, you may end up duplicating the code for each of the platforms. Over a period of time, you might end up with a lot of almost similar, but duplicate code on each of the platforms. This of course is difficult to maintain.

PCL to the rescue:

Portable Class Library (PCL) project in Visual Studio 2012 comes to the rescue. In a PCL project, you can use only those classes which are supported across the different platforms. A PCL project or assembly can be referenced from Widows 8 Store App, Windows Phone App, and Silverlight application.

When should we use PCL?

Some useful scenarios are:

·         If you plan to write a application which you plan to support on different .Net platforms in future

e.g. You are developing a traditional Windows App for Win 7. Your organization does not even allow Windows 8 OS to be installed on its machines (as of today). Even if you have no current plans for targeting Windows 8 Apps, you can make it easier to upgrade (in future) by using PCL as much as possible.

·         Entity Classes in PCL:  e.g. You are developing a Windows 8 App which calls a .Net Web Service.

This was the scenario I was working on. The Windows 8 App called a .Net Web Service (REST using ASP.Net Web API to be more accurate) for data. We had defined classes to pass the data from Web Service to the Win 8 App (being developed in XAML and C#). Before PCL, we ended up defining the same entities twice, once for the Web Service project and once for the Win 8 App project. So maintenance was becoming an issue. We have now put all our entity classes in a PCL, so that they can be used by both the Web Service and the Windows 8 App projects.

To know more about PCL, refer the Microsoft link:

No comments: