App icons missing after upgrading to iOS 11/Xamarin

I have an Xamarin iOS project and developing in Visual Studio 2017 and have app icons in an asset. Since I've upgraded to XCode 9/iOS11 the app icons aren't included anymore and Application Uploader would throw a ton of errors at me about the missing icons. Before XCode 9 it worked though.

Xamarin describes upgrading issues to iOS 11 here and there but nothing much for Visual Studio 2017 - a key is missing in Info.plist they say. But what key?

It turns out the solution is a really simple one. Open iOS project in Visual Studio 2017, open Info.plist in editor, go to Visual Assets and make sure that App Icons source is pointing towards correct asset (with app icons).

It will generate this Info.plist key and value (value might differ, based on where your app icons are):

<key>XSAppIconAssets</key>
<string>Resources/Default.xcassets/AppIcons.appiconset</string>

This value can be added manually, as well, if you know what to add.

Fixing connection problems between Visual Studio and Mac when building iOS applications

I’ve been digging a bit into problems of connection between Visual Studio (Xamarin.iOS) and a Mac and wanted to share a few tips here.

It all started with my Visual Studio being unable to build an iOS application due to the connection issues. Basically I could connect through Xamarin Mac Agent (XMA) through Visual Studio but then the build would fail saying that it couldn’t log to target Mac given my username.

For starters one might read Connecting to the Mac and Connection Troubleshooting topics. But my problem wasn’t listed there or anywhere else. So I had to figure it out on my own.

First hint was that XMA required me to type in the username/password for connecting to the Mac. It connected and I could show the iOS simulator but I couldn’t build. When configured properly it shouldn’t ask for credentials, perhaps only for the first time. For me it was asking for credentials each time I started Visual Studio.

After reading, digging and googling I understood that XMA is using SSH tunnel to connect to the Mac. First thing was inspecting the log files (VS Help/Xamarin/Open Logs…). I didn’t find much there (other than failed connection to the host lines), or so I thought. Next thing was – checking the SSH connectivity (command prompt, ssh username@host). Using my default private key I had no problems connecting to the Mac but Visual Studio kept failing the build process. Next thing to try was Xamarin’s own SSH diagnostics app (provided as C# sources – kudos) which would throw Permission Denied (publickey) upon Connecting to host. Since the public key is on host, the problem obviously has to do with the host – but why since it was working from command prompt. Using this app I also found out what private key is XMA using. And it isn’t my default one, which I tested the connection with.

The thing is that XMA is using its own private key which you can find it at %LocalAppData%Xamarin/MonoTouch/id_rsa. So next thing I tried was connecting through command prompt/ssh using –i PATH argument (forces what key is used), i.e. (replace %LocalAppData% with value) ssh –i %LocalAppData%Xamarin/MonoTouch/id_rsa user@host. And yes, it didn’t work. So definitely a key issue.

The solution

Time for looking at Mac, specially in file /Users/username/.ssh/authorized_keys  where public keys for my profile are stored. And as anybody would guess, it was missing Xamarin’s public key. To get one from the private key I used Puttygen (a part of PuTTY): imported XMA’s private key and copy & pasted the public key portion right into the new line of authorized_keys file on Mac (I had my default public key already in there). This time the ssh command line tool connected without problems. And so did XMA from Visual Studio. Happy me.

The cause

This let me thinking, why does it usually works without intervention. After further examination of log files, it was clear. XMA first tries using its private key, if it doesn’t succeed it tries to cat the public key portion to authorized_keys file on Mac (probably using the credentials you have to enter ). But what happens if the authorized_keys file is read-only? Ha, nothing, a log entry and that’s it. This was my case, I had authorized_keys file as read only. I wouldn’t mind a clear warning: “hey dude, XMA was unable to modify your authorized_keys file, please enter this public_key manually”. It’d certainly spared me some time.

The security considerations

Let me repeat what happens when first time connecting to Mac. XMA would create a private key and put its public part into authorized_keys on Mac. Were you aware of that? No? Neither was I. To make things complicated, the private key in question isn’t password protected. Theoretically an app that user runs (no admin privileges required) could use the key (or worse, copy it through the Internet) to connect to your Mac and gain your credentials on the Mac, which are most probably administration ones. It still would have to type in password for su access, but nevertheless, this isn’t something that should be taken easily IMO.

I certainly wish that the connection mechanism was better documented and people were aware what’s going on. If nothing else, we could pinpoint the problems more easily. Also, an option to use password protected private key would be much more secure.

Different XAML layouts for different device orientations in Xamarin.Forms

In case you’ve been wondering how to achieve different XAML layouts for different device orientation with Xamarin.Forms (just Forms from now), here is a solution. The thing is that there is currently no support for this. There is support for different layout when it comes Phone vs Tablet (OnIdiom<T>) or when it comes to different OS (OnPlatform<T>) but the thing is that these guys are static. They do their work once and that’s it. They won’t react to changes and it makes sense, since underlying OS or device type don’t change during runtime.

So something different is need. But before I even start with the XAML there is an important part that has to be done – getting the current orientation, or better, rotation at the Portable Class Library level. It is a twofold solution.

Here is code that exists in PCL project and isn’t OS specific.

public enum Rotation
{
    Rotation0,
    Rotation90,
    Rotation180,
    Rotation270
}
public static class Orientation
{
    private static Rotation rotation;
    public static EventHandler RotationChanged;
    public static Rotation Rotation
    {
        get
        {
            return rotation;
        }
        set
        {
            if (Rotation != value)
            {
                rotation = value;
                OnRotationChanged();
            }
        }
    }

    public static bool IsLandscape
    {
        get
        {
            return Rotation == Rotation.Rotation90 
                || Rotation == Rotation.Rotation270;
        }
    }

    private static void OnRotationChanged()
    {
        if (RotationChanged != null)
            RotationChanged(null, EventArgs.Empty);
    }
}

And here is the OS specific part where you set the orientation.

Android version:

public class MainActivity : AndroidActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        UpdateCurrentRotation();
        base.OnCreate (bundle);

        Xamarin.Forms.Forms.Init (this, bundle);

        SetPage (App.GetMainPage ());
    }

    public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);
        UpdateCurrentRotation();
    }

    private void UpdateCurrentRotation()
    {
        switch (WindowManager.DefaultDisplay.Rotation)
        {
            case  SurfaceOrientation.Rotation0:
                Orientation.Rotation = Rotation.Rotation0;
                break;
            case SurfaceOrientation.Rotation90:
                Orientation.Rotation = Rotation.Rotation90;
                break;
            case SurfaceOrientation.Rotation180:
                Orientation.Rotation = Rotation.Rotation180;
                break;
            case SurfaceOrientation.Rotation270:
                Orientation.Rotation = Rotation.Rotation270;
                break;
        }
    }
}

Windows Phone version (note that you have to set SupportedOrientations="PortraitOrLandscape" in your MainPage.xaml to enable rotation of the page):

public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
        UpdateRotation();
        Forms.Init();
        Content = App16.App.GetMainPage().ConvertPageToUIElement(this);
    }

    private void UpdateRotation()
    {
        if ((Orientation & PageOrientation.PortraitUp) 
== PageOrientation.PortraitUp) App16.Orientation.Rotation = Rotation.Rotation0; else if ((Orientation & PageOrientation.PortraitDown)
== PageOrientation.PortraitDown) App16.Orientation.Rotation = Rotation.Rotation180; else if ((Orientation & PageOrientation.LandscapeLeft)
== PageOrientation.LandscapeLeft) App16.Orientation.Rotation = Rotation.Rotation90; else App16.Orientation.Rotation = Rotation.Rotation270; } protected override void OnOrientationChanged
(OrientationChangedEventArgs e) { UpdateRotation(); base.OnOrientationChanged(e); } }

Sadly I have no iOS device at this time, but it should be pretty easy to support it as well.

At the beginning of the page/activity and each time orientation changes the current rotation is sent to Orientation class in PCL.

At this point we have the rotation information and event RotationChanges that notifies about changes in rotation. Now this information can be used to achieve the dynamic layout changes.

For that purpose I’ll use a Grid ContentView derived class that can be nicely used with XAML.

public class Rotational: ContentView
{
    public View Landscape { get; set; }
    public View Portrait { get; set; }
    public string LandscapeType { get; set; }
    public string PortraitType { get; set; }
    private bool isPortrait;

    protected override void OnParentSet()
    {
        base.OnParentSet();
        VisualElement view = ParentView;
        while (!(view is Page))
        {
            view = view.ParentView;
        }
        Page page = (Page)view;
        page.Disappearing += page_Disappearing;
        page.Appearing += page_Appearing;
    }

    void page_Appearing(object sender, EventArgs e)
    {
        Orientation.RotationChanged += CurrentOrientation_Changed;
        Update();
    }

    private void CurrentOrientation_Changed(object sender, EventArgs e)
    {
        Update(); 
    }

    void page_Disappearing(object sender, EventArgs e)
    {
        Orientation.RotationChanged -= CurrentOrientation_Changed;   
    }

    private void Update()
    {
        if (Content == null || Orientation.IsLandscape && isPortrait ||
            !Orientation.IsLandscape && !isPortrait)
        {
            Children.Clear();
            if (RhOrientation.IsLandscape)
{
isPortrait = false;
if (Landscape != null)
{
Content = Landscape;
}
else
{
View child = FindContentView(LandscapeType);
Content = child;
}
}
else
{
isPortrait = true;
if (Portrait != null)
{
Content = Portrait;
}
else
{
View child = FindContentView(PortraitType);
Content = child;
}
} } } private View FindContentView(string contentViewName) { var query = from t in GetType().GetTypeInfo().Assembly.DefinedTypes where t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(ContentView)) && t.Name == contentViewName select t; var contentViewTypeInfo = query.SingleOrDefault(); if (contentViewTypeInfo != null) { ContentView page = (ContentView)Activator.CreateInstance
(contentViewTypeInfo.AsType()); return view; } else return null; } }

The class is named Rotational and defines four properties: Portrait, PortraitPage, Landscape and LandscapePage. Portrait and Landscape are of type View and you can store View derived classes that would appear based on orientation. Here is an example:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       xmlns:v="clr-namespace:App16;assembly=App16"
                       x:Class="App16.TestPage">
  <v:Rotational>
    <v:Rotational.Landscape>
      <StackLayout Orientation="Vertical">
        <Label Text="Landscape" HorizontalOptions="Center" />
      </StackLayout>
    </v:Rotational.Landscape>
    <v:Rotational.Portrait>
      <StackLayout Orientation="Vertical">
        <Label Text="Portrait" HorizontalOptions="Center" />
      </StackLayout>
    </v:Rotational.Portrait>
  </v:Rotational>
</ContentPage>

Note that namespace declaration is required (xmlns:v="clr-namespace:App16;assembly=App16"). The above definition will show a label saying Portrait or Landscape, depending on device rotation and will change dynamically. The drawbacks of this approach are that both configurations are in-memory and the page might become a bit bloated.

Hence the second pair of properties: PortraitPage and LandscapePage. These are of string type and allow to enter the page class names the content of which will be used dynamically. Here is an example:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:v="clr-namespace:App16;assembly=App16"
                       x:Class="App16.TestPage">
  <v:Rotational PortraitType="PortraitTestContent" 
LandscapeType="LandscapeTestContent" /> </ContentPage>

Additional two pages are required (PortraitTestContent.xaml and LandscapeTestContent.xaml):

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="App16.PortraitTestPage">
    <Label Text="Portrait test" VerticalOptions="Center" 
HorizontalOptions="Center" /> </ContentView> ... <ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="App16.LandscapeTestPage"> <Label Text="Landscape Test" VerticalOptions="Center"
HorizontalOptions="Center" /> </ContentView>

The pages are found using reflection and based on their names (no namespace is used).

This method is more memory efficient since it loads required content on demand and discards it afterwards. On the other side it is slower due to the loading of the page.

So, here you have it. What do you think? Is there a better way?

The sample is attached.

Rotational.zip (77.2KB)

Update 1: Instead of dynamically loading ContentPage and then using its content, ContentView should be used (it is XAML supported). That'd be a change in FindPageElement method to FindContentView.
Update 2: Changed base type for Rotational from Grid to ContentView.

Note: sample hasn't been updated from original version.

An alpha version of memory profiler for Xamarin Android

Memory profiling is one of the pillars of a good application. Even more important is on mobile devices since memory is usually scarce there. But sadly, there is no memory profiler for Xamarin Android development. Actually there is some raw support but lacks UI and friendliness. Hence I’ve built my own memory profiler.

This is an alpha quality version.

How it works

Since version 4.14 Xamarin has a (not) very visible support for memory profiling. But even with this support it isn’t easy to profile. With each garbage collection a log file is written on the device containing all the relevant data in a text format. Note that once you turn profiling on with

adb shell setprop debug.mono.profile log:heapshot

This setting is global and it works on all Xamarin apps on the device. Remember to turn it off afterwards if you don’t need it anymore to avoid, I guess, a huge performance hit.

There are two problems with the existing support here:

  • hard to trigger a garbage collection manually
  • hard to analyze data

My solution tackles both problems. The solution is divided into two parts.

Server side

The library available through NuGet does two things:

  • broadcasts its presence through UDP
  • allows triggering garbage collection from client

The library supports API Level 4 (Xamarin v1.6) and above.

Here is the NuGet package URL. You can also install it using this Package Manager Console command:

Install-Package RhMemProfiler.Server –Pre

The package is marked as prerelease and it won’t appear in NuGet Package manager if it isn’t set for Include Prerelease.

Once package has been added go ahead and create a global variable of type RhMemProfiler.Server.Beacon and initialize it with a friendly name and package name, like:

RhMemProfiler.Server.Beacon beacon;
….
beacon.Start("your friendly name", PackageName);

PackageName is the name of your package and it is ContextWrapper’s property.

Client side

This is a Windows application distributed through ClickOnce. After installation you’ll be prompted to open the firewall for the application. This is required since it, well, uses UDP and TCP to communicate with the server side.

profilerPrivate networks access is enough unless your mobile device is running on public network.

Once that is done you’ll be presented with a main window:

profiler

If your application on mobile device/emulator is running then you’ll see at least one option (one per IP on the device) in the combo box left of Connect button. That list contains friendly name (used when initializing on server) and its IP address. Pick any of them (IP doesn’t matter at this time). Hit Connect button.

If connection is successful you’ll see Conncted text in bottom left corner. If this is the first time you are connecting and/or memory profiling isn’t enabled yet on the device then you’ll be presented the Enable Profiling button, like:

enableprof

Enable profiling, restart mobile device application, disconnect, connect again and your are good to start memory profiling:

enableprof

Once there were at least two garbage collections and a snapshot has been taken afterwards you are able to compare them by selecting start and end version.

Collect Garbage … forces garbage collection on the mobile device
Snapshot … collects memory profiling log file from the device
Disable profiling … disables profiling on the device (profiling is per device, not per application – it affects all Xamarin apps on that device)
Only with source … shows only types from your package
Group panel … lets you group columns
Start and End … memory profile versions to compare to

Test

Imagine I have a class

public class MemLeak
{
    public string Value;
}

and a list of these somewhere defined. If I do a garbage collection before, when list is empty, and after one instance of MemLeak has been added I’ll see something like this when comparing before and after:

leak

It is pretty much obvious that the count of MemLeak instances increased by 1 and there are total of two instances of it around (actually I created one before that’s why there are two of them).

Memory profiling strategy

Memory profiling works by comparing state before and after. Usually a garbage collection is taken before some action and after that action. If the number of some instance increased without a valid reason it means that the application is leaking memory. Professional memory profilers help you even pinpointing the source of the leaks, however in our case, Xamarin doesn’t have that data available through this strategy.

Known limitations

  • ADB has to be in the path.
  • Only one device or emulator can be connected to the computer at the same time (the combo lets you pick the application but not the IP)

Final words

This is an alpha release, so be gentle with it and do not complain if your computer explodes because of it. It is something I wanted to release even at this stage for you to play with. It is actually pretty functional. So, feedback is appreciated and so are questions but I don’t guarantee anything, the development is done in my spare time (like that there is any Smile) for now. Hope you’ll find it useful.

Troubleshooting memory leaks in Xamarin.Android

I was testing an application I am building with Xamarin/Android. One of the tests was rotating the device while Google Maps fragment being shown. By default each time the orientation changes the activity and its views/fragments are recreated. IOW it is a good test for possible memory leaks because the recreation can be frequent.

I was quite surprised seeing a huge memory increase each time. Those eventually lead to an OutOfMemory in Java stack somewhere in Google Maps. After double checking that managed Xamarin code wasn’t leaking (i.e. retaining the said fragment somehow) anything I was starting to wonder whether Google Maps fragment is leaking internally. Perhaps only when combined with Xamarin. That’d be odd but not impossible.

Thus I started Android Studio and crafted a repro in pure Java. It wasn’t leaking. Thus it must have something to do with Xamarin. But what? Xamarin is providing a component to Google Maps (.net wrapping). Is it possible that there is a problem? Switching back to Xamarin and a few more tests later I couldn’t create a non leaking version. No matter what I did I still got leaks.

Suspecting a problem within Xamarin somewhere I decided to report a bug to bugzilla (Xamarin’s bug reporting web, not support) about it and mail a question to Xamarin support. The Jonathan Pryor’s response on bugzilla was lightning fast. In an hour or so he solved the mystery. The response from official support line was fast as well. (kudos to Xamarin on both).

It turns out that I was bitten with unmanaged memory pressure issue. Actually with unmanaged managed memory pressure issue. The thing is that Xamain/.net doesn’t know anything about unmanaged memory consumption. This is well known to .net developers, or at least, it should be. So, if you allocate a huge unmanaged piece of memory the .net won’t know about its size and won’t fire garbage collection automatically when it is released even it you are running low on memory (there are ways to let it know the memory consumption but that isn’t automatic). That’s usually valid for native code. But in the case of Xamarin, Java part is also unmanaged code to Xamarin (albeit Java is managed, but managed within Java with its own garbage collector).

Each time the Google Maps fragment was created and destroyed Xamarin created and “released” a single reference to maps fragment. By released I mean it was referenced from anywhere anymore and thus available for garbage collection by Xamarin garbage collector. But since .net saw only few bytes in that reference (which in turn referenced a ton of Java objects) it didn’t fire garbage collection automatically (and Java garbage collector couldn’t reclaim the memory because it was referenced by Xamarin) thus memory usage was increasing by huge steps. Strictly speaking this wasn’t a memory leak because all the memory would be reclaimed eventually - when garbage collection would run.

And that’s exactly how I solved it – I now run a manual garbage collection at least upon fragment creation (to reclaim the memory used by previous one). Problem solved. The bottom line is that you might run manual garbage collection after releasing a reference to Java object which internally uses plenty of memory. Also, calling Dispose on Xamarin objects helps (they might release reference to Java’s counterpart). In my case I couldn’t call Dispose because my fragment was created by layout inflation (actually I guess, I could by obtaining a reference to it, but that wasn’t obvious nor it might not help).

Here is more about Xamarin Garbage Collection.

Json.NET, Android/Xamarin and date serialization

In case you are using JSon.NET with Android/Xamarin you might encounter an “Object null reference” exception when trying to serialize (and probably deserialize as well) a type that contains DateTime property. The null object in question is TimeZoneInfo.Local.

This error happens when Android has no time zone set and thus Xamarin doesn’t set that property because it doesn’t know what time zone to use. There is a simple test where you can inspect Android’s time zone settings, just fire this command line:

adb shell getprop persist.sys.timezone

If it returns a blank line it means you are in trouble. A simple workaround for development is to set manually Android’s time zone through Settings/Date & Time or just fire another command line (i.e. setting time zone to Belgrade):

adb shell setprop persist.sys.timezone Europe/Belgrade

This works when using Genymotion emulator. Other than this there is no way to manually set the TimeZoneInfo.Local (perhaps it might be set through reflection, didn’t try it) which means your application won’t work in affected devices. Luckily the bug has been fixed and Xamarin will default to time zone defined by Java.Util.TimeZone.Default.ID. So, hopefully, the problem will go away for good.

A memory profiler for Xamarin.Android

Here is a first ever snapshot of my home-grown memory profiler for Xamarin.Android.

While very spartan it does the core job – comparing two snapshots for objects with growing instances (aka memory leaks). An array of Autofac.Core.IRegistrationSource[] is showing its references (one root, one to a List<>).

There you. Interested?

PS. Sample features DevExpress WPF components, chiefly XpfGrid.

Using Autofac with Xamarin

Good news is that Autofac, my IoC container of choice, works with Xamarin and even within Portable Class Library.  However there is one potential pitfall and it seems it happens at least when you use factories.

Imagine resolving ITubo defined as:

public class Tubo: ITubo
{
    public Tubo(Func<ITubo> tuboFactory)
    {}
}

public interface ITubo
{}

Note the use of factory through Func<ITubo>. In this case Autofac uses reflection and perhaps some runtime IL code generation. Now, try running the following piece of code on Xamarin.Android:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Tubo>().As<ITubo>();
var container = builder.Build();
container.Resolve<ITubo>();

It is simple registration and after that I do resolve the interface. When you run this code it will most probably work. But that’s only because you are running it in Debug configuration. Now try running in in Release configuration. It will most probably throw an exception at you:

Autofac.Core.DependencyResolutionException: An exception was thrown while executing a resolve operation.

Not very informative but at least the call stack shows that problem happens within System.Core assembly. And it isn’t Autofac’s fault at all.

The reason for the problem is simple but perhaps not the most obvious one. Default project settings are that at Release configuration it cuts out all of the unused code from SDK libraries (Xamarin stuff which is basically all .net BCL) and combines all of the assemblies into a single file - through its linker (at Debug time it uses shared libraries as would .net on Windows). And since Autofac is doing operations at runtime (at least when it comes to factories), linker doesn’t see those and simply cuts off unused types at compilation time to reduce the output size. Read more about Xamarin linking process here:

Linking

The nasty part is that you won’t know what types are cut off until you run the application in Release configuration. Remember, always try your applications in Release configuration!

The solution

Anyway, the solution is, as I’ve found out, rather simple. Just instruct linker to leave alone (don’t optimize) System.Core assembly. If you are using Visual Studio the go to Project/Properties, Android Options tab and enter System.Core text into Skip linking assemblies text box. If you are using Xamarin IDE the go to Project/Properies, Build/Android Build tab, Linker subtab and enter the same System.Core into Ignore Assemblies text box (didn’t try this one). That’s it, linker will leave alone that assembly and Autofac will happily run even in Release configuration.

Luckily the difference in output file size isn’t that significant: 450KB in worst case.

Invoking DatePickerDialog asynchronously with Xamarin.Android

Invoking a DatePickerDialog in Xamarin.Android is a bit tricky because it is done through callbacks and at the end one has to dispose it as well. Hence I present asynchronous extension methods PickDateAsync and PickDateAndAssignAsync.

With my code you can use this syntax and don’t worry about DatePickerDialog disposal:

EditText et1 = FindViewById<EditText>(Resource.Id.editText1);
await et1.PickDateAndAssignAsync();

There is also an overload that accepts an instance of CancellationToken. Here are the methods:

public static class DatePickerExtension
{
    public static Task<DateTime> PickDateAsync(this EditText dateEdit)
    {
        return dateEdit.PickDateAsync(CancellationToken.None);
    }
    public static Task<DateTime> PickDateAsync(this EditText dateEdit, CancellationToken ct)
    {
        TaskCompletionSource<DateTime> tsc = new TaskCompletionSource<DateTime>();
        DatePickerDialog picker = null;
        DateTime current;
        if (!DateTime.TryParse(dateEdit.Text, out current))
            current = DateTime.Now;
        picker = new DatePickerDialog(dateEdit.Context, (sender, e) =>
        {
            if (tsc != null)
            {
                if (ct.IsCancellationRequested)
                {
                    tsc.SetCanceled();
                }
                else
                {
                    tsc.SetResult(e.Date);
                }
                tsc = null;
                picker.Dispose();
            }
        }, current.Year,current.Month-1,current.Day);
        picker.Show();
        return tsc.Task;
    }

    public static Task PickDateAndAssignAsync(this EditText dateEdit)
    {
        return dateEdit.PickDateAndAssignAsync(CancellationToken.None);
    }
    public static async Task PickDateAndAssignAsync(this EditText dateEdit, CancellationToken ct)
    {
        DateTime date = await dateEdit.PickDateAsync(ct);
        if (!ct.IsCancellationRequested)
        {
            dateEdit.Text = date.ToString("d");
        }
    }
}
Enjoy awesome asynchronous C#/.net support.

Android activity life cycle and IoC

I was recently working on an Android (Xamarin, .net) application based on MvvmCross framework. Actually not just an Android app since it could be ported quite easily to other platforms, such as Windows Phone 8 or IPhone. Anyway, I was using inversion of control principle in a slightly incorrect way and thus done a mistake which revealed only a while after the deployment.

Here are the symptoms: Application would cold start fine, would resume fine when resume was done within reasonable time (no idea, depends on the device, in my case could be hours and it would work perfectly) but it wouldn’t resume well if the timespan was too much (i.e. a day or several hours). Instead of displaying the activity content it was just an actionbar with title without any content of menuitems.

By looking at android’s log on the device itself it was clear that there were problems with IoC resolve method. It yielded an “Object reference null” type of exception. I was resolving the reference within activity’s constructor. Odd error, since MvvmCross is supposed to trigger IoC registration  before the first activity is run. But somehow it wasn’t. I’ve mentioned that to Stuart (@slodge, man behind MvvmCross) and he instantly pointed to the mistake I made – I neglected the Android activity’s lifecycle. I immediately understood my mistake: I am used to put IoC references within constructors as arguments, which is mostly fine. Except when it comes to Android activities. The thing is that the entry point of a suspended application (with activity destroyed) is the activity itself, more precisely, its constructor. MvvmCross does trigger the IoC registration method correcly, but, of course, only after the activity is created and hence I was having errors in this particular situation.

The solution is fairly simple – move IoC resolving within OnCreate method, not sooner – that’s the point where you can be certain that MvvmCross initialization is done.

Before:

public abstract class SomeClass<T> : Activity
{
    protected readonly IFragmentPresenter fragmentPresenter;

    public MvxActivityFragmentHost(): this(Mvx.Resolve<IFragmentPresenter>())
    {}

    public MvxActivityFragmentHost(IFragmentPresenter fragmentPresenter)
    {
        this.fragmentPresenter= fragmentPresenter;
    }
    ...
}

after

public abstract class SomeClass<T> : Activity
{
    protected IFragmentPresenter fragmentPresenter;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        fragmentPresenter = Mvx.Resolve<IFragmentPresenter>();
    }
    ...
}

This change did the trick. A bit more work to inject the mock reference when testing but not a big deal.

Now, if you followed the post you might be asking, why the heck does application cold starts just fine, since it should get the same error. The explanation is rather simple – I am using a splashscreen activity when application cold starts. This one doesn’t have any IoC resolving involved at all, but it does initialize MvvmCross. So when it gets to the my problematic activity, the IoC is already in place.

Now, there you have it. Respect the Android activity lifecycle otherwise it will bit you.