Using Portable Class Libraries with .NET 4 and Visual Studio 2010

Portable class libraries have recently become so ubiquitous, that it's easy to forget they don't exist all that long. They weren't even part of .NET 4, when it was originally released in 2010. As long as you're using Visual Studio 2012 or later and targeting .NET 4.5, this is not really important. But once you start targeting .NET 4, you should better keep that in mind.

You might be referencing a portable class library in your project without even knowing it: it happened to me when updating CSLA to the latest version, which depends on Microsoft.Bcl.Async NuGet package implemented as a portable class library. This might affect your users if they're not keeping their .NET 4 installation up-to-date. As documented on MSDN, portable class libraries require update KB2468871, .NET 4.0.3 or .NET 4.5 installed. Although the minimum required update has already been distributed via Windows Update, you shouldn't take it for granted that all your customers already have it installed and fail to communicate the changed software requirements in time.

Of course portable class libraries affect the build process, as well. Again, if you have at least Visual Studio 2012 or Windows SDK for Windows 8 installed on your build server, you don't need to worry. If you only have Visual Studio 2010 or .NET 4 SDK, the build will fail with a rather non-descriptive error:

d:\TeamCity\BuildAgent1\work\1955cf2ba61a55d8\Packages\Microsoft.Bcl.Async.1.0.168\
lib\net40\Microsoft.Threading.Tasks.Extensions.dll error CS1684: Warning as Error:
Reference to type 'System.Net.WebResponse' claims it is defined in 'c:\Program Files 
(x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Net.dll', 
but it could not be found 
d:\TeamCity\BuildAgent1\work\1955cf2ba61a55d8\Packages\Microsoft.Bcl.Async.1.0.168\
lib\net40\Microsoft.Threading.Tasks.Extensions.dll error CS1684: Warning as Error:
Reference to type 'System.Net.WebRequest' claims it is defined in 'c:\Program Files 
(x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Net.dll', 
but it could not be found

Installing the above mentioned .NET framework updates of course doesn't have any effect, since they include only the runtime bits. Neither does it help to install .NET 4.0.3 Targeting Pack. To build .NET 4 projects, which reference portable class libraries, Portable Library Tools are required. Installing them from Visual Studio 2010 or from command line finally ensures a successful build.

I spent too much time figuring all this out. Hopefully this post will help others make it work sooner.

Copyright
Creative Commons License