Working with PCL's in the latest Xamarin.Android
03 Jul 2013 | Xamarin.Android"PCL support!So I kind of wanted to find out if it really was true, and it also happens to be that I am doing a project which needs to fetch something from the Internet, which is great to test out HttpClient in PCL's as well. The project also uses Stuart Lodge's fantastic MvvmCross framework, also with the new PCL stuff, and everything seems to work. However there are some things you have to work around until Xamarin releases tooling that allows you to reference PCL's in your Android and iOS projects in the Visual Studio plugin.
(Cross your fingers, sacrifice your favorite meal under the full moon, and your PCL projects should Just Work! Testing wanted.)"
So what I have tried:
- Download MvvmCross from the GitHub Repo, and rebuild the whole thing with the new Xamarin.Android version.
- Create a new PCL Library project in either Xamarin Studio or Visual Studio. I choose to target WP8, Store apps and .NET 4.5.
- Grabbed prerelease Microsoft.Net.Http package for the PCL. This also imports some Bcl stuff which allows you to use Async in the PCL. Now you should be able to use HttpClient and Async, sweet!
- For the Android project, here what is tricky. VS will complain that the Android project does not support PCL's, but it is lying! What you can do is either manually add a reference in the .csproj file or open up the project in Xamarin Studio and do it there.
- You will also have to grab the DLL's from the packages folder in your solution and import System.Net.Http, System.Net.Http.Extensions and System.Net.Http.Primitives from the Microsoft.Net.Http NuGet package you downloaded. I took if from the portable-net40+sl4+win8+wp71 folder.
- Now do your MvvmCross stuff, I just bound a button to a Command in my ViewModel, which calls a method in a service, which then in turn uses HttpClient to fetch some stuff from a Web Service.
Made a video describing the whole thing in more details:
Sample code can be found in my GitHub repo