Quickstart: Build a todo app with Xamarin using Azure Cosmos DB SQL API account

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 2019 installed, you can download and use the free Visual Studio 2019 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. Sign in to the Azure portal.

  2. Select Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name Enter a unique name Enter a name to identify your Azure Cosmos 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. It must be between 3-31 characters in length.
    API Core (SQL) The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Select Core (SQL) to create a document database and query by using SQL syntax.

    Learn more about the SQL API.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.

    The new account page for Azure Cosmos DB

  4. Select Review + create. You can skip the Network and Tags sections.

  5. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  6. Select Go to resource to go to the Azure Cosmos DB account page.

    The Azure Cosmos DB account page

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 pane

  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.
    Partition key <Your partition key> Enter a partition key such as /userid.
    Throughput 400 RU Change the throughput to 400 request units per second (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 use queries in Data Explorer to retrieve and filter your data.

  1. At the top of the Documents tab in Data Explorer, review the default query SELECT * FROM c. This query retrieves and displays all documents in the collection in ID order.

    Default query in Data Explorer is SELECT * FROM c

  2. To change the query, select Edit Filter, replace the default query with ORDER BY c._ts DESC, and then select Apply Filter.

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

    The modified query displays the documents in descending order based on their time stamp, so now your second document is listed first.

    Changed query to ORDER BY c._ts DESC and clicking Apply Filter

If you're familiar with SQL syntax, you can enter any supported SQL queries in the query predicate box. You can also use Data Explorer to create stored procedures, UDFs, and triggers for server-side business logic.

Data Explorer provides easy Azure portal access to all of the built-in programmatic data access features available in the APIs. You also use the portal to scale throughput, get keys and connection strings, and review metrics and SLAs for your Azure Cosmos DB account.

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 2019 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 document 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 Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:

  1. In the Azure portal, select Resource groups on the far left. If the left menu is collapsed, select Expand button to expand it.

  2. Select the resource group you created for this quickstart.

    Metrics in the Azure portal

  3. In the new window, select Delete resource group.

    Metrics in the Azure portal

  4. In the next window, type the name of the resource group to delete, and then select 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.