Uncategorized

Adding Parse to your Xamarin.Forms solution

I’ve recently been developing a Xamarin.Forms app which required a cloud service for data persistence and syncing across multiple devices and platforms. Normally when I’m developing Xamarin.Forms apps, it tends to be because I’m either writing a proof of concept or a tech demo. Both these types of projects focus of speed of development and code reuse rather than crafting delightful user experiences (it’s 100% possible to create delightful experiences in forms, its just not the primary objective of a Xamarin.Forms app in most situations).

The app I’m developing requires both user signup and the ability of the user to sign in, which is where the Parse .NET client API shines. Although Parse may be one of the more unknown cloud service providers (especially in .NET circles), it’s my favourite for a number of reasons. It’s incredibly easy to get started with, the API is concise, and the documentation is fantastic. Not to mention a generous free plan makes it a no brainer for apps I want to deploy quickly, while being unsure how much traffic they’ll bring. My only complaint when using Parse is the lack of PCL for Xamarin.Forms. I have spoken with Parse about this and they assure me this issue will be resolved.

Adding Parse to your Forms app

Because of the PCL issue for Xamarin.Forms, you’re going to need to select a Shared Code solution, rather than a PCL backed solution. Once you’ve done this, you’ll need to add the Parse Nuget package to the individual platform projects. This means, firing up the package manager and adding Parse to the iOS, Android, and Windows Phone projects.

Initialising Parse

Before getting started with Parse, you’re going to need to ensure it’s initialised. I tend to create a class called Keys in my forms solution, which is where I store all the keys to services such as Parse and Xamarin.Insights. Below is an example keys class which you can reuse in your Xamarin.Forms apps.

//Keys.cs
public class Keys
{
    public static readonly string XamarinInsightsKey = "0000";

    public static readonly string ParseAppKey = "0000";
    public static readonly string ParseDotNetKey = "0000";
}

You can then call the ParseClient.Initialize API.

public App()
{
    ParseClient.Initialize(Helpers.Keys.ParseAppKey,   Helpers.Keys.ParseDotNetKey);

    // The root page of your application
    MainPage = new ContentPage{BackgroundColor = Color.Red};
}

Signing up a user

Now that Parse is ready to use, lets go ahead and create a new user. The API for creating a user couldn’t be any simpler, it’s one of the reasons why I’ve fallen in love with using Parse.

private async Task ExecuteSignUpUserCommand ()
{
    if (IsBusy)
        return;
    IsBusy = true;

    try
    {
        var user = new ParseUser()
        {
            Username = username,
            Password = password,
            Email = email
        };

        user["firstName"] = firstName;
        user["lastName"] = lastName;

        var connected = CrossConnectivity.Current.IsConnected;
        if (connected)
        {
            UserDialogs.Instance.ShowLoading ("Creating Account");

            //The code that actually signs a user up!
            await user.SignUpAsync();

            //More UI stuff..
            UserDialogs.Instance.HideLoading ();
            await NavigateToMainUI ();
        } else {
            UserDialogs.Instance.ShowError ("No Internet Connection");
        }
    }
    catch (Exception ex)
    {
        UserDialogs.Instance.ShowError(ex.Message, 3);
        Xamarin.Insights.Report (ex);
    }
    IsBusy = false;
}

Lets save some data

The not so pretty way
We have two options for saving data with Parse. We can use the dictionary-initialization syntax or we can subclass from ParseObject. I much prefer to subclass the ParseObject as this allows for type-safety and IntelliSense (which are two of the many reasons I use C#). Below we will save an object to Parse using both approaches.

Dictionary-Initialization

var sampleData = new ParseObject("Planet");
sampleData["name"] = "Earth";
sampleData["distanceFromSun"] = 100;
await sampleData.SaveAsync();

Subclassing ParseObject

// Planet.cs
using Parse;

[ParseClassName("Planet")]
public class Planet : ParseObject
{
    [ParseFieldName("name")]
    public string Name
    {
        get { return GetProperty(); }
        set { SetProperty(value); }
    }

    [ParseFieldName("distanceFromSun")]
    public int DistanceFromSun
    {
        get { return GetProperty(); }
        set { SetProperty(value); }
    }
}

Registering Subclasses objects

You’ll need to call ParseObject.RegisterSubclass() in your apps initialisation before calling ParseClient.Initialize(). If you don’t don’t do this, your app will crash!

ParseObject.RegisterSubclass();

The final initialisation method

public App()
{
    ParseObject.RegisterSubclass();
    ParseClient.Initialize(Helpers.Keys.ParseAppKey,         Helpers.Keys.ParseDotNetKey);

    // The root page of your application
    MainPage = new YourAmazingContentPage();
}

Using our subclasses ParseObject

var planet = new Models.Planet()
{
    Name = "Mars",
    DistanceFromSun = 227900000
};
await planet.SaveAsync();

Conclusion

You can download a sample project from GitHub which demonstrates how to sign up, sign in, save and most importantly, retrieve data.

If you’ve any questions then please feel free to comment or get in touch via Twitter

2 thoughts on “Adding Parse to your Xamarin.Forms solution”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s