Xamarin Dev-Days Vancouver Announced

Whoot! Xamarin Dev Days is coming to Vancouver! If you are new to Xamarin and mobile development, this is a great way to jump in and get started and see what all the fuss is about.

Clear your calendar for Saturday September 23 and sign up at the registration page. You can also join the Vancouver Windows Platform Dev Group to learn even more (disclaimer: I am a member and have presented on Xamarin a couple of times).

If you aren’t in Vancouver, there are a number of locations being hosted around the world. You can check them out here.

Xamarin Forms, Autodesk Forge and Android DeepLinking

Finally, after covering UWP and iOS we are going to take a quick look at Android. Android seemed to be the easiest to get setup for me. All I had to do was to make the declaration of the deep linking to an IntentFilter attribute on the MainActivity class. When you add the IntentFilter, Xamarin will automatically update the manifest file for you.

In the code below, the most important items are the DataScheme and DataHost attributes. They are the ones that tell Android that the declared protocol is handled by the application.


[Activity(Label = "DeepLink",
    Icon = "@drawable/icon",
    Theme = "@style/MainTheme",
    MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize |
                            ConfigChanges.Orientation)]
[IntentFilter(new[]
    {
        Android.Content.Intent.ActionView },
        AutoVerify = true,
        Categories = new[]
        {
            Android.Content.Intent.CategoryDefault,
            Android.Content.Intent.CategoryBrowsable,
        },
    DataScheme = "bbsw-fm",
    DataHost = "brainbucketsoftware.com")]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        /// ... rest of the OnCreate
    }
}

Unlike iOS and UWP, Xamarin Forms routes the event back to the portable Application class and the OnAppLinkRequestReceived function. From there you can process the access token:

protected override async void OnAppLinkRequestReceived(Uri uri)
{
    base.OnAppLinkRequestReceived(uri);
    bool retrievedToken = await AuthWorkflowService.GetAccessTokenAsync(uri.ToString());
    if (retrievedToken)
        await NavigationService.NavigateAsync(Pages.Test);
}

In the next post, we will look at processing the response to get the access token.

Xamarin Forms UWP Deep-Linking

Introduction

In our last post, we looked at what we needed to do to setup our shared/portable project to authenticate with Autodesk Forge. Almost all of the code the important code is in the shared area, but we do have to do somethings within each of the platform projects. Lets check out UWP.

Protocol Declaration

The first thing that I do is go into the Package.appxmanifest in the UWP project. Once you are in it, click on the “Declarations” tab. On this tab, you can declare lots of different things for your app: able to pick files, camera settings, background tasks among others. The one we are interested in is protocol.

Select protocol and add it to the list of the supported declarations. Give the protocol a name check “ExecutableOrStartPageIsRequired”. For the name, make sure that you give it something unique. Perhaps an abbreviation of your company followed by some kind of app designation.

packageappxmanifest

Override UWP Application.OnActivated

In the UWP platform project, you need to override the Application.OnActivated function to handle the deep-link. Normally Xamarin Forms will just route the URI request to OnAppLinkRequestReceived, but it doesn’t seem to be working for UWP (or iOS). So what we will do, is just call in to a new entry point which then delegates to the protected function.


/// UWP application object
sealed partial class App : Application
{
    // ... other stuff here

    protected override async void OnActivated(IActivatedEventArgs args)
    {
        base.OnActivated(args);

        if (args.Kind == ActivationKind.Protocol)
        {
            var protocolArgs = args as ProtocolActivatedEventArgs;
            DeepLink.App thisApp =
                (DeepLink.App) Prism.Unity.PrismApplication.Current;
            thisApp.UwpIOSOnAppLinkRequestReceived(protocolArgs.Uri);
        }
    }
}

Then we can go back to the application object in our portable library and fix up the OnAppLinkRequestReceived function and the manual entry point we show above that is used for UWP and iOS.


public partial class App : PrismApplication
{
    /// the rest of the class is up here ...

    protected override async void OnAppLinkRequestReceived(Uri uri)
    {
        base.OnAppLinkRequestReceived(uri);
        bool retrievedToken = await GetAccessTokenAsync(uri.ToString());
        if (retrievedToken)
            await NavigationService.NavigateAsync(Pages.Test);
    }

    public void UwpIOSOnAppLinkRequestReceived(Uri uri)
    {
        OnAppLinkRequestReceived(uri);
    }

}

All that is happening above is that when the app is activated because of the protocol that it has registered, it will look at the URL and extract the response code that was returned by Forge. It will then use that response code in a REST API call to get the authorization token and refresh token. If that is successful, we perform a navigation to the next page in our app. Obviously the code isn’t complete as it doesn’t handle any kinds of errors. For the details on how to get the authorization and refresh tokens see the previous post.

And that is it for UWP, just a little bit of code and we are back in our shared code base. Up next will be iOS.

Google Play Services on Marshmallow

When it comes to working on Android apps, I really feel like I am starting completely from scratch … or maybe even a bit less than that. And I end up running across weird problems that end up causing me all kinds of issues. This post will talk about one of those problems and how I combined the posts of two others (who I am sure know much more than I about Android) to address my issue.

I am working on an app that uses maps. I am planning on targeting Marshmallow at a minimum. I am also using the Visual Studio Android Emulator. If you don’t already know, the Visual Studio emulator doesn’t come with the Google Play Services, which are required if you want to use maps in your app.

In a previous app, I was able to spin up an emulator, go to http://teamandroid.com/gapps, download the appropriate zip file and drag and drop to the emulator to install. This worked great for me on both KitKat and Lollipop emulators. On Marshmallow … not so much.

I started surfing … I mean researching. And in my research I came across an article from Cheesebaron which you can see here. In a nutshell, he recommends (with references) two different gapps packages to download. The only problem was that when I tried his method of downloading and drag and drop installing, my emulator just started an endless loop of optimizing packages and rebooting.

I then found another article from Rob Prouse about how to do a low level install of gapps packages from the SD card. When I tried his method, which used the gapps package from teamandroid.com, that failed as well. But at least it seemed to install without any obvious errors.

I finally deleted my emulator, started up a new one and combined the two articles. I downloaded the two packages recommended by Cheesebaron. I installed the first one in the manner recommended by Rob Prouse and after installation, was able to setup my Google account on the emulator. I then installed the second package from Cheesebaron using the same SD card installation method. After rebooting the emulator, I was able to deploy my app and run it. I am not sure if this is normal behavior, but I had to go into the app settings on the emulator and enable location for it. In the past, I seem to remember it asking me on first install, but I could be mistaken.

My new Marshmallow emulator setup is as follows:

  • Download gapps packages from Cheesebaron’s article:
  • Install the first package via the emulator SD card as per Rob Prouse
  • Create your google account in the settings/accounts
  • Install the second package via the emulator SD card as per Rob Prouse.

Hopefully this helps someone else and if not, writing it down will help me.

 

Xamarin Dev Days Lab – Prism Step 4

Well, hello from Las Vegas! I am down in LV for the Autodesk Developer Network Dev Days and the Autodesk University. It’s a pretty fun time, especially if you are involved in engineering or CAD of any kind. If you are like me, also a dev person, there is lots of cloud stuff to add in there. And now even virtual reality and augmented reality to geek out!

In any event, travel makes for weird schedules and time awake. So here I am working on navigation in Xamarin Forms projects. But first a little recap: in our last post we really dug into dependency injection and showed the power of it. We saw some concrete examples of how it can make our app better architected, and how that makes it more maintainable. Next we will take that architecture to the next level and add in navigation. You probably remember from the start of the app how we had to register pages for navigation: let’s review that.

In a normal Xamarin app, the navigation system is accessed via a singleton object. To navigate to another page , you have to provide the actual page type of the destination page to the navigation service. Right away, you can see that this could be a headache in the future: if you change the page type, you need to change it everywhere in your app that the page is referenced. Yuck. And what if you have needs that are a bit more dynamic? For example, you could have a free version of an app and a paid version. In that case your dependencies just increased by a factor of …? Well, it depends on the app, but every time you have to make that decision in your app is another level of complexity. Instead, wouldn’t it be cool if you could just determine if the app was paid or not and navigate to the appropriate page based on that status?

Prism provides a better model for navigation. Not only does Prism remove the dependency on types, it also moves the navigation brains up to the view model (where the business logic is) and away from the presentation level (where the Xamarin navigation system resides). And this all begins in the RegisterTypes method of the App object. So let’s start with what we have there.


/// first we have the register types
protected override void RegisterTypes()
{
    // non nav registration here
    Container.RegisterTypeForNavigation
        <View.SpeakersPage, ViewModel.SpeakersViewModel>();
}

/// and our initial navigation
protected override void OnInitialize()
{
    NavigationService.NavigateAsync("SpeakersPage");
}

The above registers the SpeakersPagae for navigation and associates it with the SpeakersViewModel. There is also an optional parameter in the call to associate the registration with a key. Since we didn’t provide a key, Prism made one for us based on the name of the page. When you call NavigateAsync, you provide the key and the Prism navigation system looks up what is associated with the key and instantiates the appropriate page and view model.
We can improve this by specifying our own key. If we do that, in every place we navigate to the page, simply changing the initial registration will allow us to put in a different page. We won’t have to go to every place and change the call. I like to create a static class with the page keys so that I can reduce my use of magic strings.

public static class PageKeys
{
    public const string Speakers = "speakers";
    public const string Details = "details";
}

And now we can update the two functions above:


protected override void RegisterTypes()
{
    // non nav stuff here

    Container.RegisterTypeForNavigation
        <View.SpeakersPage, ViewModel.SpeakersViewModel>
        (PageKeys.Speakers);
}

protected override void OnInitialize()
{
    NavigationService.NavigateAsync(PageKeys.Speakers);
}

 
So that is looking pretty cool. Let’s pretend there is a paid and free version of the app and adjust our registration:

protected override void RegisterTypes()
{
   if (IsPaidApp)
   {
        Container.RegisterTypeForNavigation
          <View.SpeakersExPage, ViewModel.SpeakersExViewModel>
          (PageKeys.Speakers);
   }
   else
   {
       Container.RegisterTypeForNavigation
         <View.SpeakersPage, ViewModel.SpeakersViewModel>
         (PageKeys.Speakers);
   }
}

Awesome! Just by using the key instead of the page type name, we made our app even more flexible and easier to maintain. None of our in app navigation will change, we always just call:


NavigationService.NavigateAsync(PageKeys.Speakers);

What else is important in this? Well I mentioned this before, but the navigation system is rooted into the presentation layer of the code. But navigation is really about business logic. The Prism navigation service abstracts out the presentation and the service is passed around as an interface. For unit testing of your view model, you can mock the interface and your view model won’t know or care.

You probably already know how the view model gets the navigation service (dependency injection, constructor parameter), but just in case it is late or you don’t remember every single detail of the previous posts, we just put the dependency into the constructor and the dependency injection container injects it for us. You can see this in the code. If you are looking at the code and saying: wait, INavigationService is not registered anywhere in your code, you are right. The App base class does it for us because they assumed that you were going to want that service. Dig into the Prism code if you want to find out more.

The last thing I want to bring up with respect to Prism navigation is how to pass data during navigation. When you use the NavigationService.NavigateAsync method, the second parameter is a NavigationParameters object, and you can pass pretty much anything in in. Let’s dive in.

In this example, I want to know when the SpeakersPage is navigated to the first time. So in the app object, I am going to add that parameter to the initial navigation in the OnInitialize method.


protected override void OnInitialize()
{
    var nps = new NavigationParameters();
    nps.Add("first", true);
    NavigationService.NavigateAsync(PageKeys.Speakers, nps);
}

How do we consume this data? And where do we consume it? This data is really business logic data so we want to consume it in the view model. To get the data up to the view model we have to have our view model implement the INavigationAware interface. This interface has two methods: OnNavigatedFrom and OnNavigatedTo. I normally like to implement this in the BaseViewModel class so that all the view models have it already and I can also setup some generic functionality if I want.

public class BaseViewModel : BindableBase, INavigationAware
{
    /// ... other base stuff goes here

    public virtual void OnNavigatedFrom(
        NavigationParameters nps)
    {
    }

    public virtual void OnNavigatedTo(
        NavigationParameters nps)
    {
    }
}

So now in my SpeakersViewModel, I will override the OnNavigatedTo method to implement looking for first run:

public class SpeakersViewModel : BaseViewModel
{
    /// ... existing stuff here

    public override void OnNavigatedTo(
        NavigationParameters nps)
    {
        base.OnNavigatedTo(nps);

        if (nps == null || !nps.ContainsKey("first"))
            return;

        bool firstLoad = (bool) nps["first"];
        if (firstLoad)
        {
            /// do first functionality here
        }
        else
        {
            /// do something else
        }
    }
}

But how does that actually work? What happens is that the navigation service is aware of the page creation. And as part of the page creation, we know that the view model will be automatically injected. The navigation service will look at the view model object that was injected and see if it implements the INavigationAware interface. If it does, it will call the OnNavigatedTo method. More awesomeness!

Well, that is it for navigation. You can see full-on code at the usual place in my GitHub repo under Step 04.
Enjoy!