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.

[sourcecode language=”csharp”]
//Keys.cs
public class Keys
{
public static readonly string XamarinInsightsKey = “0000”;

public static readonly string ParseAppKey = “0000”;
public static readonly string ParseDotNetKey = “0000”;
}
[/sourcecode]

You can then call the ParseClient.Initialize API.

[sourcecode language=”csharp”]
public App()
{
ParseClient.Initialize(Helpers.Keys.ParseAppKey,   Helpers.Keys.ParseDotNetKey);

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

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.

[sourcecode language=”csharp”]
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;
}

[/sourcecode]

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

[sourcecode language=”csharp”]
var sampleData = new ParseObject(“Planet”);
sampleData[“name”] = “Earth”;
sampleData[“distanceFromSun”] = 100;
await sampleData.SaveAsync();
[/sourcecode]
Subclassing ParseObject
[sourcecode language=”csharp”]
// 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); }
}
}
[/sourcecode]

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!
[sourcecode language=”csharp”]
ParseObject.RegisterSubclass();
[/sourcecode]

The final initialisation method
[sourcecode language=”csharp”]
public App()
{
ParseObject.RegisterSubclass();
ParseClient.Initialize(Helpers.Keys.ParseAppKey,         Helpers.Keys.ParseDotNetKey);

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

Using our subclasses ParseObject
[sourcecode language=”csharp”]
var planet = new Models.Planet()
{
Name = “Mars”,
DistanceFromSun = 227900000
};
await planet.SaveAsync();
[/sourcecode]

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.