演習: 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. [エクスプローラー] ペインの 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();
    }
    

データベースを作成する

CosmosAsync メソッドの後に CreateDatabaseAsync メソッドをコピーして貼り付けます。 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);
}

コンテナーを作成する

CreateDatabaseAsync メソッドの下に CreateContainerAsync メソッドをコピーして貼り付けます。

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 portal を開いて、Azure Cosmos DB リソースに移動し、データ エクスプローラーを使用してデータベースとコンテナーを表示します。

Azure リソースをクリーンアップする

これで、次のコマンドを実行して、az204-cosmos-rg リソース グループをアカウントから安全に削除できるようになりました。

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