Share the love

Here are the steps and .NET code to connect to Cosmos DB and fetch data using Managed Service Identity (MSI) from an Azure App Service:

  1. Create a Cosmos DB account and a container.
  2. Create a Managed Service Identity (MSI) for your Azure App Service. You can do this by going to the App Service in the Azure portal, navigating to the “Identity” tab, and turning on the “System assigned” managed identity.
  3. Grant the MSI access to your Cosmos DB account. You can do this by going to your Cosmos DB account in the Azure portal, navigating to the “Access control (IAM)” tab, and adding a new role assignment. In the “Add a role assignment” section, search for the MSI you created in step 2 and give it the “Cosmos DB Account Reader” role.
  4. Install the Microsoft.Azure.Cosmos.Table NuGet package in your App Service.
  5. Use the following code snippet to connect to the Cosmos DB container and fetch data using the MSI:
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Azure.Services.AppAuthentication;
using System.Linq;

public class CosmosDbHelper
{
    public static async Task<List<T>> GetData<T>(string tableName) where T : TableEntity, new()
    {
        var azureServiceTokenProvider = new AzureServiceTokenProvider();
        var storageCredentials = new StorageCredentials(azureServiceTokenProvider);
        var storageAccount = new CloudStorageAccount(storageCredentials, "your-cosmosdb-account-name", "your-cosmosdb-endpoint-suffix", useHttps: true);
        var tableClient = storageAccount.CreateCloudTableClient();
        var table = tableClient.GetTableReference(tableName);
        var query = new TableQuery<T>();
        var segment = await table.ExecuteQuerySegmentedAsync(query, null);
        return segment.Results;
    }
}

In this example, GetData method of the CosmosDbHelper class connects to the Cosmos DB container and fetches the data using the AzureServiceTokenProvider and StorageCredentials classes. It also uses CloudStorageAccount and CloudTableClient classes to connect to the Cosmos DB container. It uses the TableQuery class to create a query to fetch data from the container and the ExecuteQuerySegmentedAsync method to execute the query and return the results.

You can call this method by passing the name of the table you want to fetch data from:

var data = await CosmosDbHelper.GetData<YourTableType>("your-table-name");

Also, make sure to replace your-cosmosdb-account-name, your-cosmosdb-endpoint-suffix and YourTableType with the correct values for your Cosmos DB account and the table you want to fetch data from.

Too Easy! Here’s a bit more complex example:

using Microsoft.Azure.Cosmos.Table;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Linq;
using System.Threading.Tasks;

public class CosmosDbHelper
{
    public static async Task<List<T>> GetData<T>(string tableName, string partitionKey, string filter) where T : TableEntity, new()
    {
        var azureServiceTokenProvider = new AzureServiceTokenProvider();
        var storageCredentials = new StorageCredentials(azureServiceTokenProvider);
        var storageAccount = new CloudStorageAccount(storageCredentials, "your-cosmosdb-account-name", "your-cosmosdb-endpoint-suffix", useHttps: true);
        var tableClient = storageAccount.CreateCloudTableClient();
        var table = tableClient.GetTableReference(tableName);
        var query = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey));
        if(!string.IsNullOrEmpty(filter))
            query = query.Where(filter);
        var segment = await table.ExecuteQuerySegmentedAsync(query, null);
        var data = segment.Results;
        // perform any additional operations on the data
        return data;
    }
}

In this example, GetData method of the CosmosDbHelper class connects to the Cosmos DB container, and fetches the data using the AzureServiceTokenProvider and StorageCredentials classes. It also uses CloudStorageAccount and CloudTableClient classes to connect to the Cosmos DB container. It uses the TableQuery class to create a query to fetch data from the container and the ExecuteQuerySegmentedAsync method to execute the query and return the results.

It also accepts partitionKey and filter as input, you can use partition key to filter the data from the table and filter is used to filter the data based on some condition.

Make sure to replace your-cosmosdb-account-name, your-cosmosdb-endpoint-suffix and YourTableType with the correct values for your Cosmos DB account and the table you want to fetch data from. Also, replace the partitionKey and filter with the appropriate values, if you don’t pass any value for filter it will fetch all the data from the table for provided partitionKey.

You can also use other filters like filtering based on timestamp, rowkey etc. based on your use-case.