Xamarin Dev Days Lab – Prism Step 3

Introduction

In our last post, we set up the view model for the SpeakersPage and made use of the built in view model functionality included in Prism. We setup a base view model for our app to contain common functionality. The SpeakersViewModel class has the implementation code for retrieving the list of speakers embedded in the view model itself. Fine for a demo, but in a real app, we would be better served by moving this functionality out and using it via an interface. By implementing the functionality as an interface, we will be able to reuse the code in other view models. Since the SpeakersPageViewModel only knows it via the interface, we will also be able to mock the service with known values for use in unit tests, without changing the view model. And we can use the Prism framework and the dependency injection that is built in to make this easier. So lets take a look at this.

The Interface

The first thing we want to do is look at the functionality that is currently in our view model class. All it is doing is calling a web api to return a list of speakers. That seems pretty straight forward. Let’s start our interface with that:


public interface ISpeakersService
{
    Task<List<Speaker> GetAllSpeakersAsync();
}

Implementing will be easy: we already have all the code that we need in the view model from the demo app:


public class SpeakersService : ISpeakersService
{
    public async Task<List<Speaker>> GetAllSpeakersAsync()
    {
        using (var client = new HttpClient())
        {
            //grab json from server
            var json = await client.GetStringAsync(
                "http://demo4404797.mockable.io/speakers");

             //Deserialize json
             var items =
                JsonConvert.DeserializeObject<List<Speaker>>(json);
             return items;
        }
    }
}

//

From above, you can see that we have just moved all of the implementation code from the view model into a separate service object. So how do we start using this new code in our SpeakersViewModel?
The first thing we need to do is register this service in our App object. Remember that we are registering via an interface: this means we can change out the implementation at any time.
Here is the RegisterTypes function in the App object updated to register the service:


protected override void RegisterTypes()
{
    Container.RegisterType
        <Services.ISpeakersService, Services.SpeakersService>();
    Container.RegisterTypeForNavigation
        <View.SpeakersPage, ViewModel.SpeakersViewModel>();
}

Next we need to refactor the SpeakersViewModel: we will add the interface to the view model constructor and change the GetSpeakersAsync to call the interface to retrieve the speakers data:


public class SpeakersViewModel : BaseViewModel
{
    private Services.ISpeakersService _speakersService = null;

    public SpeakersViewModel(Services.ISpeakersService speakersService)
        : base()
    {
        _speakersService = speakersService;
    }

    /// other parts of the view model go here
    /// now lets look at GetSpeakers ...
    private async Task GetSpeakers()
    {
        if (IsBusy)
            return;

        Exception error = null;
        try
        {
            IsBusy = true;

            var items =
                await _speakersService.GetAllSpeakersAsync();
            Speakers.Clear();

            foreach (var item in items)
                Speakers.Add(item);
        }
        catch (Exception ex)
        {
            error = ex;
        }
        finally
        {
            IsBusy = false;
        }

        if (error != null)
            await Application.Current.MainPage.DisplayAlert(
                "Error!",
                error.Message,
                "OK");
    }

}

So what do we have above? All of a sudden the ViewModel has a dependency on ISpeakersService. But we weren’t creating the view model in the first place: instead, Prism and the AutoWireViewModel attached property (see the previous blog post) are creating the view model for us and attaching it to the page. When Prism does this, it uses the container that was selected (step 01 blog) to create the view model and all the dependencies that are required for the view model, and it does this via reflection and then looking at what you specified in the App.RegisterTypes method. I hope that you can see that you can change up the implementation details of the interface without ever affecting the view model itself. You can even unit test your view model by mocking the service.

Now the view model just makes a call to retrieve the speakers. It has no idea if the speaker are read from a web api, a database, a file or even from memory! It just knows to make the call and it will get the data.

I really want to emphasize this: the view model knows nothing. It has no dependency on any implementation and you can change that around as you see fit! In fact, I am going to change the code of the SpeakersService implementation. I captured the json payload that was returned from the web api and saved it as a constant in the implementation. Now instead of calling out to the web api, I just return the json payload directly, and now for testing, everything is much quicker. And as mentioned earlier, using these known values, I can use this implementation for unit testing of the view model.


public class SpeakersService : ISpeakersService
{
    /// you can see this actual string value in the GitHub repo
    /// under step 03
    private const string JsonResponse =
        "...json response string captured from web api";

    public async Task<List<Speaker>> GetAllSpeakersAsync()
    {
        var items =
            JsonConvert.DeserializeObject<List<Speaker>>(JsonResponse);
        return items;
    }
}

Recap

We have taken the next step in making the dev days app a little more production worthy. We took out the implementation of our speakers service away from the view model, defined it as an interface and injected that into our view model. We used the dependency injection that is built into Prism to inject the implementation of the service into the view model. And then for fun (and quicker testing), we changed the implementation of the interface to serve up the results from a json payload that had been captured previously. Now we can do testing much quicker.

All of this code can be found in the Step03 portion of the repository. Make sure you check out the two different implementations of ISpeakersService contained in the SpeakersService.cs file and how they could be registered in App.cs.

The next step will be to add navigation to the app so we can see the details of a selected speaker.

Xamarin Dev Days Lab – Prism Step 2

This is a continuation from the first post. You can find all of the code in my GitHub repository under step 2.

Viewmodels

I think most of us know what a viewmodel is and have an understanding of the MVVM pattern. If you don’t know, or need a refresher, there will probably be enough information in here for you to search around on.

The starter app already has one view model in it called SpeakersViewModel. You will remember it as the class that implements INotifyPropertyChanged. This interface is what tells the data binding system to update the UI, and when the UI changes, to update the property in the view model. Every view model needs to implement this interface, so right away, I hope you can see that we would like to move that functionality into a base class so as not to keep redoing it. And, as you might guess, Prism already has such a base class! I still like to make my own base class though, and include any app specific properties that I use a lot.

Below is a snippet of the SpeakersViewModel showing the implementation of INotifyPropertyChanged and how to use it from within the view model itself.


public class SpeakersViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string name = null) =>
        PropertyChanged?.Invoke(
            this,
            new PropertyChangedEventArgs(name));

    private bool _isBusy = false;
    public bool IsBusy
    {
        get { return _isBusy; }
        set
        {
            _isBusy = value;
            OnPropertyChanged();
        }
    }

    /// other properties go here
}

Let’s refactor the above view model to use the Prism helpers. First we will make our own app specific viewmodel base and derive from the Prism MVVM base class. Just for fun we will put the IsBusy property into the base class just to show the property in action.


public class BaseViewModel : BindableBase
{
    BaseViewModel()
        : base()
    {
    }

    private bool _isBusy = false;
    public bool IsBusy
    {
        get { return _isBusy; }
        set { SetProperty<bool>(ref _isBusy, value); }
    }
}

public class SpeakersViewModel : BaseViewModel
{
    SpeakersViewModel()
        : base()
    {
    }

    /// put other speakers functionality here
}

I think the above is pretty straight forward. We created a base class to hold common functionality and then redid our view model. We are still deriving from INotifyPropertyChanged (via BindableBase), and we still have the IsBusy property. If you go to the code in Step02 you can see the class in its entirety.
This brings us to our next problem: how do we get the view model instantiated in the class? In the case of the dev days sample app, it is being “newed-up” in the Page code-behind and being set manually. This is fine for very simple view models, but if we need services added to the view model, we are going to find it a bit more painful.

In the Prism world, you would let Prism take care of instantiating the view model for you, and by registering your services in the Container (see the App class), they will be added to the view model automatically. The way Prism manages this is by using an attached property. If the property is set to true, it will use a naming convention to find the view model type. Instead of using the “new” operator directly, it will use the UnityContainer to create it for you. The UnityContainer will determine (via reflection) if the view model depends on any services, and if so, inject those services into the view model for you. Once it has been created, it will attach it to the BindingContext of the page. What does this look like?

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="DevDaysSpeakers.View.SpeakersPage"
Title="Speakers">

</ContentPage>

The important line is the one containing AutowireViewModel=”True”. First we need to setup the namespace so that we can attach the AutowireViewModel property to the page. If that value is true, the logic behind the property will use naming conventions to find the view model class and then create it and bind it. The default conventions is that all pages are stored in the “Views” folder and the view models are stored in the “ViewModels” folder. The full name of the view model will be the name of the page with “ViewModel” appended. In the above example, Views.SpeakersPage will become ViewModels.SpeakersPageViewModel.

We also need to remove the view model and binding that we did in the page code-behind. In the SpeakersPage constructor, remove everything except for the constructor. It should now look like this:


public partial class SpeakersPage : ContentPage
{
    public SpeakersPage()
    {
        InitializeComponent();
    }
}

If you were paying really close attention, you would notice that in our dev days app, we are actually using the “View” and “ViewModel” folder, so we are probably going to have to override the default functionality. There are two ways to do this: first is to override the default view model resolver function. This is a bit more involved, and I am going to look at this functionality in another blog post. The other method is to specify the view model type when you register the page for navigation. In your App.RegisterTypes function, change your SpeakersPage registration to look like this:

protected override void RegisterTypes()
{
    Container.RegisterTypeForNavigation
        <View.SpeakersPage,ViewModel.SpeakersViewModel>();
}

Now any time we navigate to the SpeakersPage, the SpeakersViewModel will be created and injected. If you run the app now, you should see that the UI looks exactly the same, and that you can click on the sync button and it displays the results on the main page.

Recap

To recap, what we have done is changed how the view models are created and made use of the Prism base view model. We also made use of the Prism technique of automatically creating and injecting the view model into the page BindingContext. Our next step will be to abstract out the the web api service that is inside the SpeakersViewModel so we can show how the dependency injection works within Prism: more importantly, it makes your app more testable and maintainable.

You can find the code under Step 02 of my GitHub repository.

Xamarin Dev Days Lab – Prism Step 1

One of the goals that I gave myself this year was to start improving on my public speaking. It is something that I often find difficult and I wished to improve. So earlier this year, I did a presentation to the Vancouver Windows Platform Development meetup group, and it was on developing a UWP app with a hamburger style menu and using the Prism framework.

I think it went pretty well, and I learned a lot, and not just on public speaking. Giving the presentation meant I had to dig into the framework more than I normally would to learn why things were done a certain way, and how they were done. There is a lot of great stuff to learn in Prism.

I had used Prism previously for regular WPF desktop apps before and was pretty happy with it. If you are unfamiliar with the library, here is an abbreviated history: it was started by the Microsoft Patterns and Practices Teams as a WPF library to help show developers how to architect apps in a modular and maintainable manner. Along the way it added support for Silverlight, Windows Phone and Windows Universal. After version 5, it was released out into the community to maintain and enhance. Silverlight, Windows Phone and Windows Universal were dropped and Universal Windows Apps and Xamarin Forms were added. In addition to keeping your app maintainable, it also helps out with common patterns such as MVVM, messaging, logging and dependency injection. It also helps out with platform specific things such as navigation.

I have had the idea of doing a series of posts on using Prism with Xamarin Forms for a while now, and was stuck on a suitable demo project. During the Xamarin Dev Day hands on lab, I came up with the idea of converting that app into a Prism app. At first, I will stick to the basics and then maybe follow up with some more detailed posts on specific subjects such as navigation and view model injection.

The first thing we are going to do here is take the dev days sample app and build it up to where it gets the list of speakers and shows the details of the selected speaker. I have it setup in the following repository https://github.com/MichaelPonti/XamarinPrism under DevDaysSpeakers. If you clone the repository, restore packages and build the droid app, you should be able to load the list of dev days speakers and navigate to their detail page.

Note: I am just going to stick to the droid project and not show iOS or UWP.

Next what we will do is add in the nuget packages for Prism and then fix up the App object.

When using Prism, your first need to decide what kind of dependency injection you are going to use. I always seem to default to Unity: it was the first container that I had used and has always worked well for me. Out of the box, Prism comes with Unity, Ninject, AutoFac and DryLoc. Pick the one that you like and go with it, or, use something else if you want to put in a bit of extra effort. Let’s add Prism.Unity.Forms as shown below:

nuget

Add nuget package to projects in solution.

Adding Prism.Unity.Forms will add in the following items to your projects:

  • Prism.Unity.Forms
  • Prism.Unity
  • Prism
  • Microsoft.Practices.Unity
  • Microsoft.Practices.ServiceLocation

Now that we have Prism installed in the app, let’s setup our App object (located in the shared portion of the solution). If you were at one of the dev days, or have done any Xamarin Forms in the past, you know the app class is the main entry point. Each of the platform specific projects will jump into the app object to get at the cross-platform code.

The easiest thing to do is to just comment out the existing class and replace it with the following:


public class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null)
        : base(initializer)
    {
    }

    protected override void OnInitialized()
    {
        NavigationService.NavigateAsync("SpeakersPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation<View.SpeakersPage>();
    }

    protected override void OnSleep()
    {
        base.OnSleep();
    }

    protected override void OnResume()
    {
        base.OnResume();
    }
}

So what do we have up there? Use the OnInitialized to handle tasks once the App is up and running. At the very least, we are going to navigate to the first page here. The other important piece is the RegisterTypes function. In here we will register our services and also our pages for navigation. For now, all we are going to do is register the SpeakersPage.
If you run the app now, you should find that it starts up and displays the main page. If you click on the button, that should still function as well. At this point, it will crash if we try to navigate to the details page of one of the listed speakers.

We have a pretty good start here and it is time to wrap up. I have decided to talk about the MVVM support Prism provides first instead of fixing the navigation crash. One of the nice things about Prism is that it abstracts navigation away from knowing page types and moves navigation into the view model. So we will get our view model setup first.

Stay tuned for step 02!

XamarinDevDays Vancouver Recap

Hello everyone, just a small follow up on the event yesterday. It was a nice introduction to Xamarin, and we were well led by the presentation team of Mark Schramm (@markbschramm), Adrian Stevens (@Adrian_stevens), Jan Hannemann (@bitdisaster) and Sergiy Baydachnyy (@sbaidachni).

Presentations from Adrian, Jan and Sergiy preceded lunch (thanks Microsoft) and afterwards, Adrian led us through a sample app using Xamarin Forms. If you want a quick introduction to Xamarin Forms development, head over to the dev days GitHub repo (https://github.com//xamarin/dev-days-labs) and follow the hands on lab. It is a pretty good introduction.

For my part, I am going to turn that app into a series of blog posts on using the Prism framework. So keep your eyes open for that.

Enjoy your Sunday!

Xamarin Dev Days – Vancouver Oct. 22

There is an Xamarin Dev Days being held in Vancouver this Saturday, Oct 22nd at the Microsoft Vancouver Headquarters. I heard there is about 160 attendees, all sold out and there is a waitlist. I’m going to be there, and am pretty excited about it.

If you are in Vancouver and attending, make sure you say hi. Sounds like I will be helping out the organizers with checking people in etc. so I should be easy to spot. Let me know what you think of the content on the blog.

Hope to see you there!