Unable to Debug .NET Standard Project in XF UWP

Helpful Hint

Ran into a funny one today. I was trying to debug my XF project and it wasn’t loading the symbols for the .NET Standard project so it was not hitting any of my breakpoints. I am currently using Visual Studio 2017.7.1. This was happening in my UWP project.

Obviously that’s not too helpful, but luckily I found some help in the Xamarin Forms as to the setting that was causing the problem. It has to do with the type of debugging information your build outputs. All I needed to do was change it to “Pdb-Only” and we were good to go.
credit
dotnetstandarddebug

XF vs PWA: XF Setting Up the Dashboard Page

The Goal

In this post we are going to setup the Dashboard page. The purpose of this page is to list the users favorite routes and stops so that no matter where they are, they can proceed straight to that information. It will be a relatively simple page, really just two lists. Tapping an item on one of the lists will navigate to the appropriate page and display the favorite route or stop.

Laying out the Page

This will be a pretty simple layout. Just use a grid, four rows, an auto height row for each title and an equal expanding height row for each of the lists.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Label Grid.Row="0" Text="My Favorite Stops" />
    <ListView Grid.Row="1" ItemsSource="{Binding Stops}"></ListView>

    <Label Grid.Row="2" Text="My Favorite Routes" />
    <ListView Grid.Row="3" ItemsSource="{Binding Routes}"></ListView>
</Grid>

ViewModel

The view model is going to be just as simple. Two ObservableCollections to handle the lists and a pair of commands to handle the user tapping on a list item. If you remember from setting up the hamburger menu, we are going to derive our view model from the BaseViewModel class.

public class DashboardPageViewModel : BaseViewModel
{
    private INavigationService _navigationService = null;
    private IFavoriteService _favoriteService = null;


    public DashboardPageViewModel(INavigationService navigationService, IFavoriteService favoriteService)
    {
        _navigationService = navigationService;
        _favoriteService = favoriteService;
    }


    // binds to the routes list view
    private ObservableCollection<FavoriteRouteViewModel> _routes = new ObservableCollection<FavoriteRouteViewModel>();
    public ObservableCollection<FavoriteRouteViewModel> Routes
    {
        get => _routes;
        set => SetProperty<ObservableCollection<FavoriteRouteViewModel>>(ref _routes, value);
    }

    // binds to the stops list view
    private ObservableCollection<FavoriteStopViewModel> _stops = new ObservableCollection<FavoriteStopViewModel>();
    public ObservableCollection<FavoriteStopViewModel> Stops
    {
        get => _stops;
        set => SetProperty<ObservableCollection<FavoriteStopViewModel>>(ref _stops, value);
    }


    // user taps on one of the stops
    private DelegateCommand<FavoriteStopViewModel> _commandGoToStop = null;
    public DelegateCommand<FavoriteStopViewModel> CommandGoToStop
    {
        get
        {
            return _commandGoToStop ??
                (_commandGoToStop = new DelegateCommand<FavoriteStopViewModel>((stop) => { }));
        }
    }

    // user taps on one of the routes
    private DelegateCommand<FavoriteRouteViewModel> _commandGoToRoute = null;
    public DelegateCommand<FavoriteRouteViewModel> CommandGoToRoute
    {
        get
        {
            return _commandGoToRoute ??
                (_commandGoToRoute = new DelegateCommand<FavoriteRouteViewModel>((route) => { }));
        }
    }
}

So how do we get the view model into the page itself? If you remember from the first post, we have to register all of our pages that we navigate to with the container, and we do that in our PrismApplication RegisterTypes method. In this case, we will register the dashboard page and the view model as follows:

public partial class App : PrismApplication
{
    // other stuff here

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.Register<IFavoriteService, TestFavoriteService>();
        containerRegistry.RegisterForNavigation<Views.DashboardPage, ViewModels.DashboardPageViewModel>(Pages.Dashboard);
        /// other registrations
    }
}

In the above code, we are telling the navigation service that when we navigate to the DashboardPage, we should also inject the view model into the page’s DataContext member. Of course the navigation service will make use of the Container to resolve any dependencies that might be required for the view model, such as IFavoriteService and INavigationService. Notice that we also register the IFavoriteService implementation in the RegisterTypes function. We don’t have to do that for INavigationService as it is a core part of the Prism framework and already taken care of in the PrismApplication base class.

Initializing the View Model

Things are looking pretty good, but how do we initialize the data in our view model? This is another part where the navigation service in Prism really helps us. After it finishes constructing the page, injecting the view model and making it the active view, it will test to see if the view model that was injected in the data context implements the INavigationAware interface (check out INavigatedAware and INavigatingAware for more granular implementations). INavigationAware looks like this:

public interface INavigationAware
{
    void OnNavigatingTo(INavigationParameters parameters);
    void OnNavigatedFrom(INavigationParameters parameters);
    void OnNavigatedTo(INavigationParameters parameters);
}

We will have our viewmodel implement the INavigationAware interface and then load our data when the ‘OnNavigatedTo’ method is called.

public class DashboardPageViewModel : BaseViewModel, INavigationAware
{
    /// all the other stuff from above here



    public void OnNavigatedFrom(INavigationParameters parameters)
    {
        // nothing doing here
    }

    public async void OnNavigatedTo(INavigationParameters parameters)
    {
        var favStops = await _favoriteService.GetFavoriteStopsAsync();
        /// do something here with the collection
        var favRoutes = await _favoriteService.GetFavoriteRoutesAsync();
        /// do something here with the routes collection
    }

    public void OnNavigatingTo(INavigationParameters parameters)
    {
        // nothing happening here
    }
}

And that is most of the work for the dashboard page. Really the only thing left to do is to make sure that the event that is raised from tapping one of the listview items is routed to our DelegateCommand objects in the view model. For an example of that, check out my article here.

Storing the Favorites Data

By now, you might be thinking, how am I going to store the data for the favorites in a platform independant way and still be able to use it with my shared view model? I am glad you asked, because I think that will be the next post!

code in GitHub

IPlatformInitializer in Prism For Xamarin Forms Version 7

Introduction

The implementation of platform specific services has undergone some changes over the last few releases. At first, if a view model required a service, it would check the Prism container for implementations of a service. If it wasn’t registered there, it would look in the Xamarin Forms dependency injection system for the implementation. In the next iteration, it was recommended that developers use the IPlatformInitializer that was typed to the specific container that was being used in the project.

Using IPlatformInitializer was a better solution: if you use the Xamarin Forms dependency service it involved a call to a static instance that is hard to mock for your unit tests. So that wasn’t great for us. But there was still some improvments the Prism team wanted to make. The next (and current) release of the library is going to abstract the container type away from the library users so that the container type can be swapped with minimal fuss. So that means changes to the IPlatformInitializer interface.

So how does this work now?

Define Your Interface in the Shared Library

As an example, we could have a bluetooth service that communicates with some device. This is defined in either your shared project or some other project that is shared between all of your platform specific projects.

public interface IBtDeviceCommService
{
    Task<bool> InitAsync();
    Task<bool> SendCommandAsync(string command);
}

Implement Platform Specific Services

Next we need to define the classes in each of the platform projects. I am not going to show the actual implementation of the platform specific classes, but it would look something like the following

public class UwpBtDeviceCommService : IBtDeviceCommService
{
    public async Task<bool> InitAsync()
    {
        throw new NotImplementedException();
    }

    public async Task<bool> SendCommandAsync(string command)
    {
        throw new NotImplementedException();
    }
}

Setup the IPlatformInitializer For Each Platform

How do we get the platform specific implementation registered within the Prism architecture? Looking at the UWP platform again, we can perform the registrations with the following piece of code.

public class UwpPlatformInitializer : Prism.Ioc.IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.Register(typeof(IBtDeviceCommService), typeof(UwpBtDeviceCommService));
    }
}

The way the platform initializer gets called is that you pass it in as a parameter when you create the Prism Application object. In the UWP project, there is a default MainPage object. In the constructor for the MainPage, the application object is created and loaded. It looks like the following piece of code.

public sealed partial class MainPage
{
    public MainPage()
    {
        this.InitializeComponent();
        LoadApplication(new MyPrismApplicationClass(new UwpPlatformInitializer()));
    }
}

In the Android platform project, you create the Prism Application object in the MainActivity class. In the iOS project, the Prism Application object is created in the AppDelegate class.

XF vs PWA: XF Setup the Hamburger Menu

Introduction

Ok, now that we have a functioning app, the next thing we need to do is setup the hamburger menu that will allow the user to navigate to the various parts of the application.
In this app, we have a dashboard page that will list the favorite routes and stops for the user; a stops page that will show all the stops near the current location of the user; a routes page that will show the current location of the buses on the route; a donation page that will allow the user to make in-app purchases to support the app; a settings page that will allow the user to configure the app; an about page that displays app information and credits.

Create the Master Detail Page

In this, blog post, I am not going to get much into the styling of the apps and just concentrate on the functionality. I am going to post the results periodically and you can see any styling that I do there.
The master detail page has two sections: the master section and the detail section. The master section will contain the menu and the detail section will contain the menu selection. I don’t like all of the stuff that gets added in when you create a new MasterDetailPage in the “New Item” templates. I usually just add a new ContentPage and change the base class in the XAML and code behind. I also just declare the Master section contents in the MasterDetailPage itself.

The menu itself with be our app navigation. It will contain items for the dashboard, the route page, the stops page, donate, settings and about. Tapping on one of those items will navigate the detail section to that page.

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Mvb.Views.MvbMasterPage"
    Title="METROVAN BUS BUDDY">

    <MasterDetailPage.Resources>
        <ResourceDictionary>
            <converters:MenuItemTypeConverter x:Key="menuImageConverter" />

            <Style x:Key="MenuItemLabelStyle" TargetType="{x:Type Label}" 
                    BasedOn="{StaticResource MontserratRegularLabelStyle}">
                <Setter Property="TextColor" Value="{StaticResource WhiteColor}" />
                <Setter Property="FontSize" Value="{StaticResource MediumSize}" />
            </Style>

        </ResourceDictionary>
    </MasterDetailPage.Resources>

    <MasterDetailPage.Master>
        <ContentPage Title="MENU">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>

                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="2*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>

                    <ListView Grid.Row="1"
                              x:Name="menuItems"
                              ItemsSource="{Binding MenuItems}"
                              b:ItemTappedCommandListView.ItemTappedCommand="{Binding CommandNavigate}"
                              SeparatorVisibility="None"
                              BackgroundColor="Transparent"
                              VerticalOptions="StartAndExpand">

                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <StackLayout Orientation="Horizontal">
                                        <StackLayout.Triggers>
                                            <DataTrigger TargetType="StackLayout" Binding="{Binding IsEnabled,Mode=TwoWay}" Value="False">
                                                <Setter Property="Opacity" Value="0.6" />
                                            </DataTrigger>
                                        </StackLayout.Triggers>

                                        <Image Source="{Binding MenuItem,Converter={StaticResource menuImageConverter}}"
                                               Aspect="AspectFit"
                                               WidthRequest="22"
                                               HeightRequest="22"
                                               Margin="10,0"
                                               VerticalOptions="Center" />

                                        <Label Text="{Binding Title}"
                                               Style="{StaticResource MenuItemLabelStyle}"
                                               HorizontalOptions="Center"
                                               VerticalOptions="Center" />
                                    </StackLayout>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

                </Grid>
            </Grid>

        </ContentPage>
    </MasterDetailPage.Master>
</MasterDetailPage>

The main thing that I want to call out in the above XAML is that the menu is implemented as a ListView and we are implementing each choice with a DataTemplate that will display as an icon and a label. The icon is determined by an IValueConverter that converts the MenuType enum to an image source (see my post on IValueConverters). I should also mention that we add a behavior to the ListView so that when an item is tapped, it executes an ICommand. I think it best if I document that in a separate post.

The MasterPage View Model

The viewmodel for the master page is actually pretty sparse. It has an ObservableCollection of MenuItemViewModels and the ICommand used to navigate when the user taps one of the menu items. Just to complete the picture, below is the class for the menu item view model and the master page view model.

    public enum MenuItemType
    {
        Dashboard,
        Stops,
        Route,
        Donate,
        Settings,
        About,
    }

    // BaseItemViewModel implements INotifyPropertyChanged and invokes it through
    // the SetProperty<> function. 
    public class MenuItemViewModel : BaseItemViewModel
    {
        public MenuItemViewModel()
        {
        }

        public MenuItemViewModel(string title, MenuItemType menuItem, string navigationPath)
        {
            _title = title;
            _menuItem = menuItem;
            _navigationPath = navigationPath;
        }


        #region properties


        private string _title = null;
        public string Title
        {
            get => _title;
            set => SetProperty<string>(ref _title, value);
        }


        private MenuItemType _menuItem;
        public MenuItemType MenuItem
        {
            get => _menuItem;
            set => SetProperty<MenuItemType>(ref _menuItem, value);
        }


        private string _navigationPath = null;
        public string NavigationPath
        {
            get => _navigationPath;
            set => SetProperty<string>(ref _navigationPath, value);
        }


        #endregion
    }


Here is the important part of the master page view model:

    public class MvbMasterPageViewModel : BaseViewModel
    {
        private ILoggerFacade _logService = null;
        private INavigationService _navigationService = null;

        public MvbMasterPageViewModel(IEventAggregator messageBus, ILoggerFacade logService, INavigationService navigationService)
            : base(messageBus)
        {
            _navigationService = navigationService;
            _logService = logService;
            InitalizeMenuItems();
        }



        private void InitalizeMenuItems()
        {
            /// create menu items. The important thing is that we are defining a label for displaying
            /// in the menu, a menu type that will convert into a menu icon and a navigation path.
            /// repeat for each menu item. See below for a bit more info on Prism navigation.
            _menuItems.Add(new MenuItemViewModel("Dashboard", MenuItemType.Dashboard, $"{Pages.MyNavPage}/{Pages.Dashboard}"));
            // ...
        }


        private ObservableCollection<MenuItemViewModel> _menuItems = new ObservableCollection<MenuItemViewModel>();
        public ObservableCollection<MenuItemViewModel> MenuItems
        {
            get => _menuItems;
            set => SetProperty<ObservableCollection<MenuItemViewModel>>(ref _menuItems, value);
        }



        private DelegateCommand<MenuItemViewModel> _commandNavigate = null;
        public DelegateCommand<MenuItemViewModel> CommandNavigate
        {
            get
            {
                return _commandNavigate ??
                    (_commandNavigate = new DelegateCommand<MenuItemViewModel>(
                        async (menu) =>
                        {
                            if (menu != null && menu.IsEnabled)
                            {
                                try
                                {
                                    _logService.Log($"Navigating to {menu.NavigationPath}", Category.Info, Priority.None);
                                    await _navigationService.NavigateAsync(menu.NavigationPath);
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine(e.ToString());
                                    _logService.Log(e.ToString(), Category.Exception, Priority.High);
                                    throw;
                                }
                            }
                        }));
            }
        }
    }

I just want to call out that we are using the dependency injection capabilities of Prism to automatically add in the required constructor parameters. Remember from the first post in this series, we set that up in our Application class.

The detail section of the master detail page is going to contain a custom navigation page. There isn’t much in there that is special, I just set the navigation bar background and text color.

Prism Navigation Service

Let’s revisit the Prism navigation system. If you remember from the previous post, the first thing we need to do is register our pages with the container in the RegisterTypes method in the Application base. Each page registration is associated with a string key value. When you want to perform a navigation, you provide a navigation path based on those key values. The underlying Xamarin Forms navigation system relies on the type of the page for navigation. The awesome thing for us is that Prism abstracts that glue away to simple string values so that you can move your navigation calls into your view model with the rest of the business logic. And you can mock the navigation service for unit testing.

In our case, our navigation stack will be the master detail page, the navigation page and then the actual content page. We end up passing the navigation service a string value such as “/MasterPage/NavPage/DashboardPage”. Prism parses the path into segments and looks up each in the container. It sees that the MasterPage is a MasterDetailPage and knows that the next segment should be put in the Detail section of the page. It then sees that this page is a navigation page, so it knows to put the final page, the DashboardPage, into the content of the navigation page. The navigation service also handles the other possible scenarios such as tabs and modal displays.

Back To MvbMasterPageViewModel

With the help of the NavigationService, the MvbMasterPageViewModel is performing most of the navigation in the app, so we need to do our navigation relative to the master page. Each of our menu items will have a navigation path of “NavPage/DestinationPage”. As there is no leading “/” character, the navigation service knows that it is a relative path and will figure it out relative to itself.

Sample Code

Credits

Obviously there is Prism Github Repo
Also, some of the helper classes in the MyXamarinUtils project. bike360 sample

XF Platform Specific Styling

Introduction

Sometimes you need to specify XAML that is specific to the platform. Xamarin Forms already has a special class to help with this called OnPlatform. But I find that it isn’t always granular enough to handle the different instances of Windows: Windows, Windows Phone, Windows Tablet and Xbox. We can define our own custom handler to help us with this.

It looks like the following in XAML.

<!--
here is the declaration in the content page attributes:
xmlns:h="clr-namespace:AppName.Helpers"
-->
<Label Text="Display Custom Platform Styling">
    <Label.Margin>
        <h:OnCustomPlatform
            x:TypeArguments="Thickness"
            Android="5,40"
            iOS="10,20"
            Windows="20"
            WinPhone="4,8,4,8"
            WinTablet="12,8,12,8"
            Xbox="40" />
    </Label.Margin>
</Label>

A couple of things about the above code: the h: refers to the namespace that contains our OnCustomPlatform class. The other thing to note is that I don’t know if the Device and TargetIdiom objects in Xamarin Forms work with the Xbox, so use with caution if you are going to try this with an Xbox app.

How the Class Works

using Xamarin.Forms;

public sealed class OnCustomPlatform<T>
{
    public T Android { get; set; } = default(T);
    public T iOS { get; set; } = default(T);
    public T WinPhone { get; set; } = default(T);
    public T Windows { get; set; } = default(T);
    public T WinTablet { get; set; } = default(T);
    public T Xbox { get; set; } = default(T);
    public T Other { get; set; } = default(T);

    public static implicit operator T(OnCustomPlatform<T> p)
    {
        switch (Device.RuntimePlatform)
        {
            case Device.Android:
                return p.Android;
            case Device.iOS:
                return p.iOS;
            case Device.Windows:
                if (Device.Idiom == TargetIdiom.Desktop)
                    return p.Windows;
                else if (Device.Idiom == TargetIdiom.Phone)
                    return p.WinPhone;
                else if (Device.Idiom == TargetIdiom.Tablet)
                    return p.WinTablet;
                else if (Device.Idiom == TargetIdiom.TV)
                    return p.Xbox;
                else
                    return default(T);
            default:
                return p.Other;
        }
    }
}

And that is all there is. It is actually surprisingly simple to do though I admit, after a while it gets pretty verbose the more complex you get with your page.