title | description | author | ms.service | ms.subservice | ms.devlang | ms.topic | ms.date | ms.author | ms.custom |
---|---|---|---|---|---|---|---|---|---|
Azure Cosmos DB: Build a todo app with Xamarin |
Presents a Xamarin code sample you can use to connect to and query Azure Cosmos DB |
anfeldma-ms |
cosmos-db |
cosmosdb-sql |
dotnet |
quickstart |
09/22/2020 |
anfeldma |
devx-track-csharp |
[!div class="op_single_selector"]
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 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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/ios-todo-screen.png" alt-text="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.
[!INCLUDE quickstarts-free-trial-note] [!INCLUDE cosmos-db-emulator-docdb-api]
[!INCLUDE cosmos-db-create-dbaccount]
[!INCLUDE cosmos-db-create-collection]
[!INCLUDE cosmos-db-create-sql-api-add-sample-data]
[!INCLUDE cosmos-db-create-sql-api-query-data]
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.
-
Open a command prompt, create a new folder named git-samples, then close the command prompt.
md "C:\git-samples"
-
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"
-
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
-
Then open the ToDoItems.sln file from the samples/xamarin/ToDoItems folder in Visual Studio.
Go back to the Azure portal to get your API key information and copy it into the app.
-
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/keys.png" alt-text="View and copy an access key in the Azure portal, Keys blade":::
-
In either Visual Studio 2019 or Visual Studio for Mac, open the APIKeys.cs file in the azure-cosmos-db-sql-xamarin-getting-started/src/ToDoItems.Core/Helpers folder.
-
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 = "";
-
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 = "";
[!INCLUDE cosmos-db-auth-key-info]
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/android-todo-screen.png" alt-text="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 container 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 aDocumentClient
type variable. TheDocumentClient
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 theCosmosDBService.GetToDoItems
function: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 aWhere
clause. In this case only todo items that are not completed are returned.The
CreateDocumentQuery<T>
function is executed synchronously, and returns anIQueryable<T>
. However, theAsDocumentQuery
method converts theIQueryable<T>
to anIDocumentQuery<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, whichHasMoreResults
checking to see if additional results remain to be returned.
Tip
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: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: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:Again note the unique document URI being created and passed to the
DocumentClient.DeleteDocumentAsync
function.
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.
-
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/ide-select-platform.png" alt-text="Selecting a platform to debug in Visual Studio for Mac":::
-
To start debugging the app, either press cmd+Enter or click the play button.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/ide-start-debug.png" alt-text="Starting to debug in Visual Studio for Mac":::
-
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/ios-droid-started.png" alt-text="Launch screen of ToDo app":::
-
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/simulator-complete.png" alt-text="Complete a todo item":::
-
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/simulator-edit.png" alt-text="Edit todo item":::
-
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.
:::image type="content" source="./media/create-sql-api-xamarin-dotnet/simulator-add.png" alt-text="Add todo item":::
[!INCLUDE cosmosdb-tutorial-review-slas]
[!INCLUDE cosmosdb-delete-resource-group]
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 additional data to your Azure Cosmos account.
[!div class="nextstepaction"] Import data into Azure Cosmos DB