快速入门:使用 Azure Cosmos DB SQL API 帐户通过 Xamarin 构建待办事项应用Quickstart: Build a todo app with Xamarin using Azure Cosmos DB SQL API account

Azure Cosmos DB 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally distributed multi-model database service. 可快速创建和查询文档、键/值和图形数据库,所有这些都受益于 Azure Cosmos DB 核心的多区域分布和水平缩放功能。You can quickly create and query document, key/value, and graph databases, all of which benefit from the multiple-region distribution and horizontal scale capabilities at the core of Azure Cosmos DB.


在 GitHub 上的此文档中,可以找到整个规范示例 Xamarin 应用的示例代码,其中展示了多个 Azure 产品,包括 CosmosDB。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.

本快速入门演示如何使用 Azure 门户创建 Azure Cosmos DB SQL API 帐户、文档数据库和容器。This quickstart demonstrates how to create an Azure Cosmos DB SQL API account, document database, and container using the Azure portal. 然后,你将使用 Xamarin.FormsMVVM 体系结构模式生成并部署一个基于 SQL .NET APIXamarin 的待办事项列表移动应用。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.

在 iOS 上运行的 Xamarin ToDo 应用


如果是在 Windows 上进行开发,且尚未安装 Visual Studio 2019,可以下载并使用免费的 Visual Studio 2019 Community EditionIf 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. 在安装 Visual Studio 的过程中,请确保启用“Azure 开发”和“使用 .NET 进行移动开发”工作负荷。 Make sure that you enable Azure development and Mobile Development with .NET workloads during the Visual Studio setup.

如果使用的是 Mac,则可以下载免费的 Visual Studio for MacIf you are using a Mac, you can download the free Visual Studio for Mac.

如果没有 Azure 订阅,可在开始前创建一个 试用帐户If you don't have an Azure subscription, create a trial account before you begin.

可以使用 URI 为 Azure Cosmos DB 模拟器https://localhost:8081You can 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. 转到 Azure 门户以创建 Azure Cosmos DB 帐户。Go to the Azure portal to create an Azure Cosmos DB account. 在你的主页上,从“Azure 服务” 面板中选择“创建资源” 。At your homepage choose Create a resource from the Azure services panel.


  2. 搜索“Azure Cosmos DB”,然后选择它。 。Search for and select Azure Cosmos DB.

    Azure 门户资源下拉列表

  3. 选择“创建” 。Select Create.

    创建 Azure Cosmos DB 资源

  4. 在“创建 Azure Cosmos DB 帐户”页上,输入新 Azure Cosmos 帐户的基本设置 。On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    设置Setting Value 说明Description
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。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 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 将追加到所提供的名称以创建 URI,因此,请使用唯一的名称 。Because documents.azure.cn 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. 它的长度必须介于 3 到 31 个字符之间。It must be between 3-31 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询 。Select Core (SQL) to create a document database and query by using SQL syntax.

    API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    详细了解 SQL APILearn more about the SQL API.
    应用免费层折扣Apply Free Tier Discount 应用或不应用Apply or Do not apply 使用 Azure Cosmos DB 免费层,你将在帐户中获得每秒的前 400 RU 免费的吞吐量和 5 GB 的免费存储。With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. 了解免费层的详细信息。Learn more about free tier.
    位置Location 离用户最近的区域The region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。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.
    帐户类型Account Type 生产或非生产Production or Non-Production 如果帐户将用于生产工作负荷,请选择“生产” 。Select Production if the account will be used for a production workload. 如果帐户将用于非生产环境(例如开发、测试、QA 或过渡),请选择“非生产” 。Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. 这是一个 Azure 资源标记设置,用于调整门户体验,但不会影响基础 Azure Cosmos DB 帐户。This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. 可以随时更改此值。You can change this value anytime.


    每个 Azure 订阅最多可以有一个免费层 Azure Cosmos DB 帐户,并且你必须在创建帐户时选择加入使用。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.

    Azure Cosmos DB 的“新建帐户”页

  5. 选择“查看 + 创建” 。Select Review + create. 可以跳过“网络”和“标记”部分 。You can skip the Network and Tags sections.

  6. 检查帐户设置,然后选择“创建”。 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.

    Azure 门户“通知”窗格

  7. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。 Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页

添加容器Add a container

现在可以在 Azure 门户中使用数据资源管理器工具来创建数据库和容器。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.

    Azure 门户 >“数据资源管理器”>“添加集合”窗格

  2. 在“添加容器”页中,输入新容器的设置。 In the Add container page, enter the settings for the new container.

    设置Setting 建议的值Suggested value 说明Description
    数据库 IDDatabase ID 任务Tasks 输入 Tasks 作为新数据库的名称。Enter Tasks as the name for the new database. 数据库名称必须包含 1 到 255 个字符,不能包含 /, \\, #, ? 或尾随空格。Database names must contain from 1 through 255 characters, and they cannot contain /, \\, #, ?, or a trailing space. 选中“预配数据库吞吐量”选项,这样就可以在数据库中的所有容器之间共享预配给该数据库的吞吐量。 Check the Provision database throughput option, it allows you to share the throughput provisioned to the database across all the containers within the database. 此选项还有助于节省成本。This option also helps with cost savings.
    吞吐量Throughput 400400 将吞吐量保留为每秒 400 个请求单位 (RU/s)。Leave the throughput at 400 request units per second (RU/s). 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
    容器 IDContainer ID ItemsItems 输入 Items 作为新容器的名称。Enter Items as the name for your new container. 容器 ID 与数据库名称的字符要求相同。Container IDs have the same character requirements as database names.
    分区键Partition key /category/category 本文中所述的示例使用 /category 作为分区键。The sample described in this article uses /category as the partition key.

    除了前面的设置,还可以选择为容器添加“唯一键”。 In addition to the preceding settings, you can optionally add Unique keys for the container. 在此示例中,请将此字段留空。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 container, you ensure the uniqueness of one or more values per partition key. 若要了解详细信息,请参阅 Azure Cosmos DB 中的唯一键一文。To learn more, refer to the Unique keys in Azure Cosmos DB article.

    选择“确定” 。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. 在“数据资源管理器”中展开“Tasks”数据库,然后展开“Items”容器。 From the Data Explorer, expand the Tasks database, expand the Items container. 选择“项”,然后单击“新建项”。 Select Items, and then click New Item.

    在 Azure 门户的数据资源管理器中创建新文档

  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. 将 json 添加到“文档”选项卡以后,即可选择“保存”。 Once you've added the json to the Documents tab, select Save.

    通过复制添加 JSON 数据,然后在 Azure 门户上的数据资源管理器中选择“保存”

  4. 再创建并保存一个文档,在其中插入 id 属性的唯一值,并将其他属性更改为适当值。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. 新文档可以具有所需的任何结构,因为 Azure Cosmos DB 不对数据施加任何架构。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. 在数据资源管理器的“项”选项卡顶部, 查看默认查询 SELECT * FROM cAt the top of the Items tab in Data Explorer, review the default query SELECT * FROM c. 此查询检索并显示容器中按 ID 排序的所有文档。This query retrieves and displays all documents from the container ordered by ID.

    数据资源管理器中的默认查询是“SELECT * FROM c”

  2. 若要更改查询,请选择“编辑筛选器”, 将默认查询替换为 ORDER BY c._ts DESC,然后选择“应用筛选器”。 To change the query, select Edit Filter, replace the default query with ORDER BY c._ts DESC, and then select Apply Filter.

    添加“ORDER BY c._ts DESC”并单击“应用筛选器”,更改默认查询

    此修改后的查询根据文档的时间戳按降序显示文档,所以现在最先列出的是第二个文档。The modified query displays the documents in descending order based on their time stamp, so now your second document is listed first.

    将查询更改为 ORDER BY c._ts DESC,然后单击“应用筛选器”

如果熟悉 SQL 语法,可以在查询谓词框中输入任何受支持的 SQL 查询If you're familiar with SQL syntax, you can enter any supported SQL queries in the query predicate box. 还可以使用数据资源管理器创建存储过程、UDF 和触发器以执行服务器端业务逻辑。You can also use Data Explorer to create stored procedures, UDFs, and triggers for server-side business logic.

数据资源管理器可以通过 Azure 门户轻松访问 API 中提供的所有内置编程数据访问功能。Data Explorer provides easy Azure portal access to all of the built-in programmatic data access features available in the APIs. 也可通过门户缩放吞吐量、获取密钥和连接字符串,以及查看 Azure Cosmos DB 帐户的指标和 SLA。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

现在请从 GitHub 克隆 Xamarin SQL API 应用、查看代码、获取 API 密钥,然后运行该应用。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. 打开命令提示符,新建一个名为“git-samples”的文件夹,然后关闭命令提示符。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
  2. 打开诸如 git bash 之类的 git 终端窗口,并使用 cd 命令更改为要安装示例应用的新文件夹。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. 然后,在 Visual Studio 中打开 samples/xamarin/ToDoItems 文件夹中的 ToDoItems.sln 文件。Then open the ToDoItems.sln file from the samples/xamarin/ToDoItems folder in Visual Studio.

获取 API 密钥Obtain your API keys

返回到 Azure 门户,获取 API 密钥信息并将其复制到应用中。Go back to the Azure portal to get your API key information and copy it into the app.

  1. Azure 门户的 Azure Cosmos DB SQL API 帐户的左侧导航栏中,单击“密钥” ,然后单击“读写密钥” 。In the Azure portal, in your Azure Cosmos DB SQL API account, in the left navigation click Keys, and then click Read-write Keys. 使用屏幕右侧的复制按钮将 URI 和主密钥复制到下一步的 APIKeys.cs 文件中。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.

    在 Azure 门户的“密钥”边栏选项卡中查看并复制访问密钥

  2. 在 Visual Studio 2019 或 Visual Studio for Mac 中,打开 azure-cosmos-db-sql-xamarin-getting-started/src/ToDoItems.Core/Helpers 文件夹中的 APIKeys.cs 文件。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.

  3. 从门户中复制 URI 值(使用复制按钮),并在 APIKeys.cs 中将其设为 CosmosEndpointUrl 变量的值。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 = "";

  4. 然后从门户复制“主密钥”的值,并在 APIKeys.cs 中将其设为 Cosmos Auth Key 的值。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 身份验证密钥进行了硬编码。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. 若要了解如何使用资源令牌安全地访问 Azure Cosmos DB,请查看使用 Azure Cosmos DB 对用户进行身份验证一文。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

此解决方案演示如何使用 Azure Cosmos DB SQL API 和 Xamarin.Forms 创建 ToDo 应用。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.

通过复制添加 json 数据,然后在 Azure 门户的数据资源管理器中单击“保存”

ToDoItems 解决方案中的代码包含:The code in the ToDoItems solution contains:

  • ToDoItems.Core:这是一个 .NET Standard 项目,其中包含一个 Xamarin.Forms 项目以及用于在 Azure Cosmos DB 中保留待办事项的共享应用程序逻辑代码。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:此项目包含 Android 应用。ToDoItems.Android: This project contains the Android app.
  • ToDoItems.iOS:此项目包含 iOS 应用。ToDoItems.iOS: This project contains the iOS app.

现在,请快速查看应用如何与 Azure Cosmos DB 通信。Now let's take a quick review of how the app communicates with Azure Cosmos DB.

  • 需将 Microsoft.Azure.DocumentDb.Core NuGet 包添加到所有项目。The Microsoft.Azure.DocumentDb.Core NuGet package is required to be added to all projects.

  • azure-documentdb-dotnet/samples/xamarin/ToDoItems/ToDoItems.Core/Models 文件夹中的 ToDoItem 类为上面创建的 Items 容器中的文档建模。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.

  • azure-documentdb-dotnet/samples/xamarin/ToDoItems/ToDoItems.Core/Services 文件夹中的 CosmosDBService 类将通信封装到 Azure Cosmos DB。The CosmosDBService class in the azure-documentdb-dotnet/samples/xamarin/ToDoItems/ToDoItems.Core/Services folder encapsulates the communication to Azure Cosmos DB.

  • CosmosDBService 类中有一个 DocumentClient 类型的变量。Within the CosmosDBService class there is a DocumentClient type variable. DocumentClient 用于针对 Azure Cosmos DB 帐户配置和执行请求,并进行实例化: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);
  • 查询容器中的文档时,使用 DocumentClient.CreateDocumentQuery<T> 方法,如下面的 CosmosDBService.GetToDoItems 函数所示: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;

    CreateDocumentQuery<T> 采用的 URI 指向在上一部分创建的容器。The CreateDocumentQuery<T> takes a URI that points to the container created in the previous section. 还可以指定 LINQ 运算符,例如 Where 子句。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.

    CreateDocumentQuery<T> 函数是同步执行的,返回 IQueryable<T>The CreateDocumentQuery<T> function is executed synchronously, and returns an IQueryable<T>. 不过,AsDocumentQuery 方法可以将 IQueryable<T> 转换为 IDocumentQuery<T> 对象,后者可以异步执行。However, the AsDocumentQuery method converts the IQueryable<T> to an IDocumentQuery<T> object which can be executed asynchronously. 因此,不会阻止移动应用程序的 UI 线程。Thus not blocking the UI thread for mobile applications.

    IDocumentQuery<T>.ExecuteNextAsync<T> 函数从 Azure Cosmos DB 检索结果页,该 DB 会进行 HasMoreResults 检查,看是否还有其他需要返回的结果。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.


    多个在 Azure Cosmos 容器和文档上运行的函数采用 URI 作为参数,以便指定容器或文档的地址。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. 此 URI 使用 URIFactory 类进行构造。This URI is constructed using the URIFactory class. 数据库、容器和文档的 URI 均可通过此类来创建。URIs for databases, containers, and documents can all be created with this class.

  • ComsmosDBService.InsertToDoItem 函数演示如何插入新文档: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),

    指定了项 URI 以及要插入的项。The item URI is specified as well as the item to be inserted.

  • CosmosDBService.UpdateToDoItem 函数演示如何将现有文档替换为新文档: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);

    此处需要使用新的 URI 来唯一标识要替换的文档,而获得该 URI 的方法是先使用 UriFactory.CreateDocumentUri,然后向其传递数据库和容器的名称以及文档的 ID。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.

    DocumentClient.ReplaceDocumentAsync 将通过 URI 标识的文档替换为已指定为参数的文档。The DocumentClient.ReplaceDocumentAsync replaces the document identified by the URI with the one specified as a parameter.

  • CosmosDBService.DeleteToDoItem 函数演示了如何删除某个项: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);

    再次请注意这个在创建后传递给 DocumentClient.DeleteDocumentAsync 函数的唯一的文档 URI。Again note the unique document URI being created and passed to the DocumentClient.DeleteDocumentAsync function.

运行应用程序Run the app

现已使用与 Azure Cosmos DB 进行通信所需的所有信息更新应用。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

以下步骤将演示如何使用 Visual Studio for Mac 调试器来运行应用。The following steps will demonstrate how to run the app using the Visual Studio for Mac debugger.


Android 版应用的使用完全相同。如果有差异,则会在下面的步骤中指出。Usage of the Android version app is exactly the same, any differences will be called out in the steps below. 如果希望在 Windows 上使用 Visual Studio 进行调试,可参阅此处 (iOS)此处 (Android) 的相关操作文档。If you wish to debug with Visual Studio on Windows, documentation todo so can be found for iOS here and Android here.

  1. 首先选择要作为目标的平台,方法是:单击突出显示的下拉列表,然后选择适用于 iOS 的 ToDoItems.iOS 或适用于 Android 的 ToDoItems.Android。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.

    选择可在 Visual Studio for Mac 中进行调试的平台

  2. 若要开始调试此应用,请按 cmd+Enter 或单击“开始”按钮。To start debugging the app, either press cmd+Enter or click the play button.

    开始在 Visual Studio for Mac 中调试

  3. 当 iOS 模拟器或 Android Emulator 启动完毕,此应用会在屏幕底部 (iOS) 或顶部 (Android) 显示 2 个选项卡。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.

    ToDo 应用的启动屏幕

  4. 若要在 iOS 上完成某个待办事项,请向左滑动,然后点击“完成”按钮。 To complete a todo item on iOS, slide it to the left > tap on the Complete button. 若要在 Android 上完成某个待办事项,请长按该项,然后点击“完成”按钮。To complete a todo item on Android, long press the item > then tap on the complete button.


  5. 若要编辑某个待办事项,请点击该项,此时会出现一个新的屏幕,供你输入新值。To edit a todo item > tap on the item > a new screen appears letting you enter new values. 点击“保存”按钮会将所做的更改保存到 Azure Cosmos DB。Tapping the save button will persist the changes to Azure Cosmos DB.


  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.


在 Azure 门户中查看 SLAReview SLAs in the Azure portal

Azure 门户监视 Cosmos DB 帐户吞吐量、存储、可用性、延迟和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服务级别协议 (SLA) 关联的指标的图表显示与实际性能相比的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此套指标使得监视 SLA 十分透明。This suite of metrics makes monitoring your SLAs transparent.

若要查看指标和 SLA,请执行以下操作:To review metrics and SLAs:

  1. 在 Cosmos DB 帐户的导航菜单中选择“指标” 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 选择一个选项卡,如“延迟” ,然后选择右侧的时间范围。Select a tab such as Latency, and select a timeframe on the right. 比较图表上的“实际” 和“SLA” 线。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 指标套件

  3. 查看其他选项卡上的指标。Review the metrics on the other tabs.

清理资源Clean up resources

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。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. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。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.


  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.


  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

本快速入门教程已介绍如何创建 Azure Cosmos 帐户、使用数据资源管理器创建容器,以及生成和部署控制台应用。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. 现在可将其他数据导入 Azure Cosmos 帐户。You can now import additional data to your Azure Cosmos account.