XAM110 Intro to Cross-Platform

Exercise 3: Share code using a .NET Standard library

To explore .NET Standard class libraries, we will implement some shared code within a few .NET Standard target versions to see how it affects the available APIs.

To be able to use some of the .NET Standard components in your projects, you will also need to have the .NET Core SDK installed. You can download the .NET Core SDK (now referred to as the .NET SDK) to add the necessary components. On Windows, the .NET Core cross-platform development workload in the Visual Studio Installer also installs the .NET Core SDK.

To complete the exercise, you will need Visual Studio for Windows or macOS with the Xamarin development tools installed. You will also need either an emulator/simulator or a device to run the exercise on. Please see the setup page if you need help installing the Xamarin development environment.

Open the starter solution

This exercise is a continuation of the previous exercise. You can use your existing solution or begin from the prior Exercise 2 > Completed solution in your copy of the cloned or downloaded course materials.


Add .NET Standard class library

Let's create a class library targeting .NET Standard in our solution. This will be where we test out the available APIs.

Work through the New Project wizard in Visual Studio to add a .NET Standard class library by following these steps.


Set initial .NET Standard version

If you didn't set the .NET Standard version to .NET Standard 1.0 in the new project wizard, set that in the project settings now.

  1. Right-click the library project in the Solution pad and chose Options.
  2. In the Project properties, under Build > General > Target framework choose .NETStandard 1.0.
Selecting initial .NET Standard target version of 1.0.

Before we start coding, let's set the initial target .NET Standard verison of our new class library as low as we can.

  1. Right-click the library project in the Solution Explorer and chose Properties.
  2. In the Project properties, under Application > Target framework choose .NET Standard 1.0.
Selecting initial .NET Standard target version of 1.0.

Reference .NET Standard library

  1. Add a reference to the new .NET Standard library to the existing MyTunes.Shared portable class library.
  2. Build the solution. The projects should all build properly - however our new .NET Standard library isn't doing any work yet.

Add an extension method

To show we have everything working, we'll add a simple extension method to call from our existing code.

  1. Open the default Class1.cs class provided with your new .NET Standard library.
  2. Change the namespace to MyTunes, as is was in our PCL. This will make it easier to consume the new extension without a using statement.
  3. Rename the class to SongExtensions, and make it static for the extension method.
  4. Add a new static extension method named RuinSongName that extends the string type and returns a string instance.
  5. The extension method should return a string.Replace that alters any instance of Crocodile in a song name with Alligator.
namespace MyTunes
{
    public static class SongExtensions
    {
        public static string RuinSongName(this string songName)
        {
            return songName.Replace("Crocodile", "Alligator");
        }
    }
}

Call the extention method from PCL

  1. Open SongLoader.cs in the existing MyTunes.Shared PCL.
  2. Modify Load to call our new extension method, altering the song name for each song in a foreach loop.
public static class SongLoader
{
    …
    public static async Task<IEnumerable<Song>> Load()
    {
        using (var reader = new StreamReader(OpenData()))
        {
            var songs = JsonConvert.DeserializeObject<List<Song>>(await reader.ReadToEndAsync());
            foreach (var song in songs) { song.Name = song.Name.RuinSongName(); }
            return songs;
        }
    }
}

Run the app

On your preferred platform, run the MyTunes app to make sure you see a song featuring the modified title "Alligator Rock".

MyTunes app running on UWP, showing the list of songs that includes a title modified by our new extension method, showing "Alligator Rock" by Elton John instead of "Crocodile Rock".
MyTunes app running with an altered song list.

Overreach .NET Standard version

Next we'll see what happens when we try to use code outside our current .NET Standard version.

Add HttpClient call

For a sample scenario, let's pretend we want to call out to a web service in our new RuinSongName method.

Note: This is simply to demonstrate the concept. In practice, calling a web service for every song name would likely be terribly slow for your users.
  1. To keep our HttpClient around, start by adding a static field to our SongExtensions class and the required using System.Net.Http statement. In the editor, notice Visual Studio is telling you it can't find the HttpClient type. We will fix this next.
using System.Net.Http;

namespace MyTunes
{
    public static class SongExtensions
    {
        static HttpClient httpClient = new HttpClient();
        …
    }
}

Change .NET Standard version

Visual Studio is warning us about our use of the HttpClient type. This is because that set of APIs are not available in .NET Standard v1.0. Attempting to build our project now would result in a build error.

  1. Right-click the library project in the Solution pad and chose Options.
  2. In the Project properties, under Build > General > Target framework choose .NET Standard 1.1.
Incrementing .NET Standard target version to 1.1.
  1. Right-click the library project in the Solution Explorer and chose Properties.
  2. In the Project properties, under Application > Target framework choose .NET Standard 1.1.
Incrementing .NET Standard target version to 1.1.
  1. Try building your app.

Now that we are targeting the version of .NET Standard that first included the HttpClient APIs, our code will now compile successfully.


Exercise summary

In this exercise, you have utilized a library targeting .NET Standard to see how it can interact with your Xamarin apps and other libraries.

We created a simple extension method called from our existing Portable Class Library, and then worked through exceeding the API availablility of a .NET Standard version and how increasing our target version can make those API calls available to our shared binary.

You can view the completed solution in the Exercise 3 > Completed folder of your copy of the cloned or downloaded course materials.

Go Back