快速入門:使用 .NET SDK 和 Azure Cosmos DB 的 MongoDB API 建置 Xamarin.Forms 應用程式QuickStart: Build a Xamarin.Forms app with .NET SDK and Azure Cosmos DB's API for MongoDB

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft’s globally 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 global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

此快速入門示範如何使用 Azure 入口網站建立使用 Azure Cosmos DB MongoDB API 所設定的 Cosmos 帳戶、文件資料庫和集合。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 驅動程式建置 ToDo 應用程式的 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,請下載 Visual Studio 2019 Community Edition,其在安裝時會一併安裝使用 .NET 進行行動裝置開發的工作負載。If 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 free 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, select Create a resource, select Databases, and then under Azure Cosmos DB, select 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 說明Description
    SubscriptionSubscription 您的訂用帳戶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

    然後輸入識別碼中所提供的同一個唯一名稱Then enter the same unique name as provided in ID
    選取 [建立新的] 。Select Create new. 然後為您的帳戶輸入新的資源群組名稱。Then enter a new resource-group name for your account. 為求簡化,請使用和識別碼相同的名稱。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.com 會附加到您所提供的識別碼以建立 URI,請使用唯一識別碼。Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique 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 適用於 MongoDB 的 Azure Cosmos DB 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 MongoDB API (適用於文件資料庫)、「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.
    LocationLocation 選取最接近使用者的區域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 的文件儲存體模型實作 ToDo 應用程式。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 終端機視窗 (例如 git bash),並使用 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())
                    .ToListAsync();
    
  • 查詢特定文件。Query for particular documents.

    public async Task<List<MyTask>> GetIncompleteTasksDueBefore(DateTime date)
    {
        var tasks = await TasksCollection
                        .AsQueryable()
                        .Where(t => t.Complete == false)
                        .Where(t => t.DueDate < date)
                        .ToListAsync();
    
        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.

    選取要刪除的資源群組

  3. 在新視窗中,選取 [刪除資源群組] 。In the new window, 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 DB 帳戶,以及如何使用適用於 MongoDB 的 API 來執行 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.