快速入门:使用 .NET SDK 和 Azure Cosmos DB 的 API for MongoDB 构建 Xamarin.Forms 应用QuickStart: Build a Xamarin.Forms app with .NET SDK and Azure Cosmos DB's API for MongoDB

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.

本快速入门演示了如何使用 Azure 门户创建 Cosmos 帐户并为其配置 Azure Cosmos DB 的用于 MongoDB 的 API、文档数据库和集合。This quickstart demonstrates how to create a Cosmos account configured with Azure Cosmos DB's API for MongoDB, document database, and collection using the Azure portal. 然后,使用 MongoDB.NET 驱动程序构建 Xamarin.Forms 待办事项应用。You'll then build a todo app Xamarin.Forms app by using the MongoDB .NET driver.

运行示例应用的先决条件Prerequisites to run the sample app

若要运行该示例,需要 Visual StudioVisual Studio for Mac 和有效的 Azure CosmosDB 帐户。To run the sample, you'll need Visual Studio or Visual Studio for Mac and a valid Azure CosmosDB account.

如果没有 Visual Studio,请在使用安装程序安装具有 .NET 的移动开发后,下载 Visual Studio 2019 Community EditionIf you don't already have Visual Studio, download Visual Studio 2019 Community Edition with the Mobile development with .NET workload installed with setup.

如果想要使用 Mac,请下载 Visual Studio for Mac 并运行安装程序。If you prefer to work on a Mac, download Visual Studio for Mac and run the setup.

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

创建数据库帐户Create a database account

  1. 在新窗口中,登录到 Azure 门户In a new window, sign in to the Azure portal.

  2. 在左菜单中,依次单击“创建资源”、“数据库”,然后在“Azure Cosmos DB”下单击“创建”。In the left menu, click Create a resource, click Databases, and then under Azure Cosmos DB, click Create.

    Azure 门户的屏幕截图,其中突出显示了“更多服务”和“Azure Cosmos DB”

  3. 在“创建 Azure Cosmos DB 帐户”页中,输入新 Azure Cosmos DB 帐户的设置。In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    设置Setting Value DescriptionDescription
    订阅Subscription 订阅Your subscription 选择要用于此 Azure Cosmos DB 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    资源组Resource Group 新建Create new

    然后输入在 ID 中提供的同一唯一名称Then enter the same unique name as provided in ID
    选择“新建”。Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource-group name for your account. 为简单起见,可以使用与 ID 相同的名称。For simplicity, use the same name as your ID.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 由于 documents.azure.cn 字符串将追加到所提供的 ID 后面以创建 URI,因此,请使用唯一的 ID。Because documents.azure.cn is appended to the ID that you provide to create your URI, use a unique ID.

    该 ID 只能使用小写字母、数字和连字符 (-) 字符。The ID can use only lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3 到 31 个字符之间。It must be between 3 and 31 characters in length.
    APIAPI Azure Cosmos DB 的用于 MongoDB 的 APIAzure Cosmos DB's API for MongoDB API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据库的 Core (SQL)、适用于图形数据库的 Gremlin、适用于文档数据库的用于 Azure Cosmos DB 的 API MongoDB、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB's API MongoDB for document databases, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    选择“MongoDB”,因为本快速入门将创建使用 MongoDB 的表。Select MongoDB because in this quickstart you are creating a table that works with the MongoDB.
    位置Location 选择离用户最近的区域Select the region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。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.

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

    Azure Cosmos DB 的“新建帐户”页

  4. 创建帐户需要几分钟时间。The account creation takes a few minutes. 等待门户中显示“祝贺你!具有 MongoDB 的网络协议兼容性的 Cosmos 帐户已准备就绪”页面。Wait for the portal to display the Congratulations! Your Cosmos account with wire protocol compatibility for MongoDB is ready page.

    Azure 门户“通知”窗格

本文中所述的示例与 MongoDB.Driver 版本 2.6.1 兼容。The sample described in this article is compatible with MongoDB.Driver version 2.6.1.

克隆示例应用Clone the sample app

首先,从 GitHub 下载示例应用。First, download the sample app from GitHub. 这会实施一个包含 MongoDB 文档存储模型的待办事项应用。It implements a todo app with MongoDB's document storage model.

  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-mongodb-xamarin-getting-started.git

如果不想使用 git,也可以下载 ZIP 文件格式的项目If you don't wish to use git, you can also download the project as a ZIP file

查看代码Review the code

此步骤是可选的。This step is optional. 如果有意了解如何使用代码创建数据库资源,可以查看以下代码片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 否则,可以直接跳转到更新连接字符串Otherwise, you can skip ahead to Update your connection string.

以下代码片段全部摘自 MongoService 类,可在以下路径找到:src/TaskList.Core/Services/MongoService.cs。The following snippets are all taken from the MongoService class, found at the following path: src/TaskList.Core/Services/MongoService.cs.

  • 初始化 Mongo 客户端。Initialize the Mongo Client.

    MongoClientSettings settings = MongoClientSettings.FromUrl(
        new MongoUrl(APIKeys.ConnectionString)
    settings.SslSettings =
        new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
    MongoClient mongoClient = new MongoClient(settings);
  • 检索对数据库和集合的引用。Retrieve a reference to the database and collection. 如果它们尚不存在,MongoDB.NET SDK 会自动创建该数据库和集合。The MongoDB .NET SDK will automatically create both the database and collection if they do not already exist.

    string dbName = "MyTasks";
    string collectionName = "TaskList";
    var db = mongoClient.GetDatabase(dbName);
    var collectionSettings = new MongoCollectionSettings {
        ReadPreference = ReadPreference.Nearest
    tasksCollection = db.GetCollection<MyTask>(collectionName, collectionSettings);
  • 以列表形式检索所有文档。Retrieve all documents as a List.

    var allTasks = await TasksCollection
                    .Find(new BsonDocument())
  • 查询特定文档。Query for particular documents.

    public async Task<List<MyTask>> GetIncompleteTasksDueBefore(DateTime date)
        var tasks = await TasksCollection
                        .Where(t => t.Complete == false)
                        .Where(t => t.DueDate < date)
        return tasks;
  • 创建任务并将其插入到集合中。Create a task and insert it into the collection.

    public async Task CreateTask(MyTask task)
        await TasksCollection.InsertOneAsync(task);
  • 更新集合中的任务。Update a task in a collection.

    public async Task UpdateTask(MyTask task)
        await TasksCollection.ReplaceOneAsync(t => t.Id.Equals(task.Id), task);
  • 从集合中删除任务。Delete a task from a collection.

    public async Task DeleteTask(MyTask task)
        await TasksCollection.DeleteOneAsync(t => t.Id.Equals(task.Id));

更新连接字符串Update your connection string

现在返回到 Azure 门户,获取连接字符串信息,并将其复制到应用。Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. Azure 门户的 Azure Cosmos DB 帐户的左侧导航栏中,单击“连接字符串” ,并单击“读写密钥” 。In the Azure portal, in your Azure Cosmos DB account, in the left navigation click Connection String, and then click Read-write Keys. 在后续步骤中,将使用屏幕右侧的复制按钮复制“主连接字符串”。You'll use the copy buttons on the right side of the screen to copy the Primary Connection String in the next steps.

  2. 打开 TaskList.Core 项目的 Helpers 目录中的 APIKeys.cs 文件。Open the APIKeys.cs file in the Helpers directory of the TaskList.Core project.

  3. 从门户复制“主连接字符串”值(使用复制按钮),并将其设置为 APIKeys.cs 文件中 ConnectionString 字段的值。 Copy your primary connection string value from the portal (using the copy button) and make it the value of the ConnectionString field in your APIKeys.cs file.

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

运行应用程序Run the app

Visual Studio 2019Visual Studio 2019

  1. 在 Visual Studio 中,右键单击解决方案资源管理器 中的每个项目,并单击“管理 NuGet 包” 。In Visual Studio, right-click on each project in Solution Explorer and then click Manage NuGet Packages.
  2. 单击“还原所有 NuGet 包” 。Click Restore all NuGet packages.
  3. 右键单击“TaskList.Android”,并选择“设为启动项目”。 Right click on the TaskList.Android and select Set as startup project.
  4. 按 F5 开始调试应用程序。Press F5 to start debugging the application.
  5. 如果想要在 iOS 上运行,首先请将计算机连接到 Mac(参阅操作说明)。If you want to run on iOS, first your machine is connected to a Mac (here are instructions on how to do so).
  6. 右键单击“TaskList.iOS”项目,并选择“设为启动项目”。 Right click on TaskList.iOS project and select Set as startup project.
  7. 单击 F5 开始调试应用程序。Click F5 to start debugging the application.

Visual Studio for MacVisual Studio for Mac

  1. 在平台下拉列表中,根据使用的平台选择“TaskList.iOS”或“TaskList.Android”。In the platform dropdown list, select either TaskList.iOS or TaskList.Android, depending which platform you want to run on.
  2. 按 cmd+Enter 开始调试应用程序。Press cmd+Enter to start debugging the application.

在 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

不再需要 Web 应用和 Azure Cosmos DB 帐户以后,即可删除创建的 Azure 资源,避免产生更多费用。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. 在 Azure 门户中,选择最左侧的“资源组”。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.

    Azure 门户中的指标

  3. 在新窗口中选择“删除资源组”。In the new window, select Delete resource group.

    Azure 门户中的指标

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

后续步骤Next steps

本快速入门已介绍如何创建 Azure Cosmos DB 帐户和使用 API for MongoDB 运行 Xamarin.Forms 应用。In this quickstart, you've learned how to create an Azure Cosmos DB account and run a Xamarin.Forms app using the API for MongoDB. 现在可以将其他数据导入 Cosmos DB 帐户。You can now import additional data to your Cosmos DB account.