Multi-Select ListView

I was just hanging around in the IDE this week and I had a chat with ListView. He was a very nice guy, but he was complaining about the fact that for some reason he could only ever select one item at a time…

I think of myself as a somewhat decent coder, and I decided to solve this problem – at least some part of it.

The easiest, and quickest, way to add multi-select capabilities to a ListView requires two steps: the “selectable” item and the “select” action.

The Selectable Item

I started with the model:

public class SelectableItem
{
    public object Data { get; set; }
    public bool IsSelected { get; set; }
}

But, since we are doing data binding, I created a bindable object that has several bindable properties:

public class SelectableItem : BindableObject
{
    public static readonly BindableProperty DataProperty =
        BindableProperty.Create(
            nameof(Data),
            typeof(object),
            typeof(SelectableItem),
            (object)null);

    public static readonly BindableProperty IsSelectedProperty =
        BindableProperty.Create(
            nameof(IsSelected),
            typeof(bool),
            typeof(SelectableItem),
            false);

    public SelectableItem(object data)
    {
        Data = data;
        IsSelected = false;
    }

    public SelectableItem(object data, bool isSelected)
    {
        Data = data;
        IsSelected = isSelected;
    }

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set { SetValue(IsSelectedProperty, value); }
    }
}

You may have noticed that I didn’t create a generic type. This is because later on we are going to want to get the value of the IsSelected property from the ItemSelected event handler, and we won’t know what the type is. However, we can create a generic type that inherits from this base type:

public class SelectableItem<T> : SelectableItem
{
    public SelectableItem(T data)
        : base(data)
    {
    }

    public SelectableItem(T data, bool isSelected)
        : base(data, isSelected)
    {
    }

    // this is safe as we are just returning the base value
    public new T Data
    {
        get { return (T)base.Data; }
        set { base.Data = value; }
    }
}

We now have a nice generic type for the developer (us) and a non-generic type for the event (the machine).

The Selectable ListView

The next step is to hook up the ListView with the selectable items. So, we will need a data field on the view model or the Page – depending on how you work (note the generic SelectableItem):

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        Items = new ObservableCollection<SelectableItem<string>>();

        BindingContext = this;
    }

    public ObservableCollection<SelectableItem<string>> Items { get; }
}

And, we need a list item that has a “checked” state (here it is just a red block):

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <!-- the "check" mark -->
                    <BoxView IsVisible="{Binding IsSelected}" 
                             WidthRequest="12" HeightRequest="12"
                             Color="Red" />
                    <!-- the text/data -->
                    <Label Text="{Binding Data}" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

We should now have a list of items that can show either a selected or unselected state. To handle when an item is selected by the user, we just need an event on the list:

<ListView ... ItemSelected="OnItemSelected">
    ...
</ListView>

And then we write the code to toggle the selection (note the non-generic SelectableItem):

private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    var item = e.SelectedItem as SelectableItem;
    if (item != null)
    {
        // toggle the selection property
        item.IsSelected = !item.IsSelected;
    }

    // deselect the item
    ((ListView)sender).SelectedItem = null;
}

This is all we need, and we will have a ListView that that can support multiple items being selected.

Improvements

We could call it a day, but we are not going to. The day has just started, and we are thinking that we might want to use this in multiple places. We can just copy the logic – mainly the event and cell view, but there are better ways (and we don’t like duplicate code).

Attached Property

The first thing that we will look at is if we can magically do the event hookup with a single property instead of the event:

<ListView ... local:MultiSelectListView.IsMultiSelect="True">
    ...
</ListView>

That looks nicer than the event, and we have a couple of benefits: no code in the page, the event code is written once and the property is bindable.

What we are doing here is using an attached property to “inject” a bindable property into an existing view type:

public static class MultiSelectListView
{
    public static readonly BindableProperty IsMultiSelectProperty =
        BindableProperty.CreateAttached(
            "IsMultiSelect",
            typeof(bool),
            typeof(ListView),
            false,
            propertyChanged: OnIsMultiSelectChanged);

    public static bool GetIsMultiSelect(BindableObject view)
        => (bool)view.GetValue(IsMultiSelectProperty);

    public static void SetIsMultiSelect(BindableObject view, bool value)
        => view.SetValue(IsMultiSelectProperty, value);

    private static void OnIsMultiSelectChanged(
        BindableObject bindable, object oldValue, object newValue)
    {
        var listView = bindable as ListView;
        if (listView != null)
        {
            // always remove event
            listView.ItemSelected -= OnItemSelected;

            // add the event if true
            if (true.Equals(newValue))
            {
                listView.ItemSelected += OnItemSelected;
            }
        }
    }

    private static void OnItemSelected(
        object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as SelectableItem;
        if (item != null)
        {
            // toggle the selection property
            item.IsSelected = !item.IsSelected;
        }

        // deselect the item
        ((ListView)sender).SelectedItem = null;
    }
}

We now have a super easy way to turn any list into a multi-select list with a single property.

The ItemsSource

Another area we can improve is the ItemsSource collection. Right now we have quite a long type with two generic types:

public ObservableCollection<SelectableItem<string>> Items { get; }

We can not only make this shorter, but more convenient by creating a new type that derives from ObservableCollection. And, now that we have a new type, we can add additional methods so that we don’t even have to deal with the SelectableItem type at all:

public class SelectableObservableCollection<T> : ObservableCollection<SelectableItem<T>>
{
    ...

    // a constructor overload
    public SelectableObservableCollection(IEnumerable<T> collection)
        : base(collection.Select(c => new SelectableItem<T>(c)))
    {
    }

    ...

    // a convenience property
    public IEnumerable<T> SelectedItems
        => this.Where(i => i.IsSelected).Select(i => i.Data);

    ...

    // a method overload
    public void Add(T item)
    {
        Add(new SelectableItem<T>(item));
    }
}

When we use this new type, we can do some cool things:

// a nice type
public SelectableObservableCollection<string> Items { get; }

// cool methods and properties
private void OnDoSomething()
{
    Debug.WriteLine("You have selected:");

    // use a property
    foreach (var selected in Items.SelectedItems)
    {
        Debug.WriteLine($" - {selected.Data}");
    }

    // use a method
    Items.Add("A New String");
}

The Cell

Finally, as you may have a really cool check mark for selected items (unlike our red block now), we will want to be able to create a custom cell type that will allow us to just specify the item contents, and automatically handle the check mark:

<ListView ItemsSource="{Binding Items}"
          local:MultiSelectListView.IsMultiSelect="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <local:SelectableViewCell>
                <Label Text="{Binding}" />
            </local:SelectableViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

This requires a new Cell type:

[ContentProperty(nameof(DataView))]
public class SelectableViewCell : ViewCell
{
    public SelectableViewCell();

    public View CheckView { get; set; }

    public View DataView { get; set; }
}

I have left the implementation of this cell to your imagination… just kidding, I have it all in my my repository. You can find all this code, a sample app and more there too:

I hope you enjoyed this short(ish) post and are able to make your list views handle the selection of multiple items.

Embedding Xamarin.Forms in Native Apps

Xamarin.Forms is really cool! It allows you to almost write your app once and then compile for many platforms. With Xamarin.Forms, you can quickly produce multiple apps, but, you can also take advantage of some awesome features – such as cross-platform UIs in XAML, data binding, sharing code and much more.

Xamarin.iOS, Xamarin.Android and UWP are also fantastic! You can get 100% of the platform APIs and you can produce apps that are super fast and polished.

Most of the time you have to choose between one or the other. Sure, you can do custom renderers or effects in Xamarin.Forms to get more platform API access. And sure, you can use frameworks that help you share code with native Xamarin and Windows apps. Before today, you had one of two choices:

  • Xamarin.Forms for 100% shared code and UI
  • Xamarin/Windows Native for polished, platform-specific APIs and UIs

But… why not have both? Recently Xamarin/Microsoft shared on the blog that Xamarin.Forms can be embedded into native apps. This means that you can take your existing (or new) native app and just drop in a Xamarin.Forms page without doing anything special. You lose nothing, and gain a whole lot more. You can still use XAML, data binding, converters, effects and everything else that comes with Xamarin.Forms – but now from within you native app code and UI.

I have a nice sample app that you can pull from GitHub. Be sure to check it out and let me know what you think of this new functionality. I will try and keep that repository up to date with any new developments.

Xamarin.Forms embedded in native apps

Getting the Bits

To embed Xamarin.Forms into your native app, you just need to install a preview NuGet from the Xamarin.Forms pre-release feed:

https://www.myget.org/F/xamarinforms-dev/api/v3/index.json

Then, you want to install the 3.0.0.100-embeddingpreview NuGet into any Xamarin.Forms projects as well as into the native app projects.

That is it! Now you should be able to create your shared page.

If you have any questions or comments you can do this using the Xamarin discussion (Preview: Xamarin.Forms Embedding) on the forums.

It is important to note that this is a pre-release and functionality may change with subsequent releases.

Creating Shared Pages

Let’s take an example of an existing app that you want to add the ability to register and/or login to save user preferences on some cloud service – such as Azure. Your app is out and in the wild, users are loving it, and, you have just received feedback that they want to login across devices and keep their preferences.

What do you do? Well you could create a few screens for each platform and then share some code. But, as all the login screens are going to look the same and work the same, why not do everything in shared XAML?

So, the first thing we can do is to either create a shared project, a .NET Standard library or even a PCL. We then just need to install the pre-release Xamarin.Forms NuGet. Finally, we can go ahead an add a new XAML page. Just right-click and do “Add” > “New Item…” > “Content Page (XAML)” and then you have a new page.

In this page below, I am using data binding, converters, resource dictionaries and good old XAML markup:

<?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:app="clr-namespace:EmbeddedFormsDemo.Converters"
             x:Class="EmbeddedFormsDemo.Views.LoginPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <app:NegateConverter x:Key="Negate" />
            <app:NullInvisibilityConverter x:Key="NullInvisibility" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ScrollView>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <StackLayout Spacing="12" Grid.Row="1">
                <StackLayout.Padding>
                    <OnPlatform x:TypeArguments="Thickness" 
                                Android="24" iOS="24" WinPhone="0" />
                </StackLayout.Padding>
                <Label Text="Enter any username/password:"
                       HorizontalTextAlignment="Center"
                       FontSize="12" />
                <Entry Keyboard="Email" 
                       Placeholder="username or email"
                       Text="{Binding UserName}" 
                       HorizontalTextAlignment="Center"
                       IsEnabled="{Binding IsBusy, Converter={StaticResource Negate}}" />
                <Entry IsPassword="True" 
                       Placeholder="password" 
                       Text="{Binding Password}" 
                       HorizontalTextAlignment="Center"
                       IsEnabled="{Binding IsBusy, Converter={StaticResource Negate}}" />
                <Button Text="Log In" 
                        Command="{Binding LoginCommand}"
                        IsEnabled="{Binding IsBusy, Converter={StaticResource Negate}}" />
                <Label Text="{Binding ErrorMessage}" 
                       HorizontalTextAlignment="Center"
                       FontSize="12"
                       TextColor="Red" 
                       IsVisible="{Binding ErrorMessage, Converter={StaticResource NullInvisibility}}" />
                <ActivityIndicator IsRunning="{Binding IsBusy}" 
                                   IsVisible="{Binding IsBusy}" />
            </StackLayout>
        </Grid>
    </ScrollView>
</ContentPage>

Then, in our code-behind, we can write out code to work with the UI. Here we have made use of several features such as binding, commands, messaging and async/await:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
    public const string LoginMessage = "login";

    private readonly JsonPlaceholderApi api;
    private string errorMessage;

    public LoginPage()
    {
        InitializeComponent();

        // initialize our fake services
        api = new JsonPlaceholderApi();

        // set up the data binding
        LoginCommand = new Command(OnLogin);
        BindingContext = this;
    }

    private async void OnLogin()
    {
        IsBusy = true;

        // reset errors
        ErrorMessage = "";
        // try logging in with our fake services
        var user = await api.LoginAsync(UserName, Password);
        if (user == null) {
            // there was an error
            ErrorMessage = "There was a problem logging in.";
        } else {
            // let the app know we are finished
            MessagingCenter.Send(user, LoginMessage);
        }

        IsBusy = false;
    }

    public string ErrorMessage
    {
        get { return errorMessage; }
        set { errorMessage = value; OnPropertyChanged(); }
    }

    // we don't want to save this as the user types
    public string UserName { get; set; }

    // we don't want to save this at all
    public string Password { get; set; }

    // the login button uses this
    public ICommand LoginCommand { get; }
}

That is basically all we need to do in order to create our UI. The JsonPlaceholderApi type just makes use of http://jsonplaceholder.typicode.com to get some random data, the User type is just a simple POCO object and the converters are basic IValueConverter implementations.

Displaying Shared Pages in Native Apps

Once we have created our shared Xamarin.Forms page, we can just instantiate out Xamarin.Forms page and then ask for the native version.

On Android, the CreateFragment extension method will return a native Android Fragment, which we can then use as we would any other fragment. On iOS, we use the CreateViewController extension method and we will get out a native UIViewController that, again, we can use as we would any other view controller. And finally, on Windows, we use the CreateFrameworkElement extension method to get out a native FrameworkElement that we can also uses as any other element.

There are two steps to obtaining this native container, first we make sure Xamarin.forms is initialized:

// Android
Xamarin.Forms.Forms.Init(this, null);

// iOS
Xamarin.Forms.Forms.Init();

// Windows
// the `e` from `Application.OnLaunched(LaunchActivatedEventArgs e)`
Xamarin.Forms.Forms.Init(e);

Once that is done, we can then get the native page:

// create the Xamarin.Forms page for all platforms
var formsPage = new MyFormsPage();

// Android - get the native Fragment
var nativeFragment = formsPage.CreateFragment(this);

// iOS - get the native UIViewController
var nativeController = formsPage.CreateViewController();

// Windows - get the native FrameworkElement
var nativeElement = formsPage.CreateFrameworkElement();

Now that we have the native view, we can just go ahead and use it as if it was created using the traditional mechanisms.

Xamarin.Android and Xamarin.Forms

When using Xamarin.Forms with an Android app, we are going to need to handle the native Fragment that represents the page. To this end, our Android app is using a native .axml layout with a FrameLayout that will hold all our fragments:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <!-- the other bits of UI -->
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/frameLayout" />
    <!-- some more UI -->
</RelativeLayout>

Then, in our main activity code, we load this UI as normal and everything works as it usually does. When we want to show our new XAML page at some point, all we need to do is to just make sure Xamarin.Forms is initialized and then instantiate the page before navigating to it:

using Xamarin.Forms.Platform.Android;

public void DisplayLogin()
{
    if (!Xamarin.Forms.Forms.IsInitialized)
    {
        // initialize Xamarin.Forms before we use it
        Xamarin.Forms.Forms.Init(this, null);

        // we want to listen to the messaging center
        Xamarin.Forms.MessagingCenter.Subscribe(this, LoginPage.LoginMessage, (User user) =>
        {
            // update the app
            CurrentUser = user;

            // go back to the main page
            FragmentManager.PopBackStack();
        });
    }

    // create the login page (Xamarin.Forms ContentPage)
    var loginPage = new LoginPage();

    // get hold of the native Android fragment that represents the Xamarin.Forms page
    var loginFragment = loginPage.CreateFragment(this);

    // show the login screen (native Xamarin.Android)
    FragmentManager
        .BeginTransaction()
        .AddToBackStack(null)
        .Replace(Resource.Id.frameLayout, loginFragment)
        .Commit();
}

Xamarin.iOS and Xamarin.Forms

If we want to use Xamarin.Forms in our iOS app, we will be showing a new UIViewController. We first need to make sure that Xamarin.Forms is initialized and then we can just go ahead and create the desired page. We then get the native view controller that can be presented using all the existing means:

using Xamarin.Forms;

partial void OnLoginClicked(UIButton sender)
{
    if (!Xamarin.Forms.Forms.IsInitialized)
    {
        // initialize Xamarin.Forms before we use it
        Xamarin.Forms.Forms.Init();

        // we want to listen to the messaging center
        Xamarin.Forms.MessagingCenter.Subscribe(this, LoginPage.LoginMessage, (User user) =>
        {
            // update the app
            User = user;

            // go back to the main page
            NavigationController.PopViewController(true);
        });
    }

    // create the login page (Xamarin.Forms ContentPage)
    var loginPage = new LoginPage();

    // show the login screen
    var viewController = loginPage.CreateViewController();
    NavigationController.PushViewController(viewController, true);
}

Windows UWP and Xamarin.Forms

When we want to show a Xamarin.Forms page within our native UWP app, we will work with a FrameworkElement. Like with all the other platforms, we have to make sure that Xamarin.Forms is initialized and then just create the page. Once we have obtained the native element, we can just place it anywhere we need it to be. In this example, I am placing my view in a Flyout as the it is being opened:

using Xamarin.Forms;

private void OnLoginFlyoutOpening(object sender, object e)
{
    var flyout = sender as Flyout;

    if (!Xamarin.Forms.Forms.IsInitialized)
    {
        // initialize Xamarin.Forms before we use it
        Xamarin.Forms.Forms.Init(App.LastLaunchEventArgs);

        // we want to listen to the messaging center
        Xamarin.Forms.MessagingCenter.Subscribe(this, LoginPage.LoginMessage, (User user) =>
        {
            // update the app
            User = user;
            // show some message for some random reason
            WelcomeText = $"Welcome back {user.Name}!";

            // hide the login screen
            flyout.Hide();
        });
    }

    // create the login page (Xamarin.Forms ContentPage)
    var loginPage = new LoginPage();

    // set the native dialog to contain the shared login
    var loginElement = loginPage.CreateFrameworkElement();
    flyout.Content = new Frame
    {
        Content = loginElement,
        Width = 300,
        Height = 200
    };
}

Summary

In this fairly long post, we looked at how to quickly embed a Xamarin.Forms page into an existing native app. The process is easy and painless, and will only get better.

You can download the full code from my GitHub repository and try it out for yourself. And maybe have a look at your app and see if some of those screens that are exactly the same could use Xamarin.Forms.

You can also check out some links:

Some other people also have blogs:

And, then there is code:

Tasks: ContinueWith on UI Thread

Sometimes we need to perform a task in the background, but then we want to update the UI when it is completed.

We can make use of a Task and the ContinueWith method so that we can chain tasks together. To ensure that a task is performed on a specific thread, we specify which TaskSheduler to use. To get the UI thread scheduler, we can use TaskScheduler.FromCurrentSynchronizationContext() when we are on the UI thread:

If we are going to run a background task:

var uiThread = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() =&gt; {
    // do some work on a background thread
}).ContinueWith(task =&gt; {
    // do some work on the UI thread
}, uiThread);

If we need to carry a result from the previous background task:

var uiThread = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() =&gt; {
    // do some work on a background thread

    // return a value for the next task
    return true;
}).ContinueWith(task =&gt; {
    // do some work on the UI thread

    if (task.Result) {
        // make use of the result from the previous task
    }
}, uiThread));

Binding Flurry Analytics with Xamarin.Android

This week, I needed to use Flurry Analytics in my Xamarin.iOS and my Xamarin.Android apps, but there was no .NET SDK for these platforms. Flurry did provide a SDK for each platform, but it was the native libraries, which cannot be used directly in .NET. Given this, I decided to bind those native libraries using Xamarin.iOS and Xamarin.Android.

I have split this project up into four parts:

  1. Introduction and Pre-requisites
  2. Xamarin.iOS binding
  3. Xamarin.Android binding
  4. Flurry.Analytics in the wild

After binding the iOS SDK for Flurry Analytics, we are going to move onto the Android release. This task needs only one thing from the downloaded SDK:

  • [Android-sdk-path]/Android 4.1.0/FlurryAnalytics/FlurryAnalytics-4.1.0.jar

Of course, the version numbers may change for later releases. The java archive file (.jar) is going to be used to generate the .NET interfaces and enums, and then be embedded in the resulting assembly.

Just before we do the real binding, we should just create our C# solution for the Xamarin.Android binding. Just create a new project/solution and select the Android “Bindings Library” template. For my project name I used Flurry.Analytics.Android, but you could use anything.

The default project has a few files and directories in it, we will have a look at each one in depth as we go through the binding steps:

  • /Additions/ (this allows you to add arbitrary C# to the generated classes
    before they are compiled)
  • /Properties/AssemblyInfo.cs (the usual assembly information attributes)
  • /Jars/ (this directory is for Android .jars)
  • /Transforms/EnumFields.xml (this allows you to map Java int constants to C# enums)
  • /Transforms/EnumMethods.xml (this allows changes to method parameters and return types from Java int constants to C# enums)
  • /Transforms/Metadata.xml (this allows changes to be made to the final API)

Creating the Initial Binding

This step will involve just adding the jar to the project, and letting the compiler do it’s thing, but we will almost always have to go in and tweak a few things in the Metadata.xml.

So, first things first, add the jar file to the project and compile. The build will probably fail with error messages containing single character methods and types. This is because the actual jar file has been obfuscated. However this can easily be fixed.

The way the generation works is that there is a two step process, there is a tool that generates a bunch of xml files from the jar file. These xml files are then used to generate C# code. The Metadata.xml sits in between the two steps and can be used to transform the generated xml before the C# generation.

Tweaking the Generated Binding (Manifest.xml)

As we can see that the build fails on obfuscated types, we can remove these. The removal is safe as we are only preventing the .NET binding from being created, not actually removing the underlying Java members. And, as these items have been obfuscated, we can safely assume that we aren’t supposed to be accessing them anyway.

But, instead of removing each member or type that appears, we can use a great tool that will decompile the jar file and show us exactly what types are internal and what types we should be binding. I use JD-GUI, which is a free Java decompiler. They also have a nice online version, JD-Online. What we can do is to just upload the jar file here and see what’s inside:

  • com.flurry.android.impl.analytics.*
  • com.flurry.android.*
  • com.flurry.sdk.*

As we can see, the impl and sdk branches contain internal and obfuscated types, so we can remove those:

<remove-node path="/api/package[starts-with(@name, 'com.flurry.sdk')]" />
<remove-node path="/api/package[starts-with(@name, 'com.flurry.android.impl')]" />

After this, the build should now succeed and we will have an assembly that we can use. However, there are still some types that we can remove to clean the API a bit: InstallReceiver and Constants. InstallReciever is not used by the consumer, so this is safe to remove, but Constants is still used. If we remove this, then the consumer will not have access to the values on the type. We can see that Constants just contains the values representing male, female and unknown.

To remove the InstallReciever, we can add this line to Metadata.xml:

<remove-node path="/api/package[@name='com.flurry.android']/class[@name='InstallReceiver']" />

For the Constants type, we will do something different.

Managing the Enumerations (Additions & EnumFields.xml)

As we clean up the API, we want to remove the Constants type and replace it with an enum. One way to do this is to use the EnumFields.xml:

<mapping clr-enum-type="Flurry.Analytics.Gender" jni-interface="com/flurry/android/Constants">
    <field clr-name="Male" jni-name="MALE" value="1" />
    <field clr-name="Female" jni-name="FEMALE" value="0" />
    <field clr-name="Unknown" jni-name="UNKNOWN" value="-1" />
</mapping>

This will generate a nice enum for us, but this does leave an unused interface IConstants. As this is a very small library, we can do this mapping slightly differently. First we remove the entire Constants type in the Metadata.xml:

<remove-node path="/api/package[@name='com.flurry.android']/interface[@name='Constants']" />

Then, we can create the enum in the /Additions/ directory. To do this, add a new file (for example called FlurryAgent.cs) under this directory and add the enum:

public enum Gender
{
    Male = 1,
    Female = 0,
    Unknown = -1
}

Now there is one last thing to do before the API definition is complete. There is a SetGender method on the type FlurryAgent, which takes the type sbyte. It is not intuitive to use the Gender enum here, so we can fix this in a two step process. First we will create an overload in the FlurryAgent.cs file that accepts a Gender enum member as an argument:

public partial class FlurryAgent
{
    public static void SetGender(Gender gender)
    {
        FlurryAgent.SetGender ((sbyte)gender);
    }
}

And, what we can do is also hide the original member as the new overload is good enough:

<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='setGender']" name="visibility">internal</attr>

And with this, our binding is complete, although we can do a few nice changes to the namespace and parameter names.

Changing Parameter Names

Now that we have the binding complete, we can see that it is using the namespace Com.Flurry.Android, which is no .NET-like at all. We can change this to something better:

<attr path="/api/package[@name='com.flurry.android']" name="managedName">Flurry.Analytics</attr>

This maps the com.flurry.android package name to the neat Flurry.Analytics namespace. One last thing is to fix the parameter names. Sometimes you can use the JavaDocs, but in this case, I couldn’t get it to work. Doing it manually is not hard, but it is boring and time consuming, but here are a few.

This is the usual mapping:

<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='onStartSession']/parameter[@name='p0']" name="name">context</attr>
<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='onStartSession']/parameter[@name='p1']" name="name">apiKey</attr>
<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='onEndSession']/parameter[@name='p0']" name="name">context</attr>

If there are complicated parameter types (note the &lt;):

<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='logEvent']/parameter[@name='p1' and @type='java.util.Map<java.lang.String, java.lang.String>']" name="name">parameters</attr>

If there are overloads with different parameter types:

<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='onError']/parameter[@name='p2' and @type='java.lang.Throwable']" name="name">exception</attr>
<attr path="/api/package[@name='com.flurry.android']/class[@name='FlurryAgent']/method[@name='onError']/parameter[@name='p2' and @type='java.lang.String']" name="name">errorClass</attr>

After doing this for all the members, the binding is now complete.

Finishing Up

So far we have defined our API, added any additional logic or types, added the native library and added parameter names. This is all that is needed, so our library should build fine now and we should be able to use it in an Xamarin.Android app:

// the methods
FlurryAgent.StartSession(this, "PQSZJRK4B5BW8Q7YQQXF");

// the properties that we changed back into methods
string version = FlurryAgent.ReleaseVersion;

// the extra method that we added
FlurryAgent.SetGender (Gender.Male);

MonoGame Content without Visual Studio

MonoGame is free software used by game developers to create games for many different platforms. It is almost a Write Once, Play Anywhere!

Unfortunately, the content processing pipeline is not yet available for all platforms or even the later versions of Visual Studio. Here I will show you a way to build the content for any version of Windows, without Visual Studio.

Platforms

Currently supported platforms for MonoGame:

  • iOS (including Retina displays)
  • Android
  • Windows (OpenGL & DirectX)
  • Mac OS X
  • Linux
  • Windows Store Apps (for Windows 8 and Windows RT)
  • Windows Phone 8
  • PlayStation Mobile (currently 2D only)
  • OUYA, an Android-based gaming console

Currently Supported platforms for XNA:

  • Windows Phone 7
  • Xbox 360
  • Microsoft Windows

Support for Xbox One is currently under way with both Microsoft and the MonoGame teams. Microsoft is adding .NET support to the Xbox One and the MonoGame team is adding Xbox One support to MonoGame.

Content Processors

When creating games using MonoGame, there are 2 main parts to any game: the Content and the Code. The content is usually the textures, sounds and fonts in the game. The code is what you write, the logic.

At the current time MonoGame does not have its own content processors, so we will make use of the original XNA build tools. The MonoGame team is working on their tools, but it is not yet complete.

In order to process the content, we need two things: the processor tools and some sort of UI.

Installing the Content Pipeline

We will start off by setting up our content tools before we actually do anything. First we need the assemblies that come with XNA Game Studio. This is the toolset used for building the content that will appear in our game. The actual studio does not install on without Visual Studio 2010, so we have to cheat a bit.

First of all, we need to download XNA Game Studio 4.0 Refresh from Microsoft’s Download Center. Once this is complete, we will load the framework installers out of the studio setup file:

  1. Using 7-zip (or any other compression tool), open the newly downloaded XNAGS40_setup.exe.
  2. Inside the installer, there should be a redists.msi file, open it using “Open Inside” as we don’t want it to start installing.
  3. Extract the files named SharedFilesInstaller_File, XNAFXRedist40Setup_File and XNAPlatformToolsInstaller_File into a directory.
  4. Rename the three extracted files by adding a .msi extension in Windows Explorer, this “turns” them into installers.
  5. Install each of them one at a time.

Once this is done, we would have installed all the build tools required to package the content.

Installing the Interface

Next, we need to install the XNA Content Compiler. This allows the building of the content packages when not using Visual Studio 2010.

You can do this by downloading the XNA 4.0 Content Compiler source code from my fork. I have added some extra features that allow for more advanced content processing, such as, Compression and MipMap generation.

Once you have this, you should be able to open the solution in Visual Studio and build the application. Currently the compiler can only be used on Windows as the tooling is only available on Windows.

Binding Flurry Analytics with Xamarin

Over the last few days I have been creating a Xamarin.iOS and Xamarin.Android binding for Flurry Analytics SDKs. Flurry Analytics is a neat little library that allows for tracking of your app usage and various user stats.
And, because I really enjoyed my time doing this, I thought that I will share just a bit of the fun times and the not-so-fun times.

I have split this project up into four parts:

  1. Introduction and Pre-requisites
  2. Xamarin.iOS binding
  3. Xamarin.Android binding
  4. Flurry.Analytics in the wild

Pre-requisites

Before we start any coding, we need to get all our tools and files needed for the actual binding tasks.

I was using both Windows 8, with Visual Studio, and Mac OS X with Xamarin Studio. You can bind the Android library on either platform, but for iOS, it is easier to use the Mac. In this case, I will use the Mac for both iOS and Android.

Some of my very excellent sources for this process were the actual Xamarin documentation:

But, along with this info, there are just a few things that you may need. Firstly, it is good to update your Xamarin Studio to the latest stable release as this makes sure that all potential problems are minimized from the start.

Then, the next cool tool to get hold of is, Objective Sharpie, for binding iOS libraries. This tool is quite nifty for quickly generating the .NET interfaces from the Objective-C header files. It uses the header files not the actual compiled native library. The Xamarin docs on Objective Sharpie has a brief walkthrough on how to use the tool, so I will assume you know how to use it.

After we have all our tools ready to go, we need those SDKs from Flurry.

What I did was to create a free account by Flurry, and then created an Android and iOS Application using their dashboard. You have to have an application before they will let you download their SDKs. This step is pretty straight forward, so I won’t go into it here right now. Once you have created and downloaded the SDKs, you can extract them to a nice location for reference.

Now to get started with the real work…

But, as this is quite a long process, I will be splitting this article into this intro, the iOS binding and the Android binding. So, enjoy!

Binding Flurry Analytics with Xamarin.iOS

This week, I needed to use Flurry Analytics in my Xamarin.iOS and my Xamarin.Android apps, but there was no .NET SDK for these platforms. Flurry did provide a SDK for each platform, but it was the native libraries, which cannot be used directly in .NET. Given this, I decided to bind those native libraries using Xamarin.iOS and Xamarin.Android.

I have split this project up into four parts:

  1. Introduction and Pre-requisites
  2. Xamarin.iOS binding
  3. Xamarin.Android binding
  4. Flurry.Analytics in the wild

The first thing we are going to bind is the iOS SDK for Flurry Analytics. This task needs two things from the downloaded SDK:

  • [iOS-sdk-path]/Flurry-iOS-5.2.0/Flurry/Flurry.h
  • [OS-sdk-path]/Flurry-iOS-5.2.0/Flurry/libFlurry_5.2.0.a

Of course, the version numbers may change for later releases. The header file (.h) is going to be used to generate the .NET interfaces and enums. The library (.a) is going to be used in the project.

Just before we do the cool things, we should just create our C# solution for the Xamarin.iOS binding. Just create a new project/solution and select the “iOS Binding Project” template. For my project name I used Flurry.Analytics.iOS, but you could use anything.

The default project has a few files in it, we will have a look at each one in depth as we go through the binding steps:

  • ApiDefinition.cs (this is for the generated .NET interfaces from Objective Sharpie)
  • AssemblyInfo.cs (the usual assembly information attributes)
  • Extras.cs (this is for any additional changes that are needed for the bound types)
  • StructsAndEnums.cs (this is for any extra types that you wish to include in the final assembly)

Creating the Initial Binding

This step will involve using Objective Sharpie to get us started, but we will almost always have to go in and tweak a few things.

So, first things first, open Objective Sharpie and start the wizard. Select the Flurry.h header file, and I used the namespace Flurry.Analytics. After saving your file somewhere, we can start the tweaks. I don’t save the result into my solution as the amount of tweaks needed is high enough that I like to have a before and after file. Also, this library is very small. But, there is no reason why you couldn’t just save over the ApiDefinition.cs file in you project.

Before we start, here is a snippet from the Flurry.h file:

    // an enum
    typedef enum {
        FlurryLogLevelNone = 0,
        FlurryLogLevelCriticalOnly,
        FlurryLogLevelDebug,
        FlurryLogLevelAll
    } FlurryLogLevel;

    // the main class
    @interface Flurry : NSObject {
    }
    // ...
    + (void)setAppVersion:(NSString *)version;
    + (NSString *)getFlurryAgentVersion;
    + (void)startSession:(NSString *)apiKey;
    // ...
    @end

In this snippet of Objective-C goodness, there is an enum named FlurryLogLevel and an @interface named Flurry. This will translate into a C# enum and class respectively. It is also good to note that all the methods on this particular type will be static.

The generated C# for this snippet is:

    // the enum
    public enum FlurryLogLevel : [unmapped: unexposed: Elaborated] {
        None = 0,
        CriticalOnly,
        Debug,
        All
    }

    // the main class
    [BaseType (typeof (NSObject))]
    public partial interface Flurry {
        // ...
        [Static, Export ("appVersion")]
        [Verify ("ObjC method massaged into setter property", "Flurry/Flurry.h", Line = 61)]
        string AppVersion { set; }

        [Static, Export ("getFlurryAgentVersion")]
        [Verify ("ObjC method massaged into getter property", "Flurry/Flurry.h", Line = 80)]
        string GetFlurryAgentVersion { get; }

        [Static, Export ("startSession:")]
        void StartSession (string apiKey);
        // ...
    }

As you can see, the generated file is similar, but not quite the same.

Tweaking the Generated Binding (ApiDefinition.cs)

After we generated our C# files, there are several things to note:

  • This code doesn’t compile at all
  • A good few of our methods are set to properties, especially note the setter-only ones
  • There is a [Verify(...)] attribute which doesn’t even exist
  • Some [Export] attributes have a value that ends in a colon (:), and others do not
  • The type is not a class but an interface
  • The base type is specified as a [BaseType] attribute
  • The enum has the item prefixes removed

This is quite a list here, but not all are bad. Objective Sharpie can’t generate perfect code as Objective-C is not C#, so there will always be human intervention. In these cases, it will generate what it thinks to be best and then let you know.

The [Verify] attribute is one way that Objective Sharpie lets you know that it changed something. In this instance, it is letting us know that it changed the setAppVersion method into a property. This is because usually there is both a getter and a setter method for a Objective-C property. But in this case, it is actually a method.

As you may note, these properties have a slightly different [Export] attribute in that these members don’t end in a colon. This is valid for Objective-C property setters, but as this is a method, we should add a colon back. It is also valid for methods that take parameters.

So, to fix those properties, remove the [Verify] attribute. We should also fix the exported name, and for the setter property, add the colon back in.

    [BaseType (typeof (NSObject), Name = "Flurry")]
    public partial interface FlurryAgent {

        [Static, Export ("setAppVersion:")]
        void SetAppVersion (string version);

        [Static, Export ("getFlurryAgentVersion")]
        string GetFlurryAgentVersion ();

        [Static, Export ("startSession:")]
        void StartSession (string apiKey);

    }

As you can see here, I corrected the SetAppVersion write-only property by transforming it into a void method that exports to setAppVersion:. Note the full name and colon as this method takes a parameter.

Also, I needed to fix the GetFlurryAgentVersion read-only property by transforming it into a string method that exports to “getFlurryAgentVersion”. Note the lack of colon as this method takes no parameters.

And finally, I decided I wanted my final class to be called FlurryAgent to avoid confusion with the namespace as well as indicate that it was the Agent. In order to do this, All I needed to do was to rename the type and add the Name property in the attribute with a value of "Flurry".

The reason for adding this property is, after changing the type name, the binding no longer will be able to find the underlying Objective-C type. Usually the binding will use the default name if none is provided, the C# class name. After changing it, it no longer reflected the Objective-C type name, hence the new property.

Managing the Structures and Enumerations (StructsAndEnums.cs)

The last thing to fix, in the generated code, is the enum.

This is simple to do, just remove the strange attribute-like bit: [unmapped: unexposed: Elaborated].

One of the nice things of Objective Sharpie is that it removes the enum prefixes and just uses the relevant bits. For example the original item was FlurryLogLevelNone, but this is now just None.

The final enum looks like this after it has been moved to StructsAndEnums.cs:

    public enum FlurryLogLevel {
        None = 0,
        CriticalOnly,
        Debug,
        All
    }

So far, all our generated code has been moved into either, ApiDefinitions.cs (the class), or StructsAndEnums.cs (the enum). We are still not complete yet, but we are nearly there.

Additional Binding Code (Extras.cs)

Once we have the basic binding done, we can always extend what the native library provided with extra features. This is done by adding new source files to the project.

For example, if for some reason you need to add any extra bindings to the library, say to access a private member or even just to make the new API cleaner and more .NET-like.

For example you could do something like this:

    public partial class FlurryAgent : NSObject {
        public static void LogTimedEvent (string eventName, Action action) {
            try {
                FlurryAgent.LogEvent (eventName, true);
                action(); // do our task
            } catch {
                FlurryAgent.EndTimedEvent (eventName, null);
                throw;
            }
        }
    }

What is happening here is that I am adding a new method to the final .NET assembly. This method can make use of the methods in the API definition interface. In this particular example, I am adding a method that can take an Actionand make sure that we fire a ‘starting’ and then an ‘ending’ event to the Flurry servers. This is a new bit of functionality that can be baked right into the binding assembly.

Working with the Native Library (.a)

This step is actually quite easy, just add the native library (.a) to the project, and you are almost done.

When you add the native library to the project, Xamarin Studio will create a new .linkwith.cs file that matches the library name. For example with Flurry, I added the libFlurry_5.2.0.a library to my project and it generated a libFlurry_5.2.0.linkwith.cs.

This new file is the last bit that needs to be done. It is for the linker when using this library in an iOS app. It usually will contain only a single line, a single [LinkWith] attribute. This attribute allows you to specify what targets this library can be used with, what extra iOS frameworks are needed, etc:

    [assembly: LinkWith (
        "libFlurry_5.2.0.a", 
        LinkTarget.Simulator | LinkTarget.ArmV6 | LinkTarget.ArmV7 | LinkTarget.ArmV7s, 
        ForceLoad = true)]

This is the default line, split for readability, and usually it is all that is needed. What this does is say that the linker must use the libFlurry_5.2.0.a native library as well as this library can be used on the Simulator and all the devices. The ForceLoad is used by the Xamarin.iOS linker, and specifies a linker flag. According to the documentation, this should always be true for now.

But just before we finish up, we need to add any required frameworks. Without this, there will be strange happenings…but different depending the configuration.

If building for Debug, the app will launch, but nothing will happen at all. The methods can be called and everything, but no actions will take place.

If building for Release, the linker will throw an error:

Error MT5211: Native linking failed, undefined Objective-C class: _OBJC_CLASS_\$_Flurry.
If ‘_OBJC_CLASS_\$_Flurry’ is a protocol from a third-party binding, please check that it has the [Protocol] attribute in its api definition file, otherwise verify that all the necessary frameworks have been referenced and native libraries are properly linked in.

This error is giving us lots of information for @protocol, but as we don’t have any in our project (recall the @interface), we can safely ignore the first part of the second message and focus on the ‘frameworks’ part. According to the Flurry documentation, the Security.framework is required and the SystemConfiguration.framework is optional, but recommended.

So, I added both frameworks, using the Frameworksproperty:

    [assembly: LinkWith (
        "libFlurry_5.2.0.a",
        LinkTarget.Simulator | LinkTarget.ArmV6 | LinkTarget.ArmV7 | LinkTarget.ArmV7s, 
        ForceLoad = true, 
        Frameworks = "SystemConfiguration Security")]

As shown here, the frameworks are space-separated and do not have the .framework extensions.

Finishing Up

So far we have defined our API, added any additional logic or types, added the native library, set up the linker and specified the frameworks. This is all that is needed, so our library should build fine now and we should be able to use it in an Xamarin.iOS app:

    // the methods
    FlurryAgent.StartSession("PQSZJRK4B5BW8Q7YQQXF");

    // the properties that we changed back into methods
    FlurryAgent.GetFlurryAgentVersion ();

    // the extra method that we added
    FlurryAgent.LogTimedEvent ("started", () => {
        // ...
    });

Under the Hood

One thing to know is that the iOS binding project is actually not really compiled directly, but are a series of stages. Each file actually has a different build action.

The first stage to building the binding is to build a reference assembly with the files:

  • ApiDefinition.cs (with build action ObjcBindingApiDefinition)
  • StructsAndEnums.cs (with build action ObjcBindingCoreSource)

Next, this assembly is then reflected to generate the actual binding code. This generated code is then compiled with the rest of the files:

  • Extras.cs (with build action Compile)
  • StructsAndEnums.cs (again with build action ObjcBindingCoreSource)
  • libFlurry_5.2.0.linkwith.cs (with build action Compile)
  • libFlurry_5.2.0.a (with build action ObjcBindingNativeLibrary but is actually just a resource)

An example of the generated code in the second stage, the interface member void StartSession(string) is actually used to generate a big block of code:

    [Export ("startSession:")]
    [CompilerGenerated]
    public static void StartSession (string apiKey)
    {
        if (apiKey == null)
            throw new ArgumentNullException ("apiKey");
        var nsapiKey = NSString.CreateNative (apiKey);

        MonoTouch.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr (class_ptr, selStartSession_Handle, nsapiKey);
        NSString.ReleaseNative (nsapiKey);
    }

This is all the magic that happens under the hood to redirect values from the managed .NET to the underlying native library.