Azure Cosmos DB: Build a todo app with Xamarin

Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. You can quickly create and query document, key/value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

Note

Sample code for an entire canonical sample Xamarin app showcasing multiple Azure offerings, including CosmosDB, can be found on GitHub here. This app demonstrates viewing geographically dispersed contacts, and allowing those contacts to update their location.

This quickstart demonstrates how to create an Azure Cosmos DB SQL API account, document database, and collection using the Azure portal. You'll then build and deploy a todo list web app built on the SQL .NET API and Xamarin utilizing Xamarin.Forms and the MVVM architectural pattern.

Xamarin todo app running on iOS

Prerequisites

If you are developing on Windows and don’t already have Visual Studio 2017 installed, you can download and use the free Visual Studio 2017 Community Edition. Make sure that you enable Azure development and Mobile Development with .NET workloads during the Visual Studio setup.

If you are using a Mac, you can download the free Visual Studio for Mac.

If you don't have an Azure subscription, create a free account before you begin.

You can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. Or, you can use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. The Primary Key is provided in Authenticating requests.

Create a database account

  1. In a new browser window, sign in to the Azure portal.
  2. Click Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. In the New account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    ID Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can only contain lowercase letters, numbers, and the hyphen (-) character, and it must contain 3 to 50 characters.
    API SQL The API determines the type of account to create. Azure Cosmos DB provides five APIs: SQL (document database), Gremlin (graph database), MongoDB (document database), Table API, and Cassandra API. Each API currently requires you to create a separate account.

    Select SQL because in this article you will create a document database and query using SQL syntax.

    Learn more about the SQL API
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same unique name as provided above in ID
    Select Create New, then enter a new resource-group name for your account. For simplicity, you can use the same name as your ID.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
    Enable geo-redundancy Leave blank This creates a replicated version of your database in a second (paired) region. Leave this blank.

    Then click Create.

    The new account page for Azure Cosmos DB

  4. The account creation takes a few minutes. Wait for the portal to display the Congratulations! Your Azure Cosmos DB account was created page.

    The Azure portal Notifications pane

Add a collection

You can now use the Data Explorer tool in the Azure portal to create a database and collection.

  1. Click Data Explorer > New Collection.

    The Add Collection area is displayed on the far right, you may need to scroll right to see it.

    The Azure portal Data Explorer, Add Collection blade

  2. In the Add collection page, enter the settings for the new collection.

    Setting Suggested value Description
    Database id Tasks Enter Tasks as the name for the new database. Database names must contain from 1 through 255 characters, and they cannot contain /, \, #, ?, or a trailing space.
    Collection id Items Enter Items as the name for your new collection. Collection ids have the same character requirements as database names.
    Storage capacity Fixed (10 GB) Use the default value of Fixed (10 GB). This value is the storage capacity of the database.
    Throughput 400 RU Change the throughput to 400 request units per second (RU/s). Storage capacity must be set to Fixed (10 GB) in order to set throughput to 400 RU/s. If you want to reduce latency, you can scale up the throughput later.

    In addition to the preceding settings, you can optionally add Unique keys for the collection. Let's leave the field empty in this example. Unique keys provide developers with the ability to add a layer of data integrity to the database. By creating a unique key policy while creating a collection, you ensure the uniqueness of one or more values per partition key. To learn more, refer to the Unique keys in Azure Cosmos DB article.

    Click OK.

    Data Explorer displays the new database and collection.

    The Azure portal Data Explorer, showing the new database and collection

Add sample data

You can now add data to your new collection using Data Explorer.

  1. In Data Explorer, the new database appears in the Collections pane. Expand the Tasks database, expand the Items collection, click Documents, and then click New Documents.

    Create new documents in Data Explorer in the Azure portal

  2. Now add a document to the collection with the following structure.

    {
        "id": "1",
        "category": "personal",
        "name": "groceries",
        "description": "Pick up apples and strawberries.",
        "isComplete": false
    }
    
  3. Once you've added the json to the Documents tab, click Save.

    Copy in json data and click Save in Data Explorer in the Azure portal

  4. Create and save one more document where you insert a unique value for the id property, and change the other properties as you see fit. Your new documents can have any structure you want as Azure Cosmos DB doesn't impose any schema on your data.

Query your data

You can now use queries in Data Explorer to retrieve and filter your data.

  1. See that by default, the query is set to SELECT * FROM c. This default query retrieves and displays all documents in the collection.

    Default query in Data Explorer is `SELECT * FROM c`

  2. Stay on the Documents tab, and change the query by clicking the Edit Filter button, adding ORDER BY c._ts DESC to the query predicate box, and then clicking Apply Filter.

    Change the default query by adding ORDER BY c._ts DESC and clicking Apply Filter

This modified query lists the documents in descending order based on their time stamp, so now your second document is listed first. If you're familiar with SQL syntax, you can enter any of the supported SQL queries in this box.

That completes our work in Data Explorer. Before we move on to working with code, note that you can also use Data Explorer to create stored procedures, UDFs, and triggers to perform server-side business logic as well as scale throughput. Data Explorer exposes all of the built-in programmatic data access available in the APIs, but provides easy access to your data in the Azure portal.

Clone the sample application

Now let's clone the Xamarin SQL API app from github, review the code, obtain the API keys, and run it. You'll see how easy it is to work with data programmatically.

  1. Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
    
  2. Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-sql-xamarin-getting-started.git
    
  4. Then open the ToDoItems.sln file from the samples/xamarin/ToDoItems folder in Visual Studio.

Obtain your API keys

Go back to the Azure portal to get your API key information and copy it into the app.

  1. In the Azure portal, in your Azure Cosmos DB SQL API account, in the left navigation click Keys, and then click Read-write Keys. You'll use the copy buttons on the right side of the screen to copy the URI and Primary Key into the APIKeys.cs file in the next step.

    View and copy an access key in the Azure portal, Keys blade

  2. In either Visual Studio 2017 or Visual Studio for Mac, open the APIKeys.cs file in the azure-documentdb-dotnet/samples/xamarin/ToDoItems/ToDoItems.Core/Helpers folder.

  3. Copy your URI value from the portal (using the copy button) and make it the value of the CosmosEndpointUrl variable in APIKeys.cs.

    public static readonly string CosmosEndpointUrl = "{Azure Cosmos DB account URL}";

  4. Then copy your PRIMARY KEY value from the portal and make it the value of the Cosmos Auth Key in APIKeys.cs.

    public static readonly string CosmosAuthKey = "{Azure Cosmos DB secret}";

Important

This quick start hard codes the Azure Cosmos DB authentication key for the sake of demonstration purposes. It's not recommended to hard code an authentication key when you are using it in a production app. To learn how to access Azure Cosmos DB in a securely by using a resource token, view the Authenticating users with Azure Cosmos DB article.

Review the code

This solution demonstrates how to create a ToDo app using the Azure Cosmos DB SQL API and Xamarin.Forms. The app has two tabs, the first tab contains a list view showing todo items that are not yet complete. The second tab displays todo items that have been completed. In addition to viewing not completed todo items in the first tab, you can also add new todo items, edit existing ones, and mark items as completed.

Copy in json data and click Save in Data Explorer in the Azure portal

The code in the ToDoItems solution contains:

  • ToDoItems.Core: This is a .NET Standard project holding a Xamarin.Forms project and shared application logic code that maintains todo items within Azure Cosmos DB.
  • ToDoItems.Android: This project contains the Android app.
  • ToDoItems.iOS: This project contains the iOS app.

Now let's take a quick review of how the app communicates with Azure Cosmos DB.

  • The Microsoft.Azure.DocumentDb.Core NuGet package is required to be added to all projects.
  • The ToDoItem class in the azure-documentdb-dotnet/samples/xamarin/ToDoItems/ToDoItems.Core/Models folder models the documents in the Items collection created above. Note that property naming is case-sensitive.
  • The CosmosDBService class in the azure-documentdb-dotnet/samples/xamarin/ToDoItems/ToDoItems.Core/Services folder encapsulates the communication to Azure Cosmos DB.
  • Within the CosmosDBService class there is a DocumentClient type variable. The DocumentClient is used to configure and execute requests against the Azure Cosmos DB account, and is instantiated on line 31:

    docClient = new DocumentClient(new Uri(APIKeys.CosmosEndpointUrl), APIKeys.CosmosAuthKey);
    
  • When querying a collection for documents, the DocumentClient.CreateDocumentQuery<T> method is used, as seen here in the CosmosDBService.GetToDoItems function:

    public async static Task<List<ToDoItem>> GetToDoItems()
    {
        var todos = new List<ToDoItem>();
    
        var todoQuery = docClient.CreateDocumentQuery<ToDoItem>(
                                UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
                                .Where(todo => todo.Completed == false)
                                .AsDocumentQuery();
    
        while (todoQuery.HasMoreResults)
        {
            var queryResults = await todoQuery.ExecuteNextAsync<ToDoItem>();
    
            todos.AddRange(queryResults);
        }
    
        return todos;
    }
    

    The CreateDocumentQuery<T> takes a URI that points to the collection created in the previous section. And you are also able to specify LINQ operators such as a Where clause. In this case only todo items that are not completed are returned.

    The CreateDocumentQuery<T> function is executed synchronously, and returns an IQueryable<T>. However, the AsDocumentQuery method converts the IQueryable<T> to an IDocumentQuery<T> object which can be executed asynchronously. Thus not blocking the UI thread for mobile applications.

    The IDocumentQuery<T>.ExecuteNextAsync<T> function retrieves the page of results from Azure Cosmos DB, which HasMoreResults checking to see if additional results remain to be returned.

Tip

Several functions that operate on Azure Cosmos DB collections and documents take an URI as a parameter which specifies the address of the collection or document. This URI is constructed using the URIFactory class. URIs for databases, collections, and documents can all be created with this class.

  • The ComsmosDBService.InsertToDoItem function on line 107 demonstrates how to insert a new document:

    public async static Task InsertToDoItem(ToDoItem item)
    {
        ...
        await docClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), item);
        ...
    }
    

    The document collection URI is specified as well as the item to be inserted.

  • The CosmosDBService.UpdateToDoItem function on line 124 demonstrates how to replace an existing document with a new one:

    public async static Task UpdateToDoItem(ToDoItem item)
    {
        ...
        var docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, item.Id);
    
        await docClient.ReplaceDocumentAsync(docUri, item);
    }
    

    Here a new URI is needed to uniquely identify the document to replace and is obtained by using UriFactory.CreateDocumentUri and passing it the database and collection names and the id of the document.

    The DocumentClient.ReplaceDocumentAsync replaces the document identified by the URI with the one specified as a parameter.

  • Deleting an item is demonstrated with the CosmosDBService.DeleteToDoItem function on line 115:

    public async static Task DeleteToDoItem(ToDoItem item)
    {
        ...
        var docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, item.Id);
    
        await docClient.DeleteDocumentAsync(docUri);
    }
    

    Again note the unique doument URI being created and passed to the DocumentClient.DeleteDocumentAsync function.

Run the app

You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

The following steps will demonstrate how to run the app using the Visual Studio for Mac debugger.

Note

Usage of the Android version app is exactly the same, any differences will be called out in the steps below. If you wish to debug with Visual Studio on Windows, documentation todo so can be found for iOS here and Android here.

  1. First select the platform you wish to target by clicking on the dropdown highlighted and selecting either ToDoItems.iOS for iOS or ToDoItems.Android for Android.

    Selecting a platform to debug in Visual Studio for Mac

  2. To start debugging the app, either press cmd+Enter or click the play button.

    Starting to debug in Visual Studio for Mac

  3. When the iOS simulator or Android emulator finishes launching, the app will display 2 tabs at the bottom of the screen for iOS and the top of the screen for Android. The first shows todo items which are not completed, the second shows todo items which are completed.

    Launch screen of ToDo app

  4. To complete a todo item on iOS, slide it to the left > tap on the Complete button. To complete a todo item on Android, long press the item > then tap on the complete button.

    Complete a todo item

  5. To edit a todo item > tap on the item > a new screen appears letting you enter new values. Tapping the save button will persist the changes to Azure Cosmos DB.

    Edit todo item

  6. To add a todo item > tap on the Add button on the upper right of the home screen > a new, blank, edit page will appear.

    Add todo item

Review SLAs in the Azure portal

The throughput, storage, availability, latency, and consistency of the resources in your account are monitored in the Azure portal. Let's take a quick look at these metrics.

  1. Click Metrics in the navigation menu.

    Metrics in the Azure portal

  2. Click through each of the tabs so you're aware of the metrics Azure Cosmos DB provides.

    Each chart that's associated with the Azure Cosmos DB Service Level Agreements (SLAs) provides a line that shows if any of the SLAs have been violated. Azure Cosmos DB makes monitoring your SLAs transparent with this suite of metrics.

    Azure Cosmos DB metrics suite

Clean up resources

If you're not going to continue to use this app, delete all resources created by this quickstart with the following steps so you don't incur any charges:

  1. In the Azure portal, select Resource groups on the far left, and then select the resource group you created.

    If the left menu is collapsed, click Expand button to expand it.

    Metrics in the Azure portal

  2. In the new window select the resource group, and then click Delete resource group.

    Metrics in the Azure portal

  3. In the new window, type the name of the resource group to delete, and then click Delete.

Next steps

In this quickstart, you've learned how to create an Azure Cosmos DB account, create a collection using the Data Explorer, and build and deploy a Xamarin app. You can now import additional data to your Azure Cosmos DB account.