Developer Toolkit for Visual Studio Mac

Several years ago when I was still just a web developer wanting to break into mobile development, I asked myself how does anybody do this? You have to learn Java for Android, Objective-C or Swift for iOS.... of course then I learned about Xamarin. Without a doubt Xamarin makes the tedious tasks of mobile app development far easier by centralizing your code in one common language, and even further with Xamarin Forms by abstracting the UI into reusable code. That doesn't mean that creating a new app is by any means easy. In fact setting up a new app can take a lot of time.

Nearly a year and a half ago I introduced the Prism QuickStart Templates which were the first .NET Standard templates using the new project format available for Xamarin apps. The project took on a life of it's own and was loved by many even despite it's limited availability in the CLI. As I set out to bring the templates into Visual Studio for Mac, it again took on a life of its own. A number of developers and MVP's were gracious enough to give me their feedback on things they would like to see, and while it may have delayed my ability to release, what we have today is simply stunning.

Prism Template Studio and Developer Toolkit

Ok I admit it, it's a mouthful, and if you have a better name feel free to tweet it to @DanJSiegel. Why the mouthful, because it is absolutely jammed pack with so many tools, so many helpers, and so many templates, that every time I explain it someone asks, "well what about...", and I keep either responding yeah it does that too... or yeah we could add that. It's probably that second one that has admittedly  generated the most delay in getting this out. Whether you use vanilla Xamarin Forms or Prism you'll want to install the Prism Template Studio and Developer Toolkit. 

Templates

As the name suggests it contains the a Template Pack. This Template Pack isn't quite like anything you've seen before. There are 14 new project templates that ship in this Template Pack, including 7 projects for Unit and UI Testing, 3 more for building Prism Modules, and another 3 for Prism Applications, plus a new basic Xamarin Forms project template.

Each of the templates bring something special for different developers. You can still go with the traditional flat "Official" template, or one includes PropertyChanged.Fody with projects and tests separated into src and tests folders. You can also take advantage of the powerhouse QuickStart Template or the App Center Connected App. Both of these provide the to setup a project in VSTS and automatically configure a Build in App Center.

Tools

To start there is some integrated tooling for all of your Xamarin projects to enable support for the Mobile.BuildTools, you can connect an existing project to an app in App Center, and even get some quick links to the Prism Docs, GitHub issues, and StackOverflow. Over time you can expect to see additional tooling for App Center, and refinements to do more with VSTS and better expand on your ability to get started with Unit and UI Tests.

Get started today by making sure Visual Studio Mac is up to date, and then simply install the Prism Template Studio and Developer Toolkit from the Extension Manager.

Prism 7.1 Preview 3

Today we released the 3rd Preview for Prism 7.1. This is a very significant release for us and contains some very exciting changes.

Forms Dependency Resolver

At Build we released a special preview for Xamarin Forms. In that preview we released the much awaited ability to use your Application's DI Container to resolve types inside of Xamarin Forms such as your Renderers or Platform Effects. It was a great feature but there were some issues caused on Android by the transition from a default constructor to one that requires the Android Context. Preview 3 fixes this by adding a specific Android target to each of the DI packages to handle passing the Context to the Container while resolving your Renderers.

We asked the community and while people were very torn on the subject, it was very overwhelming that using the DependencyResolver is something that should be configurable. As a result we've updated PrismApplication's constructor to accommodate this. First we removed the optional parameter for IPlatformInitializer and simply provided both a Default constructor and one that takes IPlatformInitializer. Second we added a new constructor that takes both IPlatformInitializer and a boolean to control whether we should set the DependencyResolver. As you may have guessed both of backwards compatible constructors call the new constructor, and by default will pass false to prevent PrismApplication from setting the DependencyResolver. 

Just as with Preview 2, you can still override SetDependencyResolver in order to provide your own logic.

Known Issues

FFImageLoading is a very popular image handling library. Unfortunately the CachedImageRenderer as 2 completely unnecessary constructors as they will never be used by Xamarin Forms and they only serve to confuse a DI Container. By default most DI containers will attempt to resolve a type based on the constructor with the most arguments. In the event that more than one constructor exists with the same "Highest" argument count, it will select the first one. This is the case in the CachedImageRenderer which results in the container attempting to resolve the Renderer with CachedImageRenderer(IntPtr, JniHandleOwnership).

In order to handle this you will need to add a specific registration for the Renderer in your Android Initializer. This will look different based on which container you are using. If you're using DryIoc, you can easily add either of the following examples to fix the issue:

public class AndroidInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.GetContainer().Register<CachedImageRenderer>(made: Made.Of(() => new CachedImageRenderer(Arg.Of<Android.Content.Context>())));
        // OR with Reflection
        containerRegistry.GetContainer().Register<CachedImageRenderer>(made: Made.Of(typeof(CachedImageRenderer).GetConstructor(new[] { typeof(Android.Content.Context) })));
    }
}

Modularity

Modularity has been on my personal hit list for a while now, and Preview 3 makes some major changes to help accomplish the final goal of aligning the Modularity API between WPF and Xamarin.Forms as well as making it available for UWP. To start with we've moved the Modularity Exceptions from WPF to Prism.Core, along with ModuleInfo, IModuleInitializer, and IModuleManager. Among the changes, this means that Xamarin.Forms apps will be able to listen for the ModuleLoaded event and capture any exceptions that may occur during the Module's Initialization. 

For WPF developers defining their ModuleCatalog in XAML this means a break as ModuleInfo is now in Prism.Core. Rest assured though that some care has been taken to ensure that any API changes are addative and beneficial. An example of this is that the constructor's from Prism.Form's version of ModuleInfo were added to ModuleInfo in Prism.Core. For Prism.Forms developer's a bigger break in ModuleInfo was introduced by changing ModuleType from Type to string. While I say bigger break, this should only affect developers who are directly referencing ModuleInfo's ModuleType property. Since the Modularity API in Prism.Forms favor's generics this should have a minimal impact for most developers.

XAML Navigation

Yep, I said it... This was an amazing idea and PR that came from the community. Over the past week I've had a chance to dogfood this one, and I have high hopes for what this will empower developers to do. Up until now you would need to have a ViewModel, inject the NavigationService, create a command, and an action for the command that uses the NavigationService to navigate to some other page, and then bind that command to some Button. Now with XAML Navigation you can simply have:

<Button Text="Continue"
              Command="{prism:NavigateTo ViewB}" />

Just as an example this could be used to completely eliminate a ViewModel on a Page that is simply a landing page that simply prompts the user to continue. This could be very useful for pages used in OnBoarding new users where you are explaining how to do something in your app. There is full documentation on this feature in the Prism Docs. Be sure to read more there on how to use NavigationParameters which would again make it easier to handle scenarios where you are try to Navigate based on a Cell in a ListView or a RepeaterView that so many of us have implemented.

Additional Notes

Perhaps one of the first things that developers have had to learn with Prism.Forms is that you must name INavigationService 'navigationService' in your constructor otherwise it won't be injected into your ViewModel. While that hasn't been the case in DryIoc for a while, this is now a thing of the past for Autofac and Unity as well. 

While you may not have heard of this one before, SourceLink is an amazing new tool for OSS libraries to empower developers debugging experience. Sadly this only works in Visual Studio on Windows and is only in the Backlog for Mac for now, but for those working in Visual Studio 2017 this will let you step into Prism's code while you debug. 

Last but certainly not least. A few months ago Oren Novotny began talking to me about signing NuGet packages. After hearing what he had to say, I had to agree wholeheartedly that it was something we should do for our user base. Beginning with Preview 3, we are now signing each NuGet package as part of our release pipeline. This means that when you consume our packages you will be able to verify that the package actually comes from the Prism team and has not been altered between us and you.

Be sure to try out the new Prism 7.1 preview today and let us know what you think. Be sure there is more great stuff to come.

Prism 7.1 Preview 1

Maintaining a library can be exceptionally difficult. As time progresses new demands arise that weren't there when the API was first created. Sometimes simple work arounds can be found to prevent breaking library consumers when they upgrade. Sometimes the changes are no brainers that have no negative affects. Sometimes changes simply aren't made because the potential breaks are simply too risky. Other times the benefits simply outweigh the break and changes are made.

Prism 7.1 is largely the result of changes that the Prism Team has come to realize had to be made. As part of the overall Prism 7.X effort, the team has been working on bringing the API closer together across each platform target where possible. Currently this is perhaps most evident with the introduction of the Prism.Ioc namespace allowing developers to more easily port from one DI Container to another, and even create Prism Modules that are sharable across projects with different DI Containers.

In this release have made some major changes to better unify the API between Xamarin Forms and our ongoing work with Jerry Nixon to bring Template 10 to Prism for UWP. This effort though represented the need to create a binary incompatibility, a need to create some breaking changes, and an opportunity to greatly improve the API for Xamarin Forms developers. So what are the changes? For starters we've migrated most of the Prism.Navigation namespace from Prism.Forms to Prism.Core. After a lot of deliberation we ultimately decided that these changes should not be available to WPF developers as it just doesn't make sense for WPF applications. 

In addition to the binary incompatibility caused by moving the classes from one binary to another, this creates a secondary break in the WPF will NOT be supported for Xamarin Forms developers.

I mentioned that there are breaking changes and some opportunities for improvements as well. The break that you will encounter should be fixable with a simple Find/Replace in your IDE or text editor, as NavigationParameters is now INavigationParameters which changes the method signatures for INavigatingAware, INavigatedAware, INavigationAware, IConfirmNavigation, IConfirmNavigationAsync, and INavigationService. While that may provide you with some unique opportunities for testing, that isn't the exciting change. The change is the return type from INavigationService from a simple Task to Task<INavigationResult>. Why is that so great? Well for one thing if the Navigation failed for some reason you'll have access to a Boolean to more easily execute that logic. It's also great though because until now the NavigationService could make it harder to determine what type of exception may have been thrown. INavigationResult fixes this by returning the actual exception that was thrown allowing you greater control over what to do with it.

var result = await _navigationService.NavigateAsync("BadPage");

if(!result.Success)
{
    await _pageDialogService.DisplayAlertAsync(result.Exception.GetType().Name, result.Exception.Message, "Ok");
}

 

Perhaps my single favorite improvement in Prism 7.1 for Xamarin Forms developers is the inclusion of the ContainerProvider. This was born out of a desire to be able to declare types such as a TypeConverter that may rely on some service in your application. The ContainerProvider will allow you to declare in XAML, types that do not have a default constructor and inject any of your applications services into that type. 

<?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.Ioc;assembly=Prism.Forms"
    xmlns:converters="using:Prism.Forms.Tests.Mocks.Converters"
    Title="{Binding Title}"
    x:Class="Prism.DI.Forms.Tests.Mocks.Views.XamlViewMock">
    <ContentPage.Resources>
        <ResourceDictionary>
            <prism:ContainerProvider x:TypeArguments="converters:MockValueConverter" x:Key="mockValueConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <Entry x:Name="testEntry"
           Text="{Binding Test,Converter={StaticResource mockValueConverter}}" />
</ContentPage>

Unity

Unity has been one of the most popular containers for Prism Developers. I have no doubt that this has a lot to do with the fact that it is the container Brian has used for years, has used in his demos and that was most widely available in the Prism Template Pack. The Unity team has made some major design changes in Unity 5.X. For Prism developers using Unity we have long since had a dependency on the Unity NuGet package. In it's current state, this actually broke Prism.Unity.Forms for netstandard1.0. 

The Unity team has redefined the Unity NuGet package to be an all inclusive package that presents several problems. For Xamarin Forms developers, it introduces references to 6 more assemblies than what you actually need or would use. For WPF developers it creates a secondary, and hidden reference to CommonServiceLocator, as well as the inclusion of 5 more assemblies than what you need or Prism uses. To continue depending on this NuGet package represents an additional issue that it could continue to break Prism developers. To resolve this, Prism 7.1 has changed it's target from Unity to Unity.Container. This change will be unnoticeable to anyone who uses the new PackageReference to include NuGet's in their projects, particularly when you have your dependency on Prism.Unity or Prism.Unity.Forms and not Unity itself. For all other Unity developers, you should uninstall Unity from your projects before upgrading to Prism 7.1.

Prism for Xamarin Forms Preview 3

So much goes into developing a Xamarin Forms application, and Prism for Xamarin Forms is continuing to make your mobile development a little easier. Today we released Preview 3 for Prism 7, and a lot has happened since I published the Sneak Peak and the changes to Autofac.

 

Navigation

One of the big things developers love about Prism is Deep Linking like "NavigationPage/ViewA/ViewB/ViewC". Unfortunately this also exposes a bug in Xamarin Forms which the Xamarin team hasn't fixed. The result has been that the Title displayed in the NavigationPage is for ViewA rather than ViewC. Prism 7 has finally fixed this issue so that deep linking can still occur properly.

A long awaited feature is Relative Navigation. We see this all the time in web development, and beginning with preview 3 you can now simplify our Navigation like "../SomePage". This will both pop the current page and add SomePage to the Navigation Stack. Keep in mind that this feature will only work within the context of a NavigationPage. 

Another long await feature has been the ability to simply go back to the root. Prism's Navigation Service now includes a GoBackToRootAsync extension that will support this exact use case. 

TabbedPages

Prism 7 has a lot of fixes to make working with TabbedPages a joy. In past versions of Prism we've had to both explicitly set the ViewModelLocator.AutowireViewModel property on any pages that will be children of a TabbedPage, and we've had to create a TabbedPage that explicitly sets the tabs.

<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local="clr-namespace:AwesomeApp.Views;assembly=AwesomeApp"
            x:Class="AwesomeApp.Views.MyTabbedPage">

    <local:ViewA />
    <local:ViewB />
    <local:ViewC />

</TabbedPage>

Beginning with Prism 7 you can now simply register the Xamarin Forms TabbedPage for Navigation and simply navigate like "TabbedPage?createTab=ViewA&createTab=ViewB&createTab=ViewC". But it doesn't stop there. There are times that we want to use a NavigationPage for a particular tab. We can now easily do this by adding the pipe character and navigating like: "TabbedPage?createTab=ViewA&createTab=NavigationPage|ViewB&createTab=ViewC". Best of all is that the NavigationService now better handles the children so that whether you have a traditional TabbedPage like above or one generated from the querytstring your pages will be automatically get the ViewModelLocator.AutowireViewModel set, and any Prism Behaviors will also automatically be set.

There has also been a major breaking change for selecting the active tab. In previous versions of Prism for Xamarin Forms you could set the active tab by adding the tab to select as the next Uri segment "MyTabbedPage/ViewB". This has been changed in preference of a querystring parameter like "TabbedPage?selectedTab=ViewB". Note that for those who are concerned about magic strings, we've got you covered as this is all based on the constants in KnownNavigationParameters. Putting this all together you can now navigate like:

_navigationService.NavigateAsync($"TabbedPage?{KnownNavigationParameters.CreateTab}=ViewA&{KnownNavigationParameters.CreateTab}=ViewB&{KnownNavigationParameters.CreateTab}=ViewC&{KnownNavigationParameters.SelectedTab}=ViewC");

Lifecycle

IActiveAware has been around Prism for some time but has only had limited support to handle when a page becomes the current page inside of a TabbedPage or CarouselPage. A new interface has been added to Prism.Forms called IPageLifecycleAware. This is handled through a Behavior added to every page by the NavigationService which will allow you to respond to the Appearing and Disappearing events.

Sticking with being Lifecycle aware, preview 3 has introduced a breaking change from earlier previews with IApplicationLifecycle to IApplicationLifecycleAware. While there hasn't been any actual changes to the way it works, it does better fit the naming conventions in Prism.

Modularity

Modularity has long been a core concept in Prism. Modularity has gotten a whole lot nicer in Prism 7 with a few fixes. To start with IModuleCatalog was fixed to properly return IModuleCatalog rather than ModuleCatalog when adding a Module. One of the problems with adding Modules in previous versions has been the verbosity that was required:

ModuleCatalog.AddModule(new ModuleInfo(nameof(SomeModule), typeof(SomeModule), InitializationMode.WhenAvailable));

This can now be simplified like:

// Basic Registration
ModuleCatalog.AddModule<SomeModule>();

There are of course some overloads to specify either the name or Initialization Mode. We have also added extensions to better determine whether a Module has been added to the ModuleCatalog and what the ModuleState is.

 

Xamarin Forms UI Development Made Easy with LiveXAML

I'm all about working with XAML in my Xamarin Forms apps. Developers coming from a WPF background have been used to some great tooling for visually styling their XAML for years. Xamarin Forms of course isn't so cut and dry for the obvious reason that we're dealing with an Abstraction of the UI. Chances are you've probably heard about Xamarin's Live Player. To be honest I think it's a cute idea, but really lacks what you need to be most productive. 

Naturally one of the biggest pains when working with XAML is getting the Styling just right. We do have more tools now at our disposal like the XAML Previewer in Visual Studio and Visual Studio Mac, but it lacks the touch and feel component of styling. This is where LiveXAML is making a huge difference in developing Xamarin Forms applications. LiveXAML not to be confused with Xamarin's Live Player, allows you to get the updates directly in your actual app. LiveXAML is truly one of the most amazing products I've ever worked with for XAML. 

It really is as simple as installing a single NuGet package and running the application in your Simulator or on your Device. Now you can actually see what your changes are doing, without rebuilding, in an app that is fully functional. There are no short cuts, no limitations like we see with the Live Player or the Previewer.

There are a number of challenges that are hard to handle without a data context behind them. One of them is handling a ListView with a DataTemplateSelector. It's certainly one thing to refine a single ViewCell, but when you have multiple cells that each need to be styled there is no substitute for having real working data which can only happen with your app actually running. This is one the many scenarios where using LiveXAML can really shine as you quickly update the styling and see the changes in your app. 

If you haven't had a chance to check it out head over to http://livexaml.com

Prism Template Pack in Visual Studio for Mac

Prism users have long enjoyed some great Template packs available for Visual Studio and Xamarin Studio. Visual Studio for Mac though has been a real challenge due to problems with the Mono Addins site not building the Prism Addin. It's been a very common request among our Mac users to get this support back.

Since we have been unable to rely on the Mono Addins site, we have decided to simply host our own feed for Prism Users. This new feed will allow you to add and update the Prism Template Pack in Visual Studio for Mac.

So how do you get the Template Pack? Well for starters you will need to add the Prism feed to your Extensions Repositories. Once you have it added, simply refresh the Gallery. You can either use the search bar or expand IDE extensions to find the Prism Template Pack.

Keep in mind that the new Prism Template Pack for Visual Studio for Mac now includes a DryIoc Project template in addition to the Unity Template. Both project templates will create project with the latest stable versions of Prism and Xamarin Forms.

Prism Quickstart Templates

Quickstart Templates for Prism Forms

So you had this great idea for an app... maybe you spent weeks planning with your team or with your client. The day finally comes to create the project. Suddenly you realize that we have this new .NET Standard thing and you want to take advantage of that too. You remember you need icons, you want a Splash Screen... all of the things that go into making an App. For anyone who has done this, you know there's a lot of heavy lifting to be done. In all honesty you could easily spend several days just getting a new project from File -> New to something that you're ready to start working on.

It was for this and so many other reasons that I realized we need better templates, and we need something that can help us whether we're on a Mac or on PC.

There are some very basic things left out of the base Xamarin & Prism Templates. For some developers these just require time that could be better spent on something else, and for other developers it leads them down a path of poor design.

Features

Why should you use these templates? Well here are a couple bullet points:

  • Gets you off the ground following Best Practices
  • *Starts you off using Prism for Xamarin Forms with either DryIoc or Unity for Dependency Injection
  • Already has all of your App Icons added so all you need to do is drop in the replacement files from File Explorer or Finder. There is also a link in there so you can see how to get all of your icons generated for you correctly in all of the sizes with all of the correct naming.
  • Starts you off with some base colors to use for your project with information of how to develop a Material Design pallet for your application.
  • By default it already has everything you need for Localizing strings in XAML
  • It's cross platform, using dotnet new you get the same experience from the command line whether on Mac or PC.
  • Item templates to generate Views and ViewModels with support for the common Xamarin Forms pages as well as PopupPages
  • Makes it easier to inject variables at Build to protect sensitive project secrets.
  • Quickstart with a fully working Todo app working with in memory data, Realm, or Azure Mobile Client
  • Included config for MFractor

*NOTE: Autofac & Ninject will be reintroduced once Prism 7 has a public preview.

Best Practices

App development can be simultaneously fun and frustrating. So many developers love Xamarin Forms because it really narrows down the number of API's you need to work with. What it doesn't do is eliminate your need to understand the platform your application will run on. These templates will not eliminate that need either, however they do set you down the right path, with some basic things like a splash screen so your user will at least see something while your app loads. Also included by default is the MVVM Helpers library from James Montemagno so that you can use his ObservableRangeCollection<T> to reduce the notifications sent to the UI when updating or replacing multiple items in your collection. If you don't use it MVVM Helpers you still get a ViewModelBase that will incorporate these properties as well as well as IDeviceService and virtual implementations of INavigationAware, IActiveAware, and IApplicationLifecycle.

Prism

Continuing really with Best Practices, these templates use Prism for Xamarin Forms. Currently the templates support DryIoc and Unity for Dependency Injection. Autofac and Ninject will be added back in once there is a publicly available release of Prism 7.

TabbedPages

Working with TabbedPages has traditionally been one of the more challenging areas of working with Prism. With the QuickStart template this challenge disappears. The template includes two base implementations for a TabbedPage, the PrismTabbedPage and the DynamicTabbedPage. If your TabbedPage inherits from PrismTabbedPage, it will automatically pick up and pass on the NavigationParameters to the Child Pages allowing you to properly initialize them. If you use the DynamicTabbedPage you only need to reference it in your Navigation URI and pass in variables like:

NavigationService.NavigateAsync("TabbedPage?tab=ViewA&tab=ViewB&tab=ViewC");

But it actually gets a little better than that because not only does it pick up tabs but you can also do some deep linking like:

NavigationService.NavigateAsync("TabbedPage?tab=NavigationPage/ViewA/ViewD&tab=NavigationPage/ViewB&tab=ViewC");

This means you can actually support scenarios where your actual tabs contain their own NavigationStack independent of the rest of the application.

App Icons

Applications need a lot of icons and really the templates out there don't do a very good job with App Icons. Most templates out there just leave your deployed app with a broken icon image and require some time getting the icons setup. These templates start you off with icons for your Android and iOS projects. But more than that is the GettingStarted document included in the template gives you the information you need to be able to quickly and efficiently generate a full icon set that you can drop in to replace the default icons with your own icons. Following along with Best Practices, you'll find that the iOS project is using the newer appiconset approach with the app icons as ImageAssets rather than having them in the Resources folder as BundleResources. Similarly on Android you'll find the app icon's are all in the mipmap folders rather than drawable.

Material Design

While my purpose is not to teach Material Design, there are some basics that we can easily include in the template to get you started down the right path. That includes a basic color pallet with information of how to choose new colors. There is also already a Style defined for you to customize the look and feel of a NavigationPage using those colors.

Localization

One of the things I hear over and over, developers in the United States forget some people don't speak English. For most US based dev's Localization is a complete and total afterthought. Interestingly nobody seems to have thought previously that maybe we should provide a template that assumes you want your application easily consumable by people in another country who speak another language. The quickstart template comes complete with all of the helper classes you need to get Localization working in the application and gets the Localization implemented with the DI container using Prism's IPlatformInitializer. There is also a XAML extension provided so all you need to do is include the namespace in your XAML file and use it as needed. The app of course also includes a single Resx file to get you started. You simply need to add the string resources you want to use in your application.

Cross Platform

It might seem weird when we're talking about Xamarin, but seriously it gets frustrating when we're working with a Cross Platform technology and then the developer experience is completely and totally different depending on which platform you are on. One of the most common issues we can see from a templating standpoint is that if I click File -> New, it shouldn't matter whether I'm on Mac or PC, I should be able to decide if I want my project to include iOS, Android, UWP. That's not to say I don't understand that some time may be needed before you can build a UWP app on Mac, but you should at least be able to have the platform as an option so you can work on the codebase from either platform.

Item Templates

Also included are some Item Templates custom built for the included project templates. There are two basic types of Item Templates, Pages and Services. Note that there is currently no way for the dotnet templating engine to pick up what your base namespace is, so you do have to specify this from the command line.

Pages

By default when you call dotnet new prismitem you will get a page. It's assumed that you're using the ViewModelBase from the included Project templates. You can add flags to specify whether you want to implement INavigatingAware, INavigatedAware, INavigationAware, IActiveAware, or IDestructible. By default it implements INavigationAware. There is also a flag to indicate if the page is a Tabbed Child which will automatically implement IActiveAware and INavigatingAware. Currently supported page types include ContentPage, MasterDetailPage, TabbedPage (which inherits from the Quickstart PrismTabbedPage), and PopupPages.

Samples

dotnet new prismitem -namespace MyAwesomeApp -n LoginPage
dotnet new prismitem -namespace MyAwesomeApp -page PopupPage -n SomePage
dotnet new prismitem -namespace MyAwesomeApp -n CustomerDetailPage -child

Services

Chances are your app is probably using some sort of service and if you like testability like I do, then you'll really appreciate that you can create a service with Mock class that will automatically be picked up by the Quickstart template simply by building with the Mock configuration. 

Samples

dotnet new prismitem -item Service -namespace MyAwesomeApp -n LoginService
dotnet new prismitem -item Service -namespace MyAwesomeApp -n LoginService -mocks false

Secrets

All apps have secrets and other variables that we just don't want checked into source control. To better assist with this, the template includes some helpers that will regenerate the Secrets.cs with sensitive variables you want in your codebase. Both the Secrets.cs and secrets.json files have also been added to the included .gitignore, so you can finally develop apps without having to tackle the issue of keeping app secrets out of SCM.

secrets.json

{
  "AuthClientId": "{Your App Client Id}",
  "AppServiceEndpoint": "https://appservicename.azurewebsites.net/"
}

Secrets.cs

namespace YourProject.Helpers
{
    internal static class Secrets
    {
        internal const string AuthClientId = "{Your App Client Id}";

        internal const string AppServiceEndpoint = "https://appservicename.azurewebsites.net/";
    }
}

PropertyChanged.Fody

Part of the MVVM pattern is working with INotifyPropertyChanged. Unfortunately the code can get a bit tedious. 

public class ViewAViewModel : BindableBase
{
    private string _title;
    public string Title
    {
        get => _title;
        set => SetProperty(ref _title, value);
    }

    private MyModel _selectedItem;
    public MyModel SelectedItem
    {
        get => _selectedItem;
        set => SetProperty(ref _selectedItem, value, onChanged: OnSelectedItemChanged);
    }

    private void OnSelectedItemChanged()
    {
        // Do Stuff
    }
}

With PropertyChanged.Fody already included our ViewModels and other Observable objects simply become:

public class ViewAViewModel : BindableBase
{
    public string Title { get; set; }

    public MyModel SelectedItem { get; set; }

    private void OnSelectedItemChanged()
    {
        // Do Stuff
    }
}

Mobile Center

Also bundled into this template is support for the Azure Mobile Center. While this is an opt in feature you can pass in your App Secret for iOS and/or Android from the command line with everything already wired up to send your analytics and crash data to the Azure Mobile Center. This includes an implementation of ILoggerFacade that will create a Mobile Center Analytics Event.

Data Providers

Apps today are so often really connected apps. The Quickstart Template provides you a fully functional TodoApp with the option to use either the Azure Mobile Apps Client with AzureMobileClient.Helpers or to use Realm. Either data provider will start you out with the ability to quickly develop your app with full online/offline sync with the bare minimum of configuration. 

Azure Mobile Client

In addition to simply using the Azure Mobile Client you can additionally decide if you want to use anonymous authentication or if you will require some sort of authentication. If you choose an authentication provider, the Quickstart will provide you base classes for everything you need to get started. This includes scaffolding for custom authentication sources and a fully working implementation for Azure Active Directory B2C with support coming for AAD, Google, Facebook and Microsoft Accounts.

Plugins

Because the full working app uses a PopupPage for the TodoItem detail page, the Quickstart includes Prism.Plugin.Popups, and also optionally includes a Barcode Scanning Service utilizing ZXing.Net.Mobile and is fully registered and configured.

Getting Started

To get started with the templates it's recommended that you install version 2.0 pre3 of the dotnet cli as this contains several fixes in the templating engine. Once that is installed you can install the templates by using the following commands in your cli.

dotnet new -i "Prism.Forms.QuickstartTemplates::*"

You should see the prismitems and prismformsempty templates. The Quickstart template is grouped with the empty template, though you may not see it listed it is still there.

# See the Help and options for the Quickstart Template
dotnet new prismforms -h

#Create your first quickstart
mkdir Contoso.AwesomeApp
cd Contoso.AwesomeApp
dotnet new prismforms -id com.contoso.awesomeapp -fr netstandard1.6 -mc -ios-secret 
     "{your ios secret}" -android-secret "{your android secret}" -data AzureMobileClient 
     -auth AADB2C -client-id "{your AADB2C application id}"
#Be sure the B2CName in secrets.json matches your AAD B2C name

 

Azure Mobile Client Helpers

To be honest, I forget now exactly when I first heard about the Azure Mobile Client library. I do however remember an initial sense of excitement for being able to add Online/Offline syncing to my apps. That excitement gradually faded a little when I started to deep dive into the library and realized that every project I wanted to use the Azure Mobile Client, meant that there were a number of helpers I would need to recreate. If you're familiar with the Azure Mobile Client, the chances are you may have seen tutorial either by or inspired by Adrian Hall's guide. Even Xamarin's "Connect App" template uses this basic approach. Honestly I don't mind providing an implementation for an interface or two in my projects, but it gets a little old when I have to redevelop everything in my projects.

It was for this reason that I decided to wrap the abstractions and some basic implementations into a reusable library. The AzureMobileClient.Helpers library wraps what you need to quickly get off the ground running with the AzureMobileClient. But it's really about more than simply providing the base classes you need to be successful. It's also about helping you to develop the code that follows best practices, and helps keep your code testable. 

So what does getting started even look like? Well let's say we have the classic TodoItem.

public class TodoItem : EntityData
{
    public string Name { get; set; }
    public string Notes { get; set; }
    public bool Done { get; set; }
}

We don't need to define any of the fields specific to our Azure Mobile Services Entity as it's already defined in the EntityData base class. Since I'm all about Developer Experiences, and trying to make things to where we have to write as little code as possible to have a fantastic app, I'll use Mobile Center to quickly setup a Mobile Backend. 

Create an Easy Table

Navigate to the Tables tab and create your first table. Note that when you first go to the Tables tab you'll be asked to link the app to your Azure account. The Mobile Center will automatically go out and provision a new Mobile App Service and setup everything in a Resource Group for your app. You should be aware that you can go into the Azure Portal at any time to manage the resource. When Mobile Center sets everything up it will use a SQLite database which is great for testing, and not so great for Production. If you want to set this up to be more than a demo, before you create your first table go into the Azure Portal and configure either a SQL Server connection or Storage connection under Mobile -> Data Connections. For this example we're not going to set up any authentication, but you can do this easily from Mobile Center. The great thing about Easy Tables is that the data store allows for a dynamic schema so all we need to provide for this is a table name and click Create.

Set the table name

Really with very little effort and Zero code on your part, your mobile backend is ready. Notice I said it's 'Zero code on your part', and not 'Zero code'. Behind the scenes it is setting up a Node.js backend adding the files you need. You can go into the App Service Editor at any time and make manual changes if you need to. All you need to do now is setup your Xamarin application. Keeping things simple let's set up the application using Prism with a NetStandard1.4 Core library so that we can use the latest NetStandard release of the Azure Mobile Client and the Helpers library I mentioned before.

Now in order to keep things a little easier I want to keep a singular app context that I can use so I can easily scale from 1:N models without having to update the dependencies I'm injecting into my ViewModels. To do this I'm going to reference the Container specific implementation for the library so I can more easily set this up. For this we'll use the DryIocCloudAppContext and provide our Tables very much like we would using Entity Framework and the DbContext.

public class AwesomeAppContext : DryIocCloudAppContext
{
    public AwesomeAppContext(IContainer container)
        : base(container, AppSettings.DbName)
    {
    }

    // NOTE: This must be here for the AppContext to pick up your Model Type
    // and ensure that the table is created in the SQLite store
    ICloudSyncTable<TodoItem> TodoItems => SyncTable<TodoItem>();
}

Now, we just need to register our services:

protected override void RegisterTypes()
{
    Container.Register(typeof(ICloudSyncTable<>), typeof(AzureCloudSyncTable<>), reuse: Reuse.Singleton);
    Container.RegisterInstance<IMobileServiceClient>(new MobileServiceClient(AppSettings.BackendUri));
    Container.Register<AwesomeAppContext>(Reuse.Singleton);

    Container.RegisterTypeForNavigation<NavigationPage>();
    Container.RegisterTypeForNavigation<MainPage>();
    Container.RegisterTypeForNavigation<TodoItemDetailPage>();
}

With our services we're all set. We just need to add AwesomeAppContext to the constructor of our ViewModel and we can access our data. 

public class MainPageViewModel : BaseViewModel, INavigatedAware
{
    private AwesomeAppContext _context { get; }

    public MainPageViewModel(AwesomeAppContext context)
    {
        _context = context;
        TodoItems = new ObservableRangeCollection<TodoItem>();
    }

    public ObservableRangeCollection<TodoItem> TodoItems { get; }

    public async void OnNavigatedTo(NavigationParameters parameters)
    {
        await _context.TodoItems.SyncAsync();
        TodoItems.ReplaceRange(await _context.TodoItems.ReadAllItemsAsync());
    }
}

Finally we can go from idea to working app in under 10 minutes with full Online/Offline Sync. You can see the full working TodoDemo app on GitHub.

A Dot Net Developer on a Mac

Recently I had a chance to attend a meetup here in San Diego. To be honest, around other developers I sometimes feel like the odd man out. I mean here I am a C# Dot Net developer, and I'm showing up to code with a Mac. It really wasn't all that long ago that you might look at a "C# Developer" doing something like that, as if they were on crack. But the times they are changing. In fact, at that meetup the odd man out, was the dev with a Windows Laptop.

I often have conflicting feelings about my development. On the one hand, I absolutely LOVE Visual Studio. As far as I'm concerned it hands down beats every other IDE out there. As I mentioned though, when I'm on the go, more often than not I'm working off my Mac. So then how on earth does a Dot Net developer work on a Mac. Well truthfully if it wasn't for all of the hard work coming from Microsoft the past few years I'm not sure it would be anywhere near as pleasant as it is now.

I realize that there are still a lot of short comings with NetStandard, for one it is completely useless for Xamarin libraries that contain XAML files. That said the work that has been done around the NetStandard has been instrumental in making Dot Net even a citizen in non-Windows environments. Part of the problem with being a Dot Net developer outside of Windows is that the tooling was heavily integrated with Windows, so it wasn't as easy as install Mono... go...

I have been gleefully watching over the past couple of years as all of that has started to change. One of my recurring issues, and frankly one that may have caused me to pull out a lot of hair, was that Microsoft kept increasing the developer experience around PowerShell. Well that's cool, but everyone else in the world is using Bash and PowerShell wasn't available outside of Windows. So to me I kept asking how stupid can you be to increase the dependency on a Windows Environment? Well truth be told they were working on porting PowerShell and it is actually available for Mac and Linux now so any PowerShell commands I may have been running in the past on PC, are now available on Mac.

But it really doesn't end with PowerShell. For the past year I have been somewhat vocal about what they call "Visual Studio for Mac", or as I call it "Xamarin Studio with a Visual Studio logo". This week the team released Preview 6 for VS for Mac. For the first time Mac users like myself are getting a lot closer to some of the critical pieces that have been missing. Now you may have noticed that until now, I haven't mentioned Visual Studio Code. It's not a bad editor, in fact I use it when writing articles for this blog. It's a great environment as well for quickly working up an AspNetCore website and running it locally. But it's been a little frustrating as a Dot Net developer that there hasn't been any tooling (other than PowerShell) that would allow me to connect to Azure and deploy resources right from the IDE. Preview 6 really changes things though. First it brings tooling directly into the IDE to deploy an AspNetCore application straight to Azure whether to an existing resource or a new resource you want to create. The next piece of critical functionality of course... C# 7. It may have taken a month longer, but it's finally available on Mac, proof they really are using the same Rosyln as Visual Studio???

The Hamburger Menu with Prism Forms

How many times have you heard someone ask about a Hamburger menu in Xamarin Forms? It's a topic that comes up fairly frequently and it seems there are two distinct camps. Those who will tell you it's drop dead simple, and those who are stuck trying to figure out why if it's so simple, they can't figure it out. Honestly there are already a ton of YouTube videos and Blog Posts on the topic, so much so that I didn't want to touch the subject. However there is still a ton of confusion about the "Secret Sauce".

 

I would like to think the reality is somewhere in between. So often I find the major reason for these types of disagreement, has more to do with mis-managed expectations. For those stuck trying to figure out how to implement the Hamburger Menu, I think there are two key "gotcha's".

 

I've seen a number of blogs on the topic, but it seems like they're quick to say just use a MasterDetailPage. Ok you're done, you don't have to go home, but don't stay here. But that isn't the whole story. I've seen some blogs that do make more of a point to tell you that your Detail Page must be wrapped in a NavigationPage. But again, that just isn't the whole story.

 

So how on earth do you get that hamburger menu? Well for starters, you don't go to McDonalds (or for those in my neck of the woods, In N Out). When people ask about the "hamburger menu" they aren't asking how do you implement a slide out menu in your app. But that's what we keep telling people. In order to get the "hamburger menu", you need images. See people kept telling you it was easy. The secret sauce is to add an Icon to the Master page of the MasterDetailPage. Xamarin actually does this in their sample, but seems to gloss over the importance.

 

Since I'm a Prism guy though, let me go over the creation of a Prism App with a Hamburger Menu. I will assume you have the basic Prism App setup.

 

App.xaml.cs
public partial class App : PrismApplication
{
    public App( IPlatformInitializer initializer = null ) 
        : base( initializer )
    {

    }

    protected override void OnInitialized()
    {
        InitializeComponent():
        NavigationService.NavigateAsync("MainPage/NavigationPage/ViewA");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation<NavigationPage>();
        Container.RegisterTypeForNavigation<MainPage>();
        Container.RegisterTypeForNavigation<ViewA>();
        // So on and so forth...
    }
}
You'll notice here that there are three View's I'm registering. The first is just simply the Xamarin Forms NavigationPage. There's no magic here. The next is my MainPage, which I will go more into detail. And lastly I register ViewA which is just some View that I will have as a Detail Page.

MainPage.xaml
<?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="HamburgerMenu.Views.MainPage">
    <MasterDetailPage.Master>
        <!-- Hamburger Menu Secret Sauce... Add an Icon!!!! Make sure it's in your resources for your Platform Project -->
        <NavigationPage Title="Required Foo" Icon="hamburger.png">
            <x:Arguments>
                <ContentPage Title="Menu">
                    <StackLayout Padding="40">
                        <Label Text="{Binding UserName,StringFormat='Hello, {0}'}" />
                        <Button Text="View A" Command="{Binding NavigateCommand}" CommandParameter="Navigation/ViewA?message=Did%20you%20see%20the%20secret%20sauce%3F" />
                        <Button Text="View B" Command="{Binding NavigateCommand}" CommandParameter="Navigation/ViewB?message=Told%20you%20Prism%20Rocks%21%21%21" />
                        <Button Text="View C" Command="{Binding NavigateCommand}" CommandParameter="Navigation/ViewC?message=Does%20the%20hamburger%20make%20you%20hungry%3F%3F%3F" />
                    </StackLayout>
                </ContentPage>
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Master>
</MasterDetailPage>
All code means stuff, and there's a bit going on. Whether I'm coding or not, I'm generally a very light hearted kind of guy that likes to joke around. So you'll notice here the Navigation Page that I have as the MasterDetailPage.Master, has a title of "Required Foo". That is because Title is a required field for the Master, while the Icon is optional. The icon when supplied hides the title. I mentioned that a NavigationPage is a requirement for the "Hamburger Menu", but that is for the Detail, NOT the Master. I am choosing to use the NavigationPage in my Master in this sample, not because I expect actual navigation within the 'Menu', but rather because it quickly gives me the ability to add a nice Header and Toolbar Menu Items.

Now before you go all crazy trying to figure it out. You can download this zip for the Hamburger Icon assets for Android and iOS.