In a few of our previous articles, we used Sitecore Mobile SDK (WebAPI) for Xamarin to create apps that use and serve content that is managed by Sitecore.

Sitecore Mobile SDK (WebAPI) for Xamarin relies on the Sitecore Item Web API, which is the legacy framework. The Sitecore Item Web API provides access to a REST-style web service that enables external applications to retrieve and manipulate Sitecore content via JSON output.

Now we are going to use Sitecore Mobile SDK (SSC) for Xamarin, which relies on the Sitecore.Services.Client (SSC).

I uploaded the complete code the Github JoaoNeto87/SitecoreSSCAndroid repository.

What is Sitecore Sitecore.Services.Client (SSC)

Sitecore.Services.Client is found in Sitecore 7.5 (or later).

Sitecore.Services.Client provides a service layer on both the server and the client side of Sitecore applications that you use to develop data-driven applications. Sitecore.Services.Client uses the ASP.NET Web API as a foundation.

Sitecore.Services.Client provides two services:

●     ItemService: this service gives you access to regular Sitecore items.

●     EntityService: this service gives you access to business objects that you define.

Setup Sitecore Sitecore.Services.Client (SSC)

By default Sitecore Sitecore.Services.Client uses the ServicesLocalOnlyPolicy policy that denies access to all Entity and ItemServices from requests originating from remote clients.

We are going to use ServicesOnPolicy. This policy allows access to all Entity and ItemServices from requests originating from remote clients.

You configure security policy with the Sitecore.Services.SecurityPolicy setting in the \Website\App_Config\Include\Sitecore.Services.Client.config file.

<!--
<setting name="Sitecore.Services.SecurityPolicy" value="Sitecore.Services.Infrastructure.Web.Http.Security.ServicesLocalOnlyPolicy, Sitecore.Services.Infrastructure" />
-->

<setting name="Sitecore.Services.SecurityPolicy" value="Sitecore.Services.Infrastructure.Web.Http.Security.ServicesOnPolicy, Sitecore.Services.Infrastructure" /> 

Enable SSL

In order to authenticate the user against Sitecore, Sitecore Mobile SDK (SSC) for Xamarin makes a call to the /sitecore/api/ssc/auth/login endpoint, which is only available through HTTPS POST request.

In the article Tip/Trick: Enabling SSL on IIS 7.0 Using Self-Signed Certificates, Scott Guthrie teaches us how to quickly enable SSL using Self Signed Certificates in our local machines.

Having a Sitecore site already installed, I only had to do the following:

1. Create a new Self Signed Certificate

Click the root machine node in the left-hand tree-view explorer, and then select the "Server Certificates" icon in the feature pane on the right:

Sitecore Mobile SDK SSC Xamarin 1

Click the "Create Self-Signed Certificate" link on the right-hand side of the admin tool:

Sitecore Mobile SDK SSC Xamarin 2

Enter a name to use for the certificate (for example: "test") and hit OK.  IIS7 will then automatically create a new self-signed crypto certificate for you and will register it on the machine.

2. Enable HTTPS Bindings for your Sitecore site

To SSL enable the web-site we created earlier, select the web-site node in the left-hand tree-view, and the click the "Bindings" link in its "actions" pane on the right-hand side of the screen:

Sitecore Mobile SDK SSC Xamarin 3

To enable SSL for the site, click the "Add" button. This will bring up an "add binding" dialog that we can use to add HTTPS protocol support.  We can select the self-signed certificate we created earlier from the SSL certificate drop-down list in the dialog, and in doing so indicate that we want to use that certificate when encrypting content over SSL:

Sitecore Mobile SDK SSC Xamarin 4

Setup a Visual Studio solution

Create a new Blank App (Android) by File > New > Project > Templates > Visual C# > Andorid > Blank App (Android). Name it "SitecoreSSC.Droid".

Install Sitecore Mobile SDK (SSC) for Xamarin nuget package

Install Sitecore Mobile SDK (SSC) for Xamarin nuget package. You can use either the Nuget Package Manager (Tools > Nuget Package Manager > Manage Nuget Packages for Solution...) or install it through Package Manager Console (Tools > Nuget Package Manager > Package Manager Console):

PM> Install-Package Sitecore.MobileSDK.SSC

Please, refer to Sitecore Mobile SDK (SSC) for Xamarin for more information.

Add Internet permission to your Android Manifest file

Add Internet permission to your Android Manifest by right-clicking your project in the Solution Explorer > Properties (or click on your project in the Solution Explorer and ALT + ENTER).

Now open the Android Manifest tab and in the Required permissions section select the option INTERNET. Save and rebuild your Solution.

Sitecore Mobile SDK SSC Xamarin 5

Now, let’s implement the code

In the MainActivity class add the following code:

using Android.App;
using Android.OS;
using Sitecore.MobileSDK.API;
using Sitecore.MobileSDK.API.Items;
using Sitecore.MobileSDK.PasswordProvider;

namespace SitecoreSSC.Droid
{
    [Activity(Label = "SitecoreSSC.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {

            SetHttpsHandler();
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);
            GetSitecoreContent();

        }


        private void SetHttpsHandler()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) =>
            {
                return true;
            };
        }

        private async void GetSitecoreContent()
        {

            string instanceUrl = "http://sitecoredev.local.nlc";

            using (var credentials = new ScUnsecuredCredentialsProvider("admin", "b", "sitecore"))

            using (var session =
                   SitecoreSSCSessionBuilder.AuthenticatedSessionWithHost(instanceUrl)
                   .Credentials(credentials)
                   .DefaultDatabase("web")
                   .DefaultLanguage("en")
                   .MediaLibraryRoot("/sitecore/media library")
                   .MediaPrefix("~/media/")
                   .DefaultMediaResourceExtension("ashx")
                   .BuildReadonlySession())
            {

                var request = ItemSSCRequestBuilder.ReadItemsRequestWithPath("/sitecore/content/home").Build();
                ScItemsResponse items = await session.ReadItemAsync(request);
                string fieldContent = items[0]["Text"].RawValue;
                string itemName = "Home Item Text";

                var dialogBuilder = new AlertDialog.Builder(this);
                dialogBuilder.SetTitle(itemName);
                dialogBuilder.SetMessage(fieldContent);
                dialogBuilder.Create().Show();

            }

        }

    }
}

This code was taken from Use the Mobile SDK to build an Android application in Xamarin Studio.

(Android only) If the server is using HTTPS, you need to add a handler for the callback handler:

System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) =>
{
     return true;
};

Now if you run your project you will get the following error: Sitecore.MobileSDK.API.Exceptions.RsaHandshakeException: [Sitecore Mobile SDK] Public key not received properly.

Basically, what is happening here is that your Android Emulator (assuming that you are using one) cannot reach to your Sitecore instance installed in your local IIS (in my case http://sitecoredev.local.nlc). What should you do?

You have to add your Sitecore instance to the hosts file of the Android emulator pointing to your local machine.

Add your Sitecore instance url to the hosts file of the Android emulator

I found an interesting article written by Brad Curtis talking about it. The trickiest part for me was to find out that I had to run the Android Debug Bridge (adb.exe) as Administrator and use my local IP address rather than 10. 0. 2. 2 as mentioned by Brad Curtis in his article.

Now, let's add your Sitecore instance to the hosts file of the Android emulator. Usually you find the Android Debug Bridge in C:\Program Files (x86)\Android\android-sdk\platform-tools\adb.exe. Open cmd.exe (run it as Administrator).

CD C:\Program Files (x86)\Android\android-sdk\platform-tools
adb remount

You should see the "remount succeeded" message. If you get a result different than that, make sure you have an Android emulator running.

adb pull /system/etc/hosts c:\temp\hosts

You should see the "[100%] /system/etc/hosts" message. If you get a result different than that, make sure you have the folder C:\temp with the proper permissions in your local machine.

Now in the file C:\temp\hosts add the following entry (noticed that I am using my IP address, you have to use yours):

Sitecore Mobile SDK SSC Xamarin 6

Another tricky part here is that you need to add an extra line after the last entry. Otherwise the Emulator will not recognize it.

Now push the hosts file to your Android emulator.

adb push c:\temp\hosts /system/etc

You should see the "[100%] /system/etc/hosts" message.

Restart the emulator and browse to your entered hostname in the Android emulator browser.

Now run your code in the Visual Studio. You should see the following:

SitecoreMobile_SDKSSC_7

comments powered by Disqus