練習:使用 Microsoft .NET SDK v3 建立資源

已完成

在此練習中,您會建立主控台應用程式,以在 Azure Cosmos DB 中執行下列作業:

  • 連線至 Azure Cosmos DB 帳戶
  • 建立資料庫
  • 建立容器

必要條件

設定

針對練習執行下列動作來準備 Azure 和本地環境。

連線到 Azure

  1. 啟動 Visual Studio Code 並從頂端應用程式列選取 [終端機],然後選擇 [新增終端機],以開啟終端機視窗。

  2. 使用下列命令登入 Azure。 此時會開啟瀏覽器視窗,讓您選擇要用來登入的帳戶。

    az login
    

在 Azure 中建立資源

  1. 針對本練習所需的資源建立資源群組。 將 <myLocation> 取代為您附近的區域。

    az group create --location <myLocation> --name az204-cosmos-rg
    
  2. 建立 Azure Cosmos DB 帳戶。 將 <myCosmosDBacct> 取代為識別您 Azure Cosmos DB 帳戶的唯一名稱。 名稱只能包含小寫字母、數字及連字號 (-) 字元。 其長度必須介於 3 到 31 個字元之間。 此命令需要幾分鐘的時間來完成。

    az cosmosdb create --name <myCosmosDBacct> --resource-group az204-cosmos-rg
    

    記錄 JSON 回應中顯示的 documentEndpoint,以供稍後在練習中使用。

  3. 使用下列命令擷取帳戶的主索引鍵。 從命令結果中記錄 primaryMasterKey,以用於程式碼。

    # Retrieve the primary key
    az cosmosdb keys list --name <myCosmosDBacct> --resource-group az204-cosmos-rg
    

設定主控台應用程式

既然所需的資源已部署至 Azure,下一個步驟是使用 Visual Studio Code 中的同一個終端視窗來設定主控台應用程式。

  1. 建立專案的資料夾並進行變更。

    md az204-cosmos
    cd az204-cosmos
    
  2. 建立 .NET 主控台應用程式。

    dotnet new console
    
  3. 使用下列命令來在 Visual Studio Code 中開啟目前資料夾。 選項 -r 會開啟資料夾,而不啟動新的 Visual Studio Code 視窗。

    code . -r
    
  4. 選取 [Explorer] 窗格中的 Program.cs 檔案,以在編輯器中開啟檔案。

建置主控台應用程式

開始將套件和程式碼新增至專案。

使用陳述式新增套件

  1. 在 Visual Studio Code 中開啟終端,並使用下列命令將套件 Microsoft.Azure.Cosmos 新增至專案。

    dotnet add package Microsoft.Azure.Cosmos
    
  2. 刪除 Program.cs 檔案中的任何現有程式碼,並新增 using Microsoft.Azure.Cosmos 陳述式。

    using Microsoft.Azure.Cosmos;
    

新增程式碼以連線到 Azure Cosmos DB 帳戶

  1. using 陳述式後面新增下列程式碼片段。 程式碼片段會將常數和變數新增至類別,並新增一些錯誤檢查。 請務必遵循程式碼註解中的指示取代 EndpointUriPrimaryKey 的預留位置值。

    public class Program
    {
        // Replace <documentEndpoint> with the information created earlier
        private static readonly string EndpointUri = "<documentEndpoint>";
    
        // Set variable to the Primary Key from earlier.
        private static readonly string PrimaryKey = "<your primary key>";
    
        // The Cosmos client instance
        private CosmosClient cosmosClient;
    
        // The database we will create
        private Database database;
    
        // The container we will create.
        private Container container;
    
        // The names of the database and container we will create
        private string databaseId = "az204Database";
        private string containerId = "az204Container";
    
        public static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Beginning operations...\n");
                Program p = new Program();
                await p.CosmosAsync();
    
            }
            catch (CosmosException de)
            {
                Exception baseException = de.GetBaseException();
                Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }
            finally
            {
                Console.WriteLine("End of program, press any key to exit.");
                Console.ReadKey();
            }
        }
        //The sample code below gets added below this line
    }
    
  2. Main 方法下方,新增名為 CosmosAsync 的非同步工作,該工作會具現化我們新的 CosmosClient,並新增程式碼來呼叫稍後要新增的方法,以建立資料庫和容器。

    public async Task CosmosAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    
        // Runs the CreateDatabaseAsync method
        await this.CreateDatabaseAsync();
    
        // Run the CreateContainerAsync method
        await this.CreateContainerAsync();
    }
    

建立資料庫

CreateDatabaseAsync 方法複製並貼到 CosmosAsync 方法之後。 如果目前沒有資料庫,CreateDatabaseAsync 會建立 ID 為 az204Database 的新資料庫。

private async Task CreateDatabaseAsync()
{
    // Create a new database using the cosmosClient
    this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
    Console.WriteLine("Created Database: {0}\n", this.database.Id);
}

建立容器

CreateContainerAsync 方法複製並貼到 CreateDatabaseAsync 方法下方。

private async Task CreateContainerAsync()
{
    // Create a new container
    this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, "/LastName");
    Console.WriteLine("Created Container: {0}\n", this.container.Id);
}

執行應用程式

  1. 儲存您的工作,並在 Visual Studio Code 的終端機中執行 dotnet build 命令來檢查是否有任何錯誤。 如果建置成功,請執行 dotnet run 命令。 主控台會顯示下列訊息。

    Beginning operations...
    
    Created Database: az204Database
    
    Created Container: az204Container
    
    End of program, press any key to exit.
    
  2. 開啟 Azure 入口網站,瀏覽至 Azure Cosmos DB 資源,然後使用資料總管來檢視資料庫和容器,以確認結果。

清除 Azure 資源

您現在可以執行下列命令,從您的帳戶安全地刪除 [az204-cosmos-rg] 資源群組。

az group delete --name az204-cosmos-rg --no-wait