Home > Articles > Programming > C#

Introduction to the Portable Class Library (PCL) in Windows 8

  • Print
  • + Share This
  • 💬 Discuss
In this excerpt from Building Windows 8 Apps with C# and XAML, Jeremy Likness discusses the Portable Class Library (PCL), which is the ideal way to create shared components with business logic that you can reuse in your desktop and Windows 8 applications.

The Portable Class Library (PCL) is a special project type in Visual Studio 2012 that enables you to write assemblies that work on multiple .NET platforms. It is the ideal way to create shared components with business logic that you can reuse in your desktop and Windows 8 applications. An assembly built with the PCL project template can run on those platforms without being recompiled.

The PCL works by providing a targeted subset of APIs that are common to all platforms. When you create a PCL project, you are prompted to choose the frameworks you would like your code to run on, as shown in Figure 1.

Figure 1 Choosing target frameworks for the Portable Class Library

The amount of portable code available will depend on how old the frameworks are that you target, the number of frameworks you target, and type of the target frameworks. For example, a project that targets Xbox will have far fewer APIs available than a project that targets Silverlight. Likewise, the .NET Framework 4.0 will impose more limitations than a project that targets the .NET Framework 4.5. To see what APIs are available when you make a selection, expand the References for your project in the Solution Explorer. Right-click and choose Properties, and you will see a Path property. Copy the path and open it in Windows Explorer.

Figure 2 shows the folder available when you accept all of the defaults. Each combination of frameworks results in a new profile that contains the set of APIs that will work across those platforms. The reference actually uses a new feature known as Extension SDKs that allow references to include multiple files and configuration as opposed to a single project or assembly. You can read more about Extension SDKs online at http://msdn.microsoft.com/en-us/library/hh768146(v=vs.110).aspx.

Figure 2 A Portable Class Library profile

As you can see, the example profile supports several libraries. In addition to core services, there is support for networking, serialization, and web services, as well as XML including LINQ. For any of the referenced assemblies, you can use the ILDASM.exe tool to inspect the APIs that are available. The assemblies are simply copies of the .NET Framework assemblies that are supported by the particular profile.

The WintellogMvvm project for Chapter 9 has been refactored to take advantage of the Portable Class Library. The PortableWintellog project was created to support both the .NET Framework 4.5 and Windows 8 applications. The project provides a number of classes and interfaces that can be shared without modification between Windows 8 and desktop apps.

The Contracts folder contains interfaces that are shared across the platforms. PCL projects are the perfect place to define interfaces and contracts that don’t take strong dependencies on non-portable APIs. These interfaces can help you separate logic that is platform-specific from other logic through a concept called Inversion of Control or IoC for short. IoC helps you build classes that are easier to test and are more likely to be shared across multiple platform targets.

In the previous versions of the application, the StorageUtility class was a static class used to write and read from the local cache for the application. The BlogDataSource class controlled access to the StorageUtility. In a sense, it took on an additional responsibility to interface with the static methods exposed by the class. Although this was a straightforward way to access storage, it also created a strong dependency or coupling between the data source and the implementation of the storage logic. This prevented the BlogDataSource class from being shared by any environment other than the Windows 8 platform. It also made it tough to test the class because any test would require that appropriate storage exists.

In the PortableWintellog project, the control has been inverted. This simply means the BlogDataSource class no longer has the responsibility of determining how storage works. Instead, it works with the IStorageUtility interface. The interface provides the method signatures to save and restore items but does not impose any type of implementation. This makes the BlogDataSource more loosely coupled because it no longer has a direct dependency on the storage implementation.

There are numerous advantages to this approach. First, it is possible (and easy) to test the storage logic in the BlogDataSource class without relying on the presence of storage. You can easily create a helper class (as you see later in this chapter) to emulate storage for the purpose of testing. Second, you can implement the appropriate storage based on the target environment. The WintellogMvvm project contains an implementation for Windows 8 apps. The WintellogWpf project, a desktop app based on WPF, contains an implementation for desktop applications. Even though the implementations are different, the interface allows the same BlogDataSource class to be shared between both versions of the application.

Take a look at the WintellogWpf project. It references the portable class library and reuses all of the logic contained within the BlogDataSource class. This includes the logic to fetch individual blogs and items from the list, the interaction with the cache, and even some online functions. The HttpClient is shared between both desktop and Windows 8 applications, so it is used consistently to load the page for a post to parse related images.

The StorageUtility implementation uses the local file system to store the cache instead of isolated storage. An internal helper method computes a path to the application folder on the system:

private static string GetRootPath()
{
    return Path.Combine(
        Environment.GetFolderPath(
        Environment.SpecialFolder.LocalApplicationData), 
        "Wintellog");
}

Here is the code to list files. It checks to see if the directory exists before querying for the file list. The code is wrapped in a Task to execute asynchronously:

var directory = Path.Combine(GetRootPath(), folderName);
return
    Directory.Exists(directory)
        ? Directory.GetFiles(directory)
        : new string[0];

Remember the earlier discussion about Inversion of Control? The application controls dependencies by injecting them at the start. In the App.xaml.cs file you’ll find the following snippets that map the portable contracts to WPF-specific implementations:

Ioc = new TinyIoc();
Ioc.Register<IStorageUtility>(ioc => new StorageUtility());
Ioc.Register<IApplicationContext>(ioc => new ApplicationContext());
Ioc.Register<IDialog>(ioc => new WpfDialog());
Ioc.Register<ISyndicationHelper>(ioc => new SyndicationHelper());

After the dependencies are resolved, the IoC utility is used to inject them into the BlogDataSource class through its constructor:

Ioc.Register(ioc => new BlogDataSource(
    ioc.Resolve<IStorageUtility>(),
    ioc.Resolve<IApplicationContext>(),
    ioc.Resolve<IDialog>(),
    ioc.Resolve<ISyndicationHelper>())); 

The technique of having an external helper inject the dependencies is referred to as Dependency Injection (DI) and is a common method for handling IoC. The small class for IoC included with the sample application only scratches the surface of scenarios available for IoC. There are many mature frameworks available, including one that I’ve used for several years, the Managed Extensibility Framework (MEF), that is available for use in Windows 8 through a NuGet package:

http://nuget.org/packages/Microsoft.Composition/

With all of the logic encapsulated in the various shared and local classes, it was straightforward to create some XAML in the MainPage.xaml for the blog. The functionality is far more basic than in the Windows 8 application, but it completely reuses the existing class. In fact, it demonstrates how you can have a significantly different look and feel while using the same business logic in your core classes, as evidenced by the screenshot in Figure 3.

Figure 3 The WPF version of the application

Sharing the code between platforms and applications is powerful, but there is an even bigger benefit to using the Portable Class Library for common code: testing. With this approach, you’ll only have to test the core components once even though they might be used by multiple applications. You might be asking, “What is the point of software testing?”

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus