Xamarin Forms Walkthrough UI

Here’s a walkthrough interface for use in Xamarin Forms apps. With a some work it’s easy to move beyond the default layouts and navigations patterns and make something a bit more exciting.

The video shows it in action. You can switch between pages using the buttons or by swiping. The content for the walkthrough control is defined by a list of views; it can be anything you want. The page indicators update every time you change a page.

The view provides properties to adjust the background color, back and next text, the image used for the progress indicators, and the amount of padding used for the control area.

Implementation

If you want to know how it works you can dive into the source here. In this post I’ll just run through the key parts.

The content view XAML is just a stack layout which contains two grids. The top grid expands to fill the screen and contains the child content pages when they are added. The bottom grid contains the controls to switch the page. There’s also a gesture recognizer on the whole view to pick up swipe gestures.

The key bit of code for the content view is the SetContent method. This takes a list of views and adds them into the grid. It offsets the children at intervals of a page width – so initially they extend horizontally out to right of the screen. When the page changes it animates each of the children to shift them right or left. The other thing it does is expose the configurable options.

I’ve split a lot of the logic for which pages andbuttons are displayed out into the WalkthroughController class for a couple of reasons. Firstly it’s easier to write unit tests, and secondly it nicely separates the processing and interaction logic.

That’s pretty much it – a bit of XAML and a couple of simple classes produce a nice, configurable interface 🙂

 

Xamarin Forms Walkthrough UI

Xamarin Forms Repeater View

Here’s a quick demo and explanation of a repeater view I made for Xamarin Forms. It simply repeats a set of controls for a collection of items that it’s bound to. A ListView does this too but isn’t always what I want. It’s surprising something like this isn’t included in the framework but making your own is fairly simple.

Source code and a sample application are available here.

Here’s what it looks like in action. In this simple demo each item is represented by a Frame that contains a label and a button.

Screen Shot 2017-05-14 at 07.17.50
10 internet points if you can identify what’s in the background.

Let’s look at some key points in the code. The view is based on StackLayout which will take care of positioning the items.

public class Repeater : StackLayout

There are a couple of bindable properties – ItemTemplate for the item layout and ItemsSource which provides the items. Note that ItemsSource hooks an action to PropertyChanging – I’ll come back to this later on.

public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create("ItemTemplate", typeof(DataTemplate), typeof(Repeater), null);
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(Repeater), propertyChanging: ItemsSourceChanging);

Usage in XAML is similar to ListView, with an ItemTemplate, DataTemplate, and ViewCell.

<ui:Repeater x:Name="MainRepeater">
    <ui:Repeater.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Frame HasShadow="True" Margin="10">
                    <StackLayout Orientation="Horizontal">
                        <Label Text="{Binding Title}" HorizontalOptions="StartAndExpand" VerticalTextAlignment="Center"/>
                        <Button Text="Select" />
                    </StackLayout>
                </Frame>
            </ViewCell>
        </DataTemplate>
    </ui:Repeater.ItemTemplate>
</ui:Repeater>

I populate the display items whenever the related properties change, or when the binding context changes.

protected override void OnPropertyChanged(string propertyName = null)
{
    base.OnPropertyChanged(propertyName);

    if (propertyName == ItemTemplateProperty.PropertyName || propertyName == ItemsSourceProperty.PropertyName)
    {
        this.Populate();
    }
}

protected override void OnBindingContextChanged()
{
    base.OnBindingContextChanged();
    this.Populate();
}

The Populate method clears out the layout, then populates the template for each item and adds it in.

public void Populate()
{
    if (this.ItemsSource != null)
    {
        this.Children.Clear();

        foreach (var item in this.ItemsSource)
        {
            var content = this.ItemTemplate.CreateContent();
            var viewCell = content as ViewCell;

            if (viewCell != null)
            {
                this.Children.Add(viewCell.View);
                viewCell.BindingContext = item;
            }
        }
    }
}

If we just wanted to bind to an IEnumerable we wouldn’t need anything more. However when binding to an ObservableCollection the list wouldn’t update when items are added or removed. ObservableCollection fires OnCollectionChanged, not OnPropertyChanged, when the list is updated. This is where the ItemsSourceChanging method we hooked up in the binding is used.

private static void ItemsSourceChanging(BindableObject bindable, object oldValue, object newValue)
{
    if (oldValue != null && oldValue is INotifyCollectionChanged)
    {
        ((INotifyCollectionChanged)oldValue).CollectionChanged -= ((Repeater)bindable).OnCollectionChanged;
    }

    if (newValue != null && newValue is INotifyCollectionChanged)
    {
        ((INotifyCollectionChanged)newValue).CollectionChanged += ((Repeater)bindable).OnCollectionChanged;
    }
}

private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
	Populate();
}

When the ItemsSource is changing we check to see if it implements INotifyCollectionChanged, if so we subscribe to the OnCollectionChanged event and populate the list when it fires. We also need to make sure we unsubscribe if the items source changes.

So that’s it, a simple alternative to ListView for repeating a set of controls.

Xamarin Forms Repeater View

macOs Folders Appear As Files

Here’s a weird macOS issue I’ve just run into while doing some cross platform development with Xamarin. If you have a folder which has a dot in it’s name it finder will sometimes think it’s a file. For me this was when the name ended in .workflow…

Screen Shot 2017-05-04 at 20.37.31
Looks like a file…
Screen Shot 2017-05-04 at 20.38.35
…but it’s really a folder

This happens when the element after the last dot is recognised as a file extension. After some head scratching I found an easy solution – right click on the folder and select ‘Show Package Contents’

Screen Shot 2017-05-04 at 20.42.06
‘Show Package Contents’
Screen Shot 2017-05-04 at 20.54.22
As if by magic some files appear!
macOs Folders Appear As Files

Xamarin Forms Flow Layout

Xamarin Forms is missing a flow layout control so I made one! It’s available here. It lays out child views from right to left, and moves on to a new row when it runs out of space.

Here’s a screenshot of a demo app…

Screen Shot 2017-03-22 at 20.45.36

This is the first layout I’ve made and I was surprised how easy it was. Layouts are written in the cross platform code; there isn’t a platform specific element.

To create a layout you create a new class that inherits from Layout…

public class FlowLayout : Layout<View>

The override the LayoutChildren and OnMeasure methods…

protected override void LayoutChildren(double x, double y, double width, double height)
{
    var layoutInfo = new LayoutInfo(Spacing);
    layoutInfo.ProcessLayout(Children, width);

    for (int i = 0; i < layoutInfo.Bounds.Count; i++)
    {
        if (!Children[i].IsVisible)
        {
            continue;
        }

        var bounds = layoutInfo.Bounds[i];
        bounds.Left += x;
        bounds.Top += y;

        LayoutChildIntoBoundingRegion(Children[i], bounds);
    }
}
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
    var layoutInfo = new LayoutInfo(Spacing);
    layoutInfo.ProcessLayout(Children, widthConstraint);
    return new SizeRequest(new Size(widthConstraint, layoutInfo.HeightRequest));
}

I chose to use another class – LayoutInfo – to handle the layout. This meant I was able to easily write unit tests. Trying to unit test the actual layout class is difficult as it needs the Xamarin Forms framework to work in the test environment.

 

Xamarin Forms Flow Layout

Xamarin Cross Platform Version Numbers

In this post I discuss a solution for creating a consistent version number across .net, Android, and iOS for Xamarin cross platform apps. I also list a couple of powershell scripts which help with setting the versions

The Problem

.net, Android, and iOS, all use different systems for versioning. When developing cross platform apps we consistency of numbering across the different platforms.

.net Version Numbers

.net Version numbers use a four part version number with the format <major version>.<minor version>.<build number>.<revision>

Often you’ll see version numbers with asterisks – 1.0.* or 1.0.. – When these are used the build number the build number increments every day and the revision number is random. .net version numbers are stored in the AssemblyInfo file for a project.

Android Version Numbers

Two numbers are used in Android versioning – the versionCode is an integer with higher numbers indicating more recent versions. It’s never shown to users. The versionName is a string which is displayed to users and can be anything you want. These numbers are stored in the AndroidManifest.xml file.

iOS Version Numbers

An iOS app has two version numbers which work together – A Version Number (CFBundleShotVersionString) and a Build Number (CFBundleVersion). The Version number identifies a release, and for each release the build number increments for each build that is submitted to the store. These numbers are stored in the Info.plist file.

‘Common’ Version Numbers

For Xamarin applications we want consistency of version numbers across the platform specific versions of an app, and it makes sense to use the .net version number as the ‘master’.

We can either use the automatic numbers as described above, or, if using TFS/VSTS use a number in a format such as 1.2.$(DayOfYear)$(Rev:.rr) and update the assemblyinfo

For example lets say the .net version number is 1.4.102.13.

This powershell script will update all the assemblyinfo files in a solution.

[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string] $version,
[Parameter(Mandatory=$true)]
[string] $path
)

Cls

Write-Output &quot;Version Assembly Infos&quot;
Write-Output &quot;Version: $version&quot;

$newVersion = &quot;[assembly: AssemblyVersion(&quot;&quot;$version&quot;&quot;)]&quot;
$newFileVersion = &quot;[assembly: AssemblyFileVersion(&quot;&quot;$version&quot;&quot;)]&quot;

$files = Get-ChildItem -Path $path -Filter &quot;AssemblyInfo.cs&quot; -Recurse

foreach($file in $files)
{
(Get-Content $file.FullName) `
-replace '\[assembly: AssemblyVersion\(&quot;(.*)&quot;\)\]', $newVersion `
-replace '\[assembly: AssemblyFileVersion\(&quot;(.*)&quot;\)\]', $newFileversion |
Out-File $file.FullName
}

For Android the versionName, which is just for display, can be set to the full four part version number from .net. The versionCode just needs to increase from the previous version. Here's a script which takes the global build number from TFS, but could be easily modified to increment the existing number.

With the example version number this would give us a versionName – 1.4.102.13 – and a versionCode which is unique incremented number.

[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string] $version,

[Parameter(Mandatory=$true)]
[string] $manifestPath
)

# Sets version in an Android manifest.
# The version name is set to the specified value.
# The version code is set to the build number from TFS.

Write-Output &quot;Setting Android Version&quot;
Write-Output &quot;Version: $version&quot;
Write-Output &quot;Manifest: $manifestPath&quot;

$xml = [xml](Get-Content $manifestPath)
$manifestNode = $xml.manifest

$versionCodeNew = $env:BUILD_BUILDID # This is the global build number from tfs - it increments with every build of every project.

$manifestNode.Attributes[&quot;android:versionCode&quot;].Value = $versionCodeNew
$manifestNode.Attributes[&quot;android:versionName&quot;].Value = $version

$xml.Save($manifestPath)

Write-Output &quot;Manifest Updated&quot;

For iOS we can split the four part version number. The first three parts can be used for the version number and the last part can be used for the build number. Here's a script for that. From the example version number this gives us a version number – 1.4.102 – and a build number – 13.

[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string] $version,

[Parameter(Mandatory=$true)]
[string] $infoPath
)

cls

Write-Output &quot;Version: $version&quot;
Write-Output &quot;InfoPath: $infoPath&quot;

$elements = $version.Split(&quot;.&quot;)
$major = $elements[0]
$minor = $elements[1]
$revision = $elements[2]
$build = $elements[3]

$iosVersion = &quot;$major.$minor.$revision&quot;

$xml = [xml](Get-Content $infoPath)

$buildNode = $xml.SelectSingleNode(&quot;.//key[text()=&quot;&quot;CFBundleVersion&quot;&quot;]&quot;)
$buildNode.NextSibling.InnerText = $build

$versionNode = $xml.SelectSingleNode(&quot;.//key[text()=&quot;&quot;CFBundleShortVersionString&quot;&quot;]&quot;)
$versionNode.NextSibling.InnerText = $iosVersion

$xml.Save($infoPath)
Xamarin Cross Platform Version Numbers

TFS Mac Build Agent – The type initializer for ‘System.Net.Http.CurlHandler’ threw an exception. Failed to connect.

I’ve just spent a couple of hours on this error which occurs when setting up a Mac TFS build agent on OSX El Capitan.

There are a lot of solutions out there but the one that worked for me came from the [.net core setup instructions] (https://www.microsoft.com/net/core#macos).

Simply run the following commands…

brew update
brew install openssl
mkdir -p /usr/local/lib
ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/
ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/

… then install the agent again…

~/myagent$ ./config.sh

Hopefully this will save you some time and frustration 🙂

TFS Mac Build Agent – The type initializer for ‘System.Net.Http.CurlHandler’ threw an exception. Failed to connect.

Xamarin Forms – Xaml Resource Dictionaries

This post shows how to create a standalone XAML resource dictionary for use in Xamarin Forms. Normally resource dictionaries live in the xaml for an Application or a VisualElement, putting them in a standalone class makes it easy to share them across applications.

To create the dictionary:

  • Add a new xaml page to your project.
  • In xaml change root element to ResourceDictionary from Page.
  • In code change the class so it doesn’t inherit from Page.

Here are examples of the xaml and code files:

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Microlise.Mobile.UI.Demo.OtherStyle">
<Style x:Key="ButtonPrimary" TargetType="Button">
<Setter Property="BackgroundColor" Value="#9D6381" />
<Setter Property="TextColor" Value="#242728" />
<Setter Property="FontAttributes" Value="Bold" />
</Style>
</ResourceDictionary>
using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Microlise.Mobile.UI.Demo
{
public partial class OtherStyle
{
public OtherStyle()
{
this.InitializeComponent();
}
}
}
Xamarin Forms – Xaml Resource Dictionaries