Insights

Sitecore & Xamarin for Mobile Apps

Sitecore Developer
Valtech

November 20, 2017

A huge moment for the internet occurred in October 2016, StatCounter reported for the first time that more users around the world accessed the internet through their mobile devices than their desktop computers. No one was surprised. We all knew it and the respective wave of demand for mobile app experiences that go beyond the responsive site was coming. As developers and architects, we need to be prepared to deliver on the promise of the mobile web on a Sitecore technology stack. This article explains the technical foundations you need to understand to get started and explores some of the possibilities that Sitecore, the Sitecore mobile SDK and Xamarin bring to the table.

Xamarin and the Sitecore Mobile SDK

Before we get into the details I wanted to provide a high-level overview of what Xamarin is and where it came from and what the Sitecore mobile SDK adds to your projects.

Xamarin was founded in 2011 by the engineers who created Mono & Mono for Android, so you can’t really begin a discussion about Xamarin without first mentioning Mono. The main purpose of Mono is to be able to run .NET applications cross-platform, Android, Linux, macOS, PlayStation and the list goes on.

The remit of Xamarin therefore is to provide the tools to write cross-platform mobile applications with native user interfaces. That last part is important, each mobile platform (Android, iOS, BlackBerry OS, Windows Phone) has very specific UI paradigms that should be respected to ensure that your mobile apps “feel right” for each platform, this especially manifests itself when we talk about things such as navigation patterns.

And it’s doing well! Xamarin is used by 1.4 million developers in 120 countries, was acquired by Microsoft in 2016 and the good news is it’s now free. To summarise, as a technology stack you get:

  • C#
  • Mono.Net
  • A compiler that produces a native application or an integrated .NET runtime)
  • IDE tools

Sitecore’s Mobile SDK is a portable class library (managed assembly that works on more than one .NET framework platform), which essentially provides a high-level abstraction for Sitecore items by wrapping around the Sitecore WebAPI and Sitecore Services Client (SSC) to perform CRUD operations.

Of the two flavours (WebAPI and SSC), SSC is probably the better choice if you are using Sitecore 8.1+ as it provides an improved authentication model and better support for extensibility when using the EntityService for custom business object modelling and custom WebAPI controllers that interface with repositories designed to work with your business domain.

Local Environment Setup

So now that we understand the background and use cases of Xamarin and the Sitecore Mobile SDK the next step to getting started is to setup a local development environment and for this example we will be using:

  • Visual Studio 2017 with Xamarin components installed (can be done during or after Visual Studio installation)
  • Android
  • Device emulation
  • Sitecore 8.2 Update 5 (many other versions of Sitecore are supported)

The Solution

The first thing we need to do is create a new project, which will be a C#, Android Blank App:

Because we are working with the Sitecore Mobile SDK which communicates with Sitecore over a network the first thing to do once the project has been created is to add permission to access network resources to the android manifest via the project properties and of course install the SDK using Nuget (Sitecore.MobileSDK.SSC). It is also possible to include the source code of the SDK in your solution for reference and debugging purposes by cloning the repository from GitHub:

https://github.com/Sitecore/sitecore-mobile-pcl-sdk

Device Emulation

To setup device emulation you need to download and install the Visual Studio emulator for Android. The emulator comes with pre-installed devices but you can also download additional devices that match the characteristics of the devices you wish to target in terms of the Android API version used and device properties such as screen size:

From here you can launch the device which will run on HyperV and at that point the device will appear in Visual Studio as an option in the debug drop down, selecting this option will build and launch your application onto the device which you can then interact with and debug in the same way as you would with a regular .NET application. Some other points to mention are:

  • Visual Studio does come with built-in emulators but the emulators described above that run on HyperV will offer much better performance (as much as 10x the performance)
  • You can also connect a physical device to your machine via USB but you must enable developer mode on the device first
  • Your Android project properties specify a minimum Android version supported. If this version is higher than the version installed on the emulated device it will not display as an option in the debug drop down

Common device emulation issues and steps to take to resolve them:

  1. No internet access on the device
    • Ensure that the device in HyperV has an external network adapter in the hardware list that appears after the internal adapter (you may need to add an external switch using the virtual switch manager)
  2. The device cannot see your local Sitecore instance
    • Modify the hosts file on the device using adb
      • C:\Program files (x86)\Android\android-sdk\platform-tools
      • adb remount (takes the device out of read only mode)
      • adb pull /system/etc/host C:\temp\hosts
      • Modify locally
      • adb push C:\temp\hosts /system/etc/
      • Restart device
    • Use the IP 10.0.2.2, which is a loopback to 127.0.0.1 on the host machine or the IP listed as the first desktop adapter in the device settings > network window on the running device within Visual Studio emulator for Android
    • Check your local firewall settings
  3. The emulator is running, debugging starts and then immediately stops (most common in Windows 10)
    • Go to HyperV > Device Settings > Processor > Compatibility and check “Migrate to a physical computer with a different processor version”

Sitecore Services Client Configuration

Finally we need to configure Sitecore Services Client on our local Sitecore instance. The emulated device is considered an external device so we need to modify Sitecore.Services.Client.config to change the setting Sitecore.Services.SecurityPolicy from its default of “local only” to “on”.

Lastly authentication for SSC must happen securely so you need to add a self-signed certificate in IIS and add a https binding to your Sitecore instance (selecting the previously created certificate).

Working with the Sitecore Mobile SDK

The following code samples will give you a general sense of how to read items from Sitecore and create new items in Sitecore from your mobile application, as is always the case there are many APIs available in the SDK which cannot all be covered here but the aim is to convey the general principles and after that I would encourage you to use the documentation on https://doc.sitecore.net/.

Authentication

Before we can do anything, we must authenticate with SSC, we do this by enclosing our API calls in the following using statement:

using (var credentials = new ScUnsecuredCredentialsProvider("user", "password", "domain"))

{

}

All permissions in terms of being able to read and create items based on the credentials used are handled by standard Sitecore security.

It can be assumed that all code samples that follow are wrapped in this using statement.

Sessions

All requests to SSC are performed within the context of a session. The session amongst other things specifies which Sitecore instance we want to send requests to, which credentials to use, some default parameters for the session (such as the database to use) and whether this is a read only session or not.

using (var session =

SitecoreSSCSessionBuilder.AuthenticatedSessionWithHost("host")

.Credentials(credentials)

.DefaultDatabase("web")

.DefaultLanguage("en")

.MediaLibraryRoot("/sitecore/media library")

.MediaPrefix("-/media")

.DefaultMediaResourceExtension(".ashx")

.BuildReadonlySession())

{

}

The default parameters can all be overridden at the request level, which we will move onto next. It can be assumed that all request code samples are wrapped in a session using statement.

Requests

Requests are where the action happens!

Read

In this example, we are reading the children of an item with a specific ID:

var builder = ItemSSCRequestBuilder

.ReadChildrenRequestWithId("{B2803DA4-6341-430B-997F-D5FAC33B3328}");

var response = await session.ReadChildrenAsync(builder.Build());

if (response.ResultCount > 0)

{

}

You will notice that the call is asynchronous but there are synchronous equivalents available if that is needed. The response inherits from IEnumerable<ISitecoreItem> so we can enumerate over the response to work with the items returned and ISitecoreItem has a field indexer just like working with regular Sitecore items:

foreach (ISitecoreItem item in response.OrderBy(x => x.DisplayName))

{

var title = item["Title"].RawValue;

}

Items can be read in other ways for example returning items that are the result of a stored search query in Sitecore.

Create

In this example we are creating a new item under the home item with a specific template and name. In this case we are also overriding the default session database at the request level and then populating fields on the newly created item:

var builder = ItemSSCRequestBuilder

.CreateItemRequestWithParentPath("/sitecore/content/Home")

.ItemTemplateId("5354DEF3-81E1-4601-B159-E7C7B5A4E73B")

.ItemName("Sample")

.Database("master");

builder.AddFieldsRawValuesByNameToSet("Title", "Sample Title");

builder.AddFieldsRawValuesByNameToSet("Description", "Lorem ipsum.");

var response = await session.CreateItemAsync(builder.Build());

if (response.Created)

{

}

Summary

There are regional differences in the statistics of the growth of mobile vs. desktop, for example in the western world mobile is yet to overtake desktop but it’s a fair assumption to say the trend toward mobile is heading in an upward direction and with it the demand for multi-platform mobile experiences is going to increase.

Xamarin and the Sitecore Mobile SDK are an excellent pathway or entry point to delivering on the promise of mobile and cross-channel content governance. But of course, it’s not the only way. You may be thinking, I am a developer or I have a team of developers who are experienced and quite comfortable building native mobile applications so why do I need Xamarin and that is a fair question. The point is the Sitecore Mobile SDK is a wrapper to Sitecore’s WebAPI or SSC, which are, if we want to simplify, secured web services, you can absolutely write your own client within your current technology stack to work with and push content to Sitecore. If on the other hand you are already working with Xamarin or you want to develop a team of cross-functional developers who are looking for an accelerated / low barrier to entry path into mobile app development then Xamarin and the Sitecore Mobile SDK can save you a lot of time, which allows you to focus on the task of building excellent mobile experiences in a way that does not feel foreign to .NET web application developers.

Finally, however you approach your mobile app development, if Sitecore is in your technology stack it should absolutely be your content and your behavioural system of record for web and mobile channels. The first part is easy, the content and the governance processes that surround it. The second part has traditionally been difficult to achieve because of limitations in the architecture of xDB, but now, with the introduction of Sitecore 9 and xConnect at Sitecore Symposium the obstacles to pushing mobile analytics into xDB and querying xDB from mobile have been removed, which is a very exciting prospect.

Meet The Challenges Of Today's Digital Economy

Ready to take that first step and rise to your digital potential? Contact Valtech today.
Talk to us