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.


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 container using the Azure portal. You'll then build and deploy a todo list mobile app built on the SQL .NET API and Xamarin utilizing Xamarin.Forms and the MVVM architectural pattern.

Xamarin todo app running on iOS


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 create an Azure Cosmos DB free tier account, with the first 400 RU/s and 5 GB of storage for free. You can also use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. For the key to use with the emulator, see Authenticating requests.

Create a database account

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. On the New page, search for and select Azure Cosmos DB.

  3. On the Azure Cosmos DB page, select Create.

  4. In 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 A unique name Enter a name to identify your Azure Cosmos account. Because documents.azure.com is appended to the name that you provide to create your URI, use a unique name.

    The name can only contain lowercase letters, numbers, and the hyphen (-) character. It must be between 3-44 characters in length.
    API The type of account to create Select Core (SQL) to create a document database and query by using SQL syntax.

    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.

    Learn more about the SQL API.
    Location 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.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.
    Apply Azure Cosmos DB free tier discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier.


    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    The new account page for Azure Cosmos DB

  5. In the Global Distribution tab, configure the following details. You can leave the default values for the purpose of this quickstart:

    Setting Value Description
    Geo-Redundancy Disable Enable or disable global distribution on your account by pairing your region with a pair region. You can add more regions to your account later.
    Multi-region Writes Disable Multi-region writes capability allows you to take advantage of the provisioned throughput for your databases and containers across the globe.


    The following options are not available if you select Serverless as the Capacity mode:

    • Apply Free Tier Discount
    • Geo-redundancy
    • Multi-region Writes
  6. Optionally you can configure additional details in the following tabs:

    • Networking - Configure access from a virtual network.
    • Backup Policy - Configure either periodic or continuous backup policy.
    • Encryption - Use either service-managed key or a customer-managed key.
    • Tags - Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups.
  7. Select Review + create.

  8. 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

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

    The Azure Cosmos DB account page

Add a container

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

  1. Select Data Explorer > New Container.

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

    The Azure portal Data Explorer, Add Container pane

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

    Setting Suggested value Description
    Database ID ToDoList 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. Check the Share throughput across containers option, it allows you to share the throughput provisioned on the database across all the containers within the database. This option also helps with cost savings.
    Database throughput You can provision Autoscale or Manual throughput. Manual throughput allows you to scale RU/s yourself whereas autoscale throughput allows the system to scale RU/s based on usage. Select Manual for this example.

    Leave the throughput at 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later by estimating the required RU/s with the capacity calculator.

    Note: This setting is not available when creating a new container in a serverless account.
    Container ID Items Enter Items as the name for your new container. Container IDs have the same character requirements as database names.
    Partition key /category The sample described in this article uses /category as the partition key.

    Don't add Unique keys or turn on Analytical store for this example. Unique keys let you add a layer of data integrity to the database by ensuring the uniqueness of one or more values per partition key. For more information, see Unique keys in Azure Cosmos DB. Analytical store is used to enable large-scale analytics against operational data without any impact to your transactional workloads.

    Select OK. The Data Explorer displays the new database and container.

Add sample data

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

  1. From the Data Explorer, expand the Tasks database, expand the Items container. Select Items, and then select New Item.

    Create new documents in Data Explorer in the Azure portal

  2. Now add a document to the container 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, select Save.

    Copy in json data and select 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 Items tab in Data Explorer, review the default query SELECT * FROM c. This query retrieves and displays all documents from the container ordered by ID.

    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.

    mkdir "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. In Visual Studio, open C:\git-samples\azure-cosmos-db-sql-xamarin-getting-started\src\ToDoItems.sln

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 Visual Studio, open ToDoItems.Core/Helpers/APIKeys.cs.

  3. In the Azure portal, using the copy button, copy the URI value and make it the value of the CosmosEndpointUrl variable in APIKeys.cs.

    //#error Enter the URL of your Azure Cosmos DB endpoint here
    public static readonly string CosmosEndpointUrl = "[URI Copied from Azure portal]";
  4. In the Azure portal, using the copy button, copy the PRIMARY KEY value and make it the value of the Cosmos Auth Key in APIKeys.cs.

    //#error Enter the read/write authentication key of your Azure Cosmos DB endpoint here
    public static readonly string CosmosAuthKey = "[PRIMARY KEY copied from Azure portal";


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 ToDoItems.Core/Models folder models the documents in the Items container created above. Note that property naming is case-sensitive.

  • The CosmosDBService class in the 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:

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

    /// <summary> 
    /// </summary>
    /// <returns></returns>
    public async static Task<List<ToDoItem>> GetToDoItems()
        var todos = new List<ToDoItem>();
        if (!await Initialize())
            return todos;
        var todoQuery = docClient.CreateDocumentQuery<ToDoItem>(
            UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
            new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
            .Where(todo => todo.Completed == false)
        while (todoQuery.HasMoreResults)
            var queryResults = await todoQuery.ExecuteNextAsync<ToDoItem>();
        return todos;

    The CreateDocumentQuery<T> takes a URI that points to the container 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 will examine in order to see if additional results remain to be returned.


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

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

    /// <summary> 
    /// </summary>
    /// <returns></returns>
    public async static Task InsertToDoItem(ToDoItem item)
        if (!await Initialize())
        await docClient.CreateDocumentAsync(
            UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),

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

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

    /// <summary> 
    /// </summary>
    /// <returns></returns>
    public async static Task UpdateToDoItem(ToDoItem item)
        if (!await Initialize())
        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 container 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:

    /// <summary> 
    /// </summary>
    /// <returns></returns>
    public async static Task DeleteToDoItem(ToDoItem item)
        if (!await Initialize())
        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.


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 two 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 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 Search bar, search for and select Resource groups.

  2. From the list, select the resource group you created for this quickstart.

    Select the resource group to delete

  3. On the resource group Overview page, select Delete resource group.

    Delete the resource group

  4. In the next window, enter 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 account, create a container using the Data Explorer, and build and deploy a Xamarin app. You can now import more data to your Azure Cosmos account.