Angular 4 Azure Cosmos DocumentDB CRUD Application

Share this

In this article, you will learn how to create an Angular 4 Azure Cosmos DocumentDB CRUD application using ASP.NET Web API.

In my previous post C# Unit Testing with Moq, I extended my previous Angular 4 CRUD application developed in ASP.NET Web API and Entity Framework to include Unit Tests using a mocking framework MoQ.

In this article, I will use the source code from my previous article and replace the traditional SQL Server database with Azure Cosmos DB using DocumentDB  which is a NoSQL database and implement the CRUD operations on the Azure Cosmos DocumentDB.

Source Code for the article can be found on GitHub Repo :

https://github.com/sudipta-chaudhari/Azure_Cosmos_DocumentDB_ASPNET_WebApi_Angular4_CRUD

If you have no idea about Azure Cosmos DocumentDB, please refer to the Microsoft article https://docs.microsoft.com/en-us/azure/cosmos-db/introduction for in-depth information.

For modelling document data for NoSQL databases, please refer to this Mirosoft article https://docs.microsoft.com/en-us/azure/cosmos-db/introduction for in-depth information.

Our old database schema was as displayed in the below ER diagram.

Angular4_CRUD_EntityDataModel

New NoSQL JSON model for our application is as below.

The “Id” attribute in the JSON model above has been skipped as it will be auto generated by Azure Cosmos DocumentDB as a GUID string.

(1) Create Azure Cosmos DocumentDB, Collection & Document using Azure Portal

Login to Azure portal https://portal.azure.com. Navigate to ‘More Services’, then search for ‘Cosmos DB’. You will see the screen similar to the screenshot below.

AzurePortal_CosmosDB_Search

Select ‘Azure Cosmos DB’ option. This will bring you to the page where you can create a new Cosmos DB. This page also shows the existing Cosmos DB’s created.

AzurePortal_CosmosDB_AddNew_ViewExisting

Click on the “Add” button which will bring up a section where you need to enter the details for creating a new Cosmos DB as shown in the below screenshot.

AzurePortal_CosmosDB_CreateNew

In the below screenshot, please provide the details as below

  • ID : should be unique across. Azure will check this and if the ‘ID’ already exists i.e. a Cosmos DB has already been created previously, this will be reported to the user and the user will be asked to choose a different ID.
  • API : From ‘API’ drop down, please select ‘SQL (DocumentDB)’.
  • Subscription : Choose your appropriate subscription where you want to create Cosmos DB.
  • Resource Group : Provide details for a new Resource group to be created or choose and existing Resource Group.
  • Location : Choose an appropriate location
  • Enable geo-redundancy : Click this check box to enable geo-redundancy

After providing the above information, in some time the Azure Cosmos DocumentDB will be created and an navigating to this newly created resource, you will see a page as shown in the below screenshot where the database URI is : https://inventory-db.documents.azure.com:443/

AzurePortal_CosmosDB

The Azure Cosmos DocumentDB URI is in a standard format https://.documents.azure.com:443 where is the database name chosen by you.

Click ‘Overview’ section from the left hand menu to navigate to the home screen of your database. From the top of the screen, click ‘Add Collection’ button which will bring up a screen to enter the collection information. Enter the values as shown in below screenshot and then click ‘OK’ button at the bottom to create the collection.

AzurePortal_CosmosDB_AddCollection

Now your collection is created and should be visible under the “Overview” section. Now from the left hand menu, click “Data Explorer”, navigate to “Documents” under your database and collection tree view and click the “New Document” button. In the right had side editor,  add the JSON as shown in the below screenshot and click “Save” button.

AzurePortal_CosmosDB_NewDocument

After clicking ‘Save’ button, click the auto generated id under “id” section which will display the newly created document with the auto generated fields inserted in the document as shown in below screenshot.

AzurePortal_CosmosDB_NewDocument_IDAutoGenerated

Now click the ‘Keys’ section from the left hand menu. Here you will see the URI, Primary Key, Secondary Key, Primary Connection String and Secondary Connecting String as shown in the screenshot below.

AzurePortal_CosmosDB_Keys

Copy these settings as we will be using the Primary Account Key and URI and add them to web.config file’s section keys.

This complete the creation of Azure Cosmos DocumentDB, creating collection and adding a sample document.

(2) Add web.config keys

Add the below keys to web.config file under “appSettings” section

The “CosmosDBKey” attribute’s value is the Primary Key value which was obtained in Step (1).

(3) Add Microsoft.Azure.DocumentDB package

Open the existing solution from my previous post C# Unit Testing with Moq in Visual Studio, right click ‘References’ and select ‘NuGet Packages’. Add ‘Microsoft.Azure.DocumentDB’ package to the solution.

(4) Update View Model class

Under application root path’s “Models” folder, modify the ViewModel class named ProductJSON.cs as shown below.

The change that has been made in this view model class is the Id property which was of integer type has been changed to String type now. Earlier, SQL Server database Product table had the Id property as Integer which was the table’s primary key. ProductJson.cs Id property of type integer mapped to this primary key field. Since, the DocumentDB’s document has the auto generated id property of type string, Id property of the ViewModel class has been changed to data type string. Also, [JsonProperty(PropertyName="id")] has been mapped to Id property as DocumentDB’s document has the auto generated property has lower case “id”.

(5) Create Generic Repository class for interacting with Azure Cosmos DocumentDB

Under application root path’s “Repositories” folder, add a new file named DocumentDBRepository.cs with the code as shown below.

This generic class has all the methods for CRUD operations to be performed against the Azure Cosmos DocumentDB. As this class is generic, it can be used against any other view model class other than ProductJSON.cs to perform CRUD operations against any other DocumentDB Collection.

  • Initialize method creates a DocumentClient class instance by using the URI and Primary Key by reading the values from appSettings. The instance is then stored in a private static field in this repository.
  • CreateDatabaseIfNotExistsAsync method checks whether the database that we are going to use in this application exists or not. If it doesn’t exist, then create it.
  • CreateCollectionIfNotExistsAsync method checks whether the collection that we are going to use in this application exists or not. If it doesn’t exist, then create it.
  • GetItemAsync method retrieves a document from the database by document’s id
  • GetItemsAsync method retrieves all the documents from the collection
  • CreateItemAsync method create a new document in the collection
  • UpdateItemAsync method updates an existing document in the collection by id
  • DeleteItemAsync method deletes an existing document in the collection by id

(6) Initialize DocumentDBRepository in global.asax Application_Start() method

Initialize DocumentDBRepository in Global.asax Application_Start() method as shown in below code snippet.

(7) Changes in Angular app’s typescript model, component and data service

Update product.ts as shown in below code snippet

Modify dataService.ts file’s addProduct, updateProduct and deleteProduct methods as shown below.

In productComponent.ts file, update the editProduct, updateProduct and deleteProduct methods as shown below.

(8) Modify WebAPI Controller’s API methods 

Comment out ProductController.cs old api methods and replace this with new api methods as follows.

(9) Comment out old Repository and UnitTest code 

Comment out all the code from the below mentioned files:-

  • ProductRepository.cs as this code has now been replaced by DocumentDBRepository.cs
  • Angular4WebApiTests.cs as these were the unit tests Mocking the ProductRepository.cs methods

(10) Run the application and view results of CRUD Operations

Display Products (CRUD)

Angular4_CRUD_DisplayProducts

Add Product (CRUD)

Angular4_CRUD_AddProduct

Update Product (CRUD)

Angular4_CRUD_EditProduct

Delete Product (CRUD)

Angular4_CRUD_DeleteProduct

Hope you followed the article. If you have any comments, questions or suggestions, leave a message and I will try to respond at my earliest.


Share this

2 thoughts on “Angular 4 Azure Cosmos DocumentDB CRUD Application”

  1. Hi Sudita, in Which version of visual Studio it was implemented?
    i taken code from gitHub, when i opened it in Visual Studioi 2015, the references are having yellow symbols. can you please tell me how to get ride of yellow symbols.

    1. I had created this application using VS 2017. For the yellow symbols on references, try restoring NuGet packages.

Leave a Reply