ASP.NET Core Web API and Microsoft Azure Cosmos DB emulator
Hello friends. In this blog, I would like to share some examples of creating WebAPI's using ASP.NET Core with Microsoft Azure Cosmos DB as the back end. You can download the Azure Cosmos Emulator from the Microsoft website.
The emulator is really helpful for development purposes as it creates a local environment. One major advantage is that developers can develop and test their applications locally without creating an Azure subscription. Once the testing is completed successfully, the cloud based Azure cosmos account comes into picture.
In this example, I am creating a user using the API. For this purpose, I am using Microsoft Visual Studio 2019 and selected ".Net Core" project type.
Then selected "Web API" as the project template.
The project will be created with the below structure.
In order to connect to the Azure Cosmos, we need to add the below Nuget package and we are all set to start the development.
In this example, I am going to add a user into the Azure Cosmos DB through the ASP.NET Core WebAPI.
The user class will have the below fields.
User.cs
public Int64 UserID;
public string Name;
public string Email;
public string Password;
public DateTime LastUpdatedDate;
I've created a controller class named "UserController.cs" which includes the Web API.
[HttpPost]
[Route("CreateUser")]
public async void Post([FromBody]Users user)
{
try
{
await DocumentDBRepository<Users>.CreateItemAsync(user, Constants.USERS);
}
catch (Exception ex)
{
ErrorLogHelper.InsertLog((user.Email != null ? user.Email.Trim() : string.Empty), ex.Message, ex.StackTrace);
}
}
Here the DocumentDBRepository is the helper class that interacts with the Database.
I've the below namespaces added into the DocumentDBRepository class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
Then we need to mention the endpoint of the Azure Cosmos emulator in the project. You can get this endpoint from the locally installed emulator software. Open the emulator and it will open in the browser and will display the URI and Key. You can copy that and place in your project for connecting to the database.
private static readonly string Endpoint = "https://localhost:8081";
private static readonly string Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
We need to have a DatabaseID or name.
private static readonly string DatabaseId = "CSDB";
We need to have a CollectionID for the users which holds the user data.
private static readonly string CollectionId = "Users";
The below are the methods in the DocumentDBRepository class.
public static async Task<Document> CreateItemAsync(T item, string actionType)
{
if (client == null)
Initialize();
return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, actionType), item);
}
We need to initialize the connection before performing any actions. The below method will help here.
public static void Initialize()
{
client = new DocumentClient(new Uri(Endpoint), Key);
CreateDatabaseIfNotExistsAsync().Wait();
CreateUsersCollectionIfNotExistsAsync().Wait();
}
private static async Task CreateDatabaseIfNotExistsAsync()
{
try
{
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
}
else
{
throw;
}
}
}
private static async Task CreateUsersCollectionIfNotExistsAsync()
{
try
{
await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, Constants.USERS));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(DatabaseId),
new DocumentCollection { Id = Constants.USERS },
new RequestOptions { OfferThroughput = 1000 });
}
else
{
throw;
}
}
}
The below is the screen to Azure Cosmos DB emulator where we can see the users created through the Web API.
Thankyou all..
The emulator is really helpful for development purposes as it creates a local environment. One major advantage is that developers can develop and test their applications locally without creating an Azure subscription. Once the testing is completed successfully, the cloud based Azure cosmos account comes into picture.
In this example, I am creating a user using the API. For this purpose, I am using Microsoft Visual Studio 2019 and selected ".Net Core" project type.
Then selected "Web API" as the project template.
The project will be created with the below structure.
In order to connect to the Azure Cosmos, we need to add the below Nuget package and we are all set to start the development.
In this example, I am going to add a user into the Azure Cosmos DB through the ASP.NET Core WebAPI.
The user class will have the below fields.
User.cs
public Int64 UserID;
public string Name;
public string Email;
public string Password;
public DateTime LastUpdatedDate;
I've created a controller class named "UserController.cs" which includes the Web API.
[HttpPost]
[Route("CreateUser")]
public async void Post([FromBody]Users user)
{
try
{
await DocumentDBRepository<Users>.CreateItemAsync(user, Constants.USERS);
}
catch (Exception ex)
{
ErrorLogHelper.InsertLog((user.Email != null ? user.Email.Trim() : string.Empty), ex.Message, ex.StackTrace);
}
}
Here the DocumentDBRepository is the helper class that interacts with the Database.
I've the below namespaces added into the DocumentDBRepository class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
Then we need to mention the endpoint of the Azure Cosmos emulator in the project. You can get this endpoint from the locally installed emulator software. Open the emulator and it will open in the browser and will display the URI and Key. You can copy that and place in your project for connecting to the database.
private static readonly string Endpoint = "https://localhost:8081";
private static readonly string Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
We need to have a DatabaseID or name.
private static readonly string DatabaseId = "CSDB";
We need to have a CollectionID for the users which holds the user data.
private static readonly string CollectionId = "Users";
The below are the methods in the DocumentDBRepository class.
public static async Task<Document> CreateItemAsync(T item, string actionType)
{
if (client == null)
Initialize();
return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, actionType), item);
}
We need to initialize the connection before performing any actions. The below method will help here.
public static void Initialize()
{
client = new DocumentClient(new Uri(Endpoint), Key);
CreateDatabaseIfNotExistsAsync().Wait();
CreateUsersCollectionIfNotExistsAsync().Wait();
}
private static async Task CreateDatabaseIfNotExistsAsync()
{
try
{
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
}
else
{
throw;
}
}
}
private static async Task CreateUsersCollectionIfNotExistsAsync()
{
try
{
await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, Constants.USERS));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(DatabaseId),
new DocumentCollection { Id = Constants.USERS },
new RequestOptions { OfferThroughput = 1000 });
}
else
{
throw;
}
}
}
The below is the screen to Azure Cosmos DB emulator where we can see the users created through the Web API.
Thankyou all..
Very nice article, really helpful
ReplyDeleteHi, This is a great article. Loved your efforts on it buddy. Thanks for sharing this with us. DP-060T00: Migrate NoSQL workloads to Azure Cosmos DB
ReplyDelete