Connecting to the Cosmos DB account

The first step is to connect to the Cosmos DB account that we already created in the previous exercise, as follows:

  1. Open Visual Studio and create a new Console App (.NET) project.
  2. Name the project PacktCosmosApp.
  3. Right-click your project in the Solution Explorer and select Manage NuGet packages.
  4. Select Browse, search for Microsoft.Azure.Cosmos, and install the package.
  5. Open Program.cs and replace the references with the following:
using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Cosmos;
  1. Add the following variables in the Program.cs method:
 // Azure Cosmos DB endpoint.
private static readonly string EndpointUri = "<your endpoint here>";
// Primary key for the Azure Cosmos account.
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 name of the database and container we will create
private string databaseId = "FamilyDatabase";
private string containerId = "FamilyContainer";
  1. Now, go back to the Azure portal. Navigate to the Cosmos DB that we created in the previous step and under Settings, select Keys. Copy both the keys:

  1. In Program.csreplace <your endpoint here> with the URI that you've copied. Then, replace <your primary key> with the primary key you just copied.

Replace the Main() method with the following:

 public static async Task Main(string[] args)
{
}
  1. Below the Main method, add a new asynchronous task called GetStartedDemoAsync, which instantiates our new CosmosClient. We use GetStartedDemoAsync as the entry point that calls methods that operate on Azure Cosmos DB resources:
 public async Task GetStartedDemoAsync()
{
this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
}
  1. Add the following code to run the GetStartedDemoAsync synchronous task from your Main method:
 public static async Task Main(string[] args)
{
try
{
Console.WriteLine("Beginning operations... ");
Program p = new Program();
await p.GetStartedDemoAsync();

}
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 demo, press any key to exit.");
Console.ReadKey();
}
}

If you now run the application, the console will display the message: End of demo, press any key to exit. This means that the application successfully connected to the Cosmos DB account.

Now that we've successfully connected to the Cosmos DB account, we can create a new database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset