Implementing a Xamarin solution with Couchbase Mobile is the perfect combination in creating a cross-platform mobile application in C# that has local persistence. This allows your content and data to not be ephemeral but better yet, your mobile application is not dependent on a network connection at all times. In this blog we will explore how to get started with Xamarin and begin to implement the Couchbase Lite components from the Couchbase Mobile stack to create a storage layer.
New Xamarin Solution
Xamarin allows you to have the write once and run anywhere approach where it has a Native User Interface with Native performance. With the Xamarin Couchbase Lite NuGet package, you are able to share code across platforms using the C# and .NET Framework with full API support. Upon downloading and installing the iOS and Android components of Xamarin; when you open up Xamarin Studio, you will be presented with the Developer Center materials and some example solutions on the right hand side. You can try those at your leisure but we will be instead creating a new project and inserting Couchbase Mobile solution. Click ‘New Solution’
You will now be presented with a Xamarin Solution page. For this blog we will focus on creating an Android Application and to do that we will..
- Choose ‘Android’ in the C# dropdown and then ‘Android Application’ as our project.
- Provide a name for your project like below where the name is ‘CouchbaseMobile_Xamarin_App’
- Click ‘OK’
Add Couchbase NuGet Package
Now you have an empty Android Application project and we will be adding Couchbase Mobile as our next step. Xamarin now has first class support for NuGet which is built in and fully integrated. NuGet is a package management system for .NET that simplifies the process of using third party libraries within your mobile application such as Couchbase Lite. We will now download the latest Couchbase Lite.NET package from NuGet within Xamarin Studio.
- Right click on your project within the ‘Solution’ explorer section. I defined and created a project called ‘CouchbaseMobile_Xamarin_App’
- Select ‘Add’
- Select ‘Add Packages
With the ‘Add Packages’ dialog prompt now displayed like below, we will:
- Type in on the top right search field ‘Couchbase Lite’ and press enter to search for the package to install from within the Official NuGet Gallery
- Select the Couchbase Lite package from the list of return results
- Click on ‘Add Package’
Package Console & Folder
Xamarin Studio now will add the packages and all of the dependencies for Couchbase Lite where at the time of writing we are using V126.96.36.199. To verify and see the progress of the installation, click on the:
- ‘Package Console’ tab on the bottom right from within Xamarin Studio.
You are able to see detailed information on the Couchbase.Lite package being installed. Where the Package Console will have..
- Adding Couchbase.Lite…
- …There will be other files that are added in between…
- Finally you will be able to see ‘Successfully added ‘Couchbase.Lite …’ to your project
Next, over at the Solution explorer section over on the left of Xamarin Studio, you should see the following 4 packages now installed. Drop down the ‘Packages’ folder and you should see:
From the ‘Packages’ folder you can now easily update individual packages or all of them to the latest version or remove it from the project, by right clicking and selecting the appropriate menu item.
- Right click ‘Packages’ and click ‘Update’ to update all packages.
- Within Xamarin Studio you should see now ‘Updating 4 packages in project..’
Android & iOS Mobile Apps
We have successfully added Couchbase Lite into our Android project within Xamarin Studio. Now we will go into some starter code to create an app that has a local mobile database. The App that we are building is a Tasky tracking ToDo app that will have local persistance and what is cool is that we will only need to write our Database code once for both the iOS and Android solution as we are using Xamarin. One database and two different platform solutions. Below you can see both the Android version and the iOS UI.
The beauty here is that with just one database code base, you are able to target both platforms as oppose to re-writing the database code again to be platform specific. Below the iOS version is running the same Couchbase Lite client side code base as the above Android version.
We will begin by bringing into our project the require frameworks to create our database. You would only need to create the Database once and you would be able to reference it across the various platforms that your app supports.
- Right click on your App Project within the Solution Explorer
- Select: Add>Add New Project
This will be our Database project class so name the project appropriately. For the example, I have named it ‘shared_Couchbase_Database’
- Select: C#
- Select: Shared Project options
Couchbase Starter Code
We will begin by bringing into our project the require frameworks to create our database. At this point, your application project should have now the app project and a project for your database. Ours is named ‘shared_Couchbase_Database’ and the generated file got renamed to be ‘TaskManager’. Open that file and we will add the following statement at the top to be able to use the Couchbase APIs:
We will use the Couchbase Lite APIs to create a mobile database now. Currently, we are creating our database project to reference against the iOS and Android app projects. This will have our basic database operations. We will declare a Database variable and initialize the database within the constructor, while passing in a name which will be the name of our database to the ‘GetDatabase’ method. If it does not exist, a Database will be created. We have just created a database programmatically using the Couchbase Mobile APIs with the code below:
db = Manager.SharedInstance.GetDatabase("name_db");
Now we will be creating 4 basic operations for our mobile database. Create-Read-Update-Delete operations. We already saw before by creating a database, we also created a document database when we passed in a variable. Therefore the ‘Create’ has been done. Simple!
To get a particular Task that was created, we will create a ‘GetTask’ method and pass in a ‘String id’ this id references a particular document that relates to the Task.
The return type of the method is a type ‘Task’ and will be created later on. Each Task or Item that is created by the end user in the app will have a unique document ID in your database. So when a Task is created, a document is therefore created in junction. You can think of a Document as representing a Task here. Within the GetTask method, we will return back the associated document. From the particular document that is returned, we will call the ‘UserProperties’ API to get the properties of a document. The task that we return from the method will now have references to the document properties, eg. id, name, notes, done.
var doc = db.GetDocument(id);
var props = doc.UserProperties;
‘CreateAllDocumentsQuery’ method will create a Query that matches all Documents in the Database.
var query = db.CreateAllDocumentsQuery ();
call the ‘Run()’ method on the query variable to capture all the documents and from there you will iterate through these results to obtain the properties of each of the available documents. We will operate on a resultant row for a Coucbase Lite View, which is an index.
Obtain the ID by calling on the ‘DocumentID’ property on a particular row.
ID = row.DocumentId,
With each ‘task’ object that has its property results initialized, we will store it in the Task List and return it.
Call the ‘PutProperties’ method to save new Task or documents, which will create and save a new Revision with the specified properties.
The method takes a Dictionary as an input parameter so we will call the ‘ToDictionary’ method on the Task item.
doc.PutProperties (item.ToDictionary ());
If in the case the Task object’s ID value is not null, you will first retrieve the document in order to update the values of the keys. This is might look familiar as you have done this also in Step 5
doc = db.GetDocument (item.ID);
Copy and paste in the code that will update the document with the new key-values from the Task object before the end of the ‘else’ statement
The last operation is the ‘Delete’ operation and to delete a document, you will first need to obtain the document or task object that you wish to delete from the database. Then you will call the ‘Delete’ method on the document to remove it from the database.
Now that you have created a local databse with its operations, next we will create our ‘Task’ file that will contain the properties that would represent a task that a user creates.
To create the Task class, we will right click the database project that was previously created and then select:
- Add>New File …
In the ‘New File’ page, we will create an empty C# file called ‘Task’ for our example here and then click ‘New’. This is our Task object in which we will be creating the generic properties associated in order to represent a task.
Next, we are going to create our Task class which will hold all the properties of our Task object. Include the using statement:
We will create our Task class with the properties that represent a task. Recall that Couchbase Mobile is a NoSQL JSON database solution so we are storing our data as key-values. Below we are using a ‘Dictionary’ type to represent the key-value data schema for ‘name’, ‘notes’, ‘done’ keys that would reference the respective class variables of the same name.
You now have a complete local database on your mobile app and can head over to the
GitHub portal to complete the Xamarin Mobile Task App. You already have a completed Mobile Database within your application and the next steps are building a cross platform Xamarin App that is specific to either iOS or Android UX. For Couchbase Lite, you can reference the
Xamarin Android guide or the
Xamarin iOS guide to learn more on how to create offline mobile experieences with Sync and how to create document indexes using Views and then Querying documents for your mobile app. There is also the
Couchbase Mobile Xamarin Mini-Hack where you can learn how to build an offline mobile application and we will explore this further in the next Xamarin Couchbase blog!