You are on page 1of 15

Introduction to Portable Class Libraries

Creating Reusable Cross Platform Library Projects

Overview
A key component of building cross-platform applications is being able to share code across various platform-
specific projects. However, this is complicated by the fact that different platforms often use a different sub-set of
the .NET Base Class Library (BCL), and therefore are actually built to a different .NET Core Library Profile. This
means that each platform can only use class libraries that are targeted to the same profile, so they would appear
to require separate class library projects for each platform.

There are two major approaches to code sharing that address this problem: Shared Asset projects and
Portable Class Library (PCL) projects.

Shared Projects use a single set of files and offers a quick and simple way in which to share code within a
solution and generally employs conditional compilation directives to specify code paths for various
platforms that will use it (for more information see the Shared Projects article and the Setting up a Xamarin
Cross-Platform Solution guide).
PCL projects target specific profiles that support a known set of BCL classes/features. However, the down
side to PCL is that they often require extra architectural effort to separate profile specific code into their
own libraries. For a more detailed discussion on these two approaches, see the Sharing Code Options
guide.

In this guide, were going to walk through creating a PCL project that targets a specific profile and then is used by
multiple platform-specific projects.

Requirements
PCL Support was added in Xamarin.Android 4.10.1, Xamarin.iOS 7.0.4 and Xamarin Studio 4.2. Portable Library
projects are automatically enabled in Xamarin Studio on OS X, and are built-in to Visual Studio 2013.

Visual Studio 2012 users may not have the latest PCL profiles installed (for example, to use with
Xamarin.Forms). These Portable Library Reference Assemblies 4.6 can be downloaded from Microsoft.

If you are using Xamarin Studio for Windows (without also having Visual Studio installed) you should download
the Portable Library Tools - be sure to follow the instructions to find and run PortableLibraryTools.exe
/buildmachine with the Command Prompt. After successfully installing the Portable Library Tools you'll have
to re-install Xamarin.Android to enable PCL for that project type.

Because Windows Phone 8 development requires Windows 8 or newer, you will not be able to create libraries for
some profiles that require those SDKs on Windows 7, regardless of which version of Visual Studio or Xamarin
Studio you have installed.

What is a Portable Class Library?


When you create a regular Application Project or a Library Project, the resulting DLL is restricted to working on
the specific platform it is created for. This prevents you from writing an assembly for a Windows Phone app, and
then re-using it on Xamarin.iOS and Xamarin.Android.

When you create a Portable Class Library, however, you can choose a combination of platforms that you want
your code to run on. The compatibility choices you make when creating a Portable Class Library are translated
into a Profile identifier, which describes which platforms the library supports.

The table below shows some of the features that vary by .NET platform. To write a PCL assembly that is
guaranteed to run on specific devices/platforms you simply choose which support is required when you create
the project.

Feature .NET Framework Windows Store Apps Silverlight Windows Phone Xamarin

Core Y Y Y Y Y

LINQ Y Y Y Y Y

IQueryable Y Y Y 7.5 + Y

Serialization Y Y Y Y Y

Data Annotations 4.0.3 + Y Y Y

The Xamarin column reflects the fact that Xamarin.iOS and Xamarin.Android supports all the profiles shipped
with Visual Studio 2013, and the availability of features in any libraries you create will only be limited by the other
platforms you choose to support (such as Windows Phone or Windows Store).

This includes profiles that are combinations of:

.NET 4 or .NET 4.5


Silverlight 5
Windows Phone 8
Windows Store Apps

You can read more about the different profiles' capabilities on Microsofts website.

Creating a PCL to share code has a number of pros and cons versus the File-Linking alternative:
Benefits

Centralized code sharing write and test code in a single project that can be consumed by other libraries
or applications.
Refactoring operations will affect all code loaded in the solution (the Portable Class Library and the
platform-specific projects).
The PCL project can be easily referenced by other projects in a solution, or the output assembly can be
shared for others to reference in their solutions.

Disadvantages

Because the same Portable Class Library is shared between multiple applications, platform-specific
libraries cannot be referenced (eg. Community.CsharpSqlite.WP7).
The Portable Class Library subset may not include classes that would otherwise be available in both
MonoTouch and Mono for Android (such as DllImport or System.IO.File).

To some extent both disadvantages can be circumvented using the Provider pattern or Dependency Injection to
code the actual implementation in the platform projects against an interface or base class that is defined in the
Portable Class Library.

This diagram shows the architecture of a cross-platform application using a Portable Class Library to share code,
but also using Dependency Injection to pass in platform-dependent features:
Xamarin Studio Walkthrough
This section walks through how to create and use a Portable Class Library using Xamarin Studio. Refer the to
PCL Example section for a complete implementation.

Creating a PCL

Adding a Portable Class Library to your solution is very similar to adding a regular Library project.

1. In the New Project dialog select the Portable Library option

2.

3. When a PCL is created in Xamarin Studio it is automatically configured with a Profile that works for
Xamarin.iOS and Xamarin.Android. The PCL project will appear as shown in this screenshot, the
References node will indicate that the library uses a subset of the .NET Framework (defined by the PCL
profile).

The PCL is now ready for code to be added. It can also be referenced by other projects (Application
projects, Library projects and even other PCL projects).
Editing PCL Settings

To view and change the PCL settings for this project, right-click the project and choose Options > Build > General
to see the screen shown here:

The settings on this screen control which platforms this particular PCL is compatible with. Changing any of these
options alters the profile being used by this PCL, which in turn controls what features can be used in the portable
code.

Changing any of the Target Framework options automatically updates the Current Profile; the screen will
also display a warning if incompatible options are selected.
If the profile is changed after code has already been added to the PCL, its possible that the library will no longer
compile if the code references features that are not part of the newly-selected profile.

Working With a PCL

When code is written in a PCL library, the Xamarin Studio editor will recognize the limitations of the selected
profile and adjust auto-complete options accordingly. For example, this screenshot shows the auto-complete
options for System.IO using the default profile (Profile136) used in Xamarin Studio notice the scrollbar which
indicates about half of the available classes are displayed (in fact there are only 14 classes available).

Compare that with the System.IO auto-complete in a Xamarin.iOS or Xamarin.Android project there are 40
classes available including commonly used classes like File and Directory which are not in any PCL profile.

This reflects the underlying trade-off of using PCL the ability to share code seamlessly across many platforms
means certain APIs are not available to you because they dont have comparable implementations across all
possible platforms.

Using PCL

Once a PCL project has been created, you can add a reference to it from any compatible Application or Library
project in the same way you normally add references. In Xamarin Studio, right-click on the References node and
choose Edit References then switch to the Projects tab as shown:

The following screenshot shows the Solution pad for the TaskyPortable sample app, showing the PCL library at
the bottom and a reference to that PCL library in the Xamarin.iOS project.
The output from a PCL (ie. the resulting assembly DLL) can also be added as a reference to most projects. This
makes PCL an ideal way to ship cross-platform components and libraries.

Visual Studio Walkthrough


This section walks through how to create and use a Portable Class Library using Visual Studio. Refer the to PCL
Example section for a complete implementation.

Creating A PCL

Adding a PCL to your solution in Visual Studio is slightly different to adding a regular project.

1. In the Add New Project screen, select the Portable Class Library option

2.

3. Visual Studio will immediately prompt with the following dialog so that the profile can be configured. Tick
the platforms you need to support and press OK.
4.

5. The PCL project will appear as shown in the Solution Explorer. The References node will indicate that the
library uses a subset of the .NET Framework (defined by the PCL profile).

The PCL is now ready for code to be added. It can also be referenced by other projects (Application
projects, Library projects and even other PCL projects).

Editing PCL Settings

The PCL settings can be viewed and changed by right-clicking on the project and choosing Properties > Library ,
as shown in this screenshot:
If the profile is changed after code has already been added to the PCL, its possible that the library will no longer
compile if the code references features that are not part of the newly-selected profile.

Working with a PCL

When code is written in a PCL library, Visual Studio will recognize the limitations of the selected profile and
adjust Intellisense options accordingly. For example, this screenshot shows the auto-complete options for
System.IO using the default profile (Profile136) used in Xamarin Studio notice the scrollbar which indicates
about half of the available classes are displayed (in fact there are only 14 classes available).

Compare that with the System.IO auto-complete in a regular project there are 40 classes available including
commonly used classes like File and Directory which are not in any PCL profile.

This reflects the underlying trade-off of using PCL the ability to share code seamlessly across many platforms
means certain APIs are not available to you because they dont have comparable implementations across all
possible platforms.

Using PCL
Once a PCL project has been created, you can add a reference to it from any compatible Application or Library
project in the same way you normally add references. In Visual Studio, right-click on the References node and
choose Add Reference... then switch to the Solution : Projects tab as shown:

The following screenshot shows the Solution pane for the TaskyPortable sample app, showing the PCL library at
the bottom and a reference to that PCL library in the Xamarin.iOS project.

The output from a PCL (ie. the resulting assembly DLL) can also be added as a reference to most projects. This
makes PCL an ideal way to ship cross-platform components and libraries.
PCL Example
The TaskyPortable sample application demonstrates how a Portable Class Library can be used with Xamarin.
Here are some screenshots of the resulting apps running on iOS, Android and Windows Phone:

It shares a number of data and logic classes that are purely portable code, and it also demonstrates how to
incorporate platform-specific requirements using Dependency Injection for the SQLite database implementation.

The solution structure is shown below (in Xamarin Studio and Visual Studio respectively):
Because the SQLite-NET code has platform-specific pieces (to work with the SQLite implementations on each
different operating system) for demonstration purposes it has been refactored into an abstract class that can be
compiled into a Portable Class Library, and the actual code implemented as subclasses in the iOS and Android
projects.

TaskyPortableLibrary

The Portable Class Library is limited in the .NET features that it can support. Because it is compiled to run on
multiple platforms, it cannot make use of [DllImport] functionality that is used in SQLite-NET. Instead SQLite-
NET is implemented as an abstract class, and then referenced through the rest of the shared code. An extract of
the abstract API is shown below:

public abstract class SQLiteConnection : IDisposable {

public string DatabasePath { get; private set; }


public bool TimeExecution { get; set; }
public bool Trace { get; set; }
public SQLiteConnection(string databasePath) {
DatabasePath = databasePath;
}
public abstract int CreateTable<T>();
public abstract SQLiteCommand CreateCommand(string cmdText, params object[]
ps);
public abstract int Execute(string query, params object[] args);
public abstract List<T> Query<T>(string query, params object[] args) where T :
new();
public abstract TableQuery<T> Table<T>() where T : new();
public abstract T Get<T>(object pk) where T : new();
public bool IsInTransaction { get; protected set; }
public abstract void BeginTransaction();
public abstract void Rollback();
public abstract void Commit();
public abstract void RunInTransaction(Action action);
public abstract int Insert(object obj);
public abstract int Update(object obj);
public abstract int Delete<T>(T obj);

public void Dispose()


{
Close();
}
public abstract void Close();

The remainder of the shared code uses the abstract class to store and retrieve objects from the database. In
any application that uses this abstract class we must pass in a complete implementation that provides the actual
database functionality.

TaskyAndroid and TaskyiOS

The iOS and Android application projects contain the user-interface and other platform-specific code used to
wire-up the shared code in the PCL.

These projects also contain an implementation of the abstract database API that works on that platform. On iOS
and Android the Sqlite database engine is built-in to the operating system, so the implementation can use
[DllImport] as shown to provide the concrete implementation of database connectivity. An excerpt of the
platform-specific implementation code is shown here:

[DllImport("sqlite3", EntryPoint = "sqlite3_open")]


public static extern Result Open(string filename, out IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_close")]
public static extern Result Close(IntPtr db);

The full implementation can be seen in the sample code.

TaskyWinPhone

The Windows Phone application has its UI built with XAML and contains other platform-specific code to connect
the shared objects with the user interface.

In contrast to the implementation used for iOS and Android, the Windows Phone app must create and use an
instance of the Community.Sqlite.dll as part of its abstract database API. Rather than using DllImport,
methods like Open are implemented against the Community.Sqlite assembly that is referenced in the
TaskWinPhone project. An excerpt is shown here, for comparison with the iOS and Android version above

public static Result Open(string filename, out Sqlite3.sqlite3 db)


{
db = new Sqlite3.sqlite3();
return (Result)Sqlite3.sqlite3_open(filename, ref db);
}

public static Result Close(Sqlite3.sqlite3 db)


{
return (Result)Sqlite3.sqlite3_close(db);
}

Summary

This article has briefly discussed the benefits and pitfalls of Portable Class Libraries, demonstrated how to create
and consume PCLs from inside Xamarin Studio and Visual Studio; and finally introduced a complete sample
application TaskyPortable that shows a PCL in action.

You might also like