Azure App Service, Azure Cloud, Azure Cosmos DB, Cloud Computing

How to use NoSQL Azure DocumentDB or Azure Cosmos DB in our Dot.net Applications: Part 6

I am putting together a series for people who are excited to bring Azure into their software development life cycle and use Azure cloud’s extensive services to their full potential.

In this series, I will cover as below:

  1. Getting Started with Azure Development, Create App Service Plan and Publish MVC project using Visual Studio
  2. Deployment Slots and Slot Swap on Azure App Service using Visual Studio and Azure SDK
  3. Remote debugging App Service using visual Studio, monitoring and configuring alerts
  4. Diagnostic logs, live stream, process explorer and KUDU
  5. How to use Azure SQL Database in Dot.net Applications
  6. How to use Azure DocumentDB or Azure Cosmos DB in our Dot.net Applications
  7. How to use Visual Studio Team Service to do continuous Integration and continuous delivery
  8. Azure storage data services types and how to store files in azure storage account 1/2
  9. Azure storage data services types and how to store files in azure storage account 2/2
  10. How to use Azure Functions and trigger on new image/blob creation in Azure Storage using BlobTrigger 1/2
  11. How to use Azure Functions and trigger on new image/blob creation in Azure Storage using BlobTrigger 2/2

If you do not know where to start, please check my blog post, which covers detail about getting subscription and setting up. In this series, we assume that you already have active Azure subscription and Visual Studio 2013 or later installed on your system.

6. How to use Azure DocumentDB or Azure Cosmos DB in our Dot.net Applications

Azure DocumentDB or Azure Cosmos DB is database for very low latency and immensely saleable applications, which have global audience and it provides native NOSQL support. Azure cosmos DB support storing and retrieving JSON object at scale.

During development you do not need to create a new instance of documentDB, visual studio provide you the emulator to use during development phase. To explore the possibilities, In our case, we will create Azure Cosmos DB / documentDB on azure and use it in our application that we are building in this series.

In Azure first we need to create an account for Azure Cosmos DB and then we can create collections and databases in it. Let us do just that.

Go to Azure Portal and Click on Add and search for documentDB | select Azure Cosmos DB and click on create.

Figure 1 Create Azure Cosmos DB

Now fill the form, select the API, Azure support multiple APIs like SQL API, MongoDB API, Graph API, Table API and Cassandra API, and choose the appropriate API, we are going for SQL API. This will create a new Azure Cosmos DB account for you.

For more info on APIs

Figure 2 Create Azure Cosmos DB

It may take some time to create it. Once created go to the resource | select your documentdb account | Quick start. Right now, we do not have any collection and we do not have any database. Firstly we will create new collection, and then create database in that collection, but we have a short cut to do just that, click on Create Items collection button. It will create the basic collection for you which will cost you around 0.033$ / hour and will give you 400 reads/sec. Read/sec defined as if the file is 1 kb size and 1 kb file read is represented as 1 RU  then 400 request could be read per second 400 RU/S and under 400 RU/S load, our current documentDB will work just fine. If the requests are, more the throttling will happen and latency will increase, in case of extreme throttling request timeout could happen. Writing operation will cost you more than reading, Writing the file of 1 Kb size will cost you 5 RUs as it is more expensive then read. You can check following link for more info

Figure 3 Create Items collection in Azure Cosmos DB

Click on Create “Items” collection” and then click on  download  button to get the code for TODOList sample Project, we will use this project as sample and will modify our existing project to communicate with the Azure Cosmos DB.

Now go to Collections | Browse you will see that it created new collection Items and database in it called ToDoList , all we have to do now is to integrate todo project we have downloaded, to our app that we are building in this series.

Figure 4 Azure Cosmos DB collections and database

Open the downloaded sample source code in the visual studio and run for few times and add some records. This will create some record in the database that we will see later and we will also clear some misconceptions about documentDB that many developers may have.

Figure 5 Run TodoList sample project

Open DocumentDBRepository, this is our main file, which is communicating with Azure Cosmos DB, and notice it is using , endpoint, authKey, database and collection app settings. We will copy the DocumentDBRepository.cs file and include appSettings to our exisitng application.

Figure 6 DocumentDBRepository

Make sure to install Microsoft.Azure.DocumentDB package through nugget.

Figure 7 Install Microsoft.Azure.DocumentDB

Make sure copy all the files highlighted and change _layout.cshtml file to include our Item controller also highlighted.

Figure 8 migrated the code

Also, make sure you copy below to Global.asax.cs | build  | check locally that there is no error while building or running, and publish the changes to App Service, we have already covered how to publish the source code to app service in previous posts.

DocumentDBRepository<todo.Models.Item>.Initialize();

Figure 9 Insert DocumentDBRepository initialize line

Now once your project run successfully, insert records few times by creating some tasks. Keep in mind that we can use To-do Items example to insert any JSON serializable object in the same collection even if the object do not relate with each other, DocumentDB is not limited to structure like table, you can insert any object of any type given that it is serializable to JSON or can be represented in JSON format.

Figure 10 insert few To-do items in documentDb

Sample code is also given below:

We can also verify the data is inserted through Azure Portal, Go to your Azure Cosmos DB | Collections | Document Explorer | click any item | you will see the data in document tab in JSON format.

{


“id”: “d2dc5626-e279-4390-b079-f6ba1a4af982”,


“name”: “test3”,


“description”: “test3”,


“isComplete”: false

}

Check for more information

At this point you are successfully integrated your existing project to use the Azure Cosmos DB.

Coming up next How to use Visual Studio Team Service to do continuous Integration and continuous delivery

 

11 thoughts on “How to use NoSQL Azure DocumentDB or Azure Cosmos DB in our Dot.net Applications: Part 6”

  1. Hi,
    What does it mean?
    Make sure copy all the files highlighted and change _layout.cshtml file to include our Item controller also highlighted.
    Copy those files from todo.sln to the current .sln? How to do that? Cheers.

    1. yes, you are right, You need to copy files from todo.sln to current.sln.
      This is very simple, All you need to do is to use add existing item options to add the items in you current solution, this way you need to go to file location of the items highlighted.

      There is an other way you can copy the files from todo.sln folder ( use Windows Explorer ) and paste in current.sln using windows explorer, now the added files will not show in the current.sln, you need to select solution and click on show all items and then the items which are not included in the sln will show, now right click on each item and select include.
      I hope this will answer your question, if you need more detail, pleas let me know.

      1. Thanks for your prompt reply and helpful tips.
        Newbie here, hope you can bear with me.
        Cheers.

  2. For DocumentDBRepository.Initialize(); that needs to be copied to Global.asax.cs on WebApplication1.sln, can only work if I use:
    todo.DocumentDBRepository.Initialize();
    If I just only use DocumentDBRepository.Initialize(); it gave:
    Severity Code Description Project File Line Suppression State
    Error CS0103 The name ‘DocumentDBRepository’ does not exist in the current context WebApplication1 F:\Data\VS\Solution1\WebApplication1\WebApplication1\Global.asax.cs 20 Active
    Is it correct for me to use my alternative so the system can understand to get the reference from todo Sln but how to make it fully running on WebApplication1.sln instead of using todo.sln
    Thanks for your guidance

    1. Please make sure to include the nugget package and reference in the application1 sln. For reference compare dll referenced and nugget packages in both solutions. I hope it would help.

      1. Hi,
        Thanks for the reply.
        Apparently after Adding existing item onto the WebApplication1.sln I needed to adjust all the name spaces on the copied files to reflect WebApplication1 as the namespace rather than todo as the namespace.
        Published and seems working fine, thanks

  3. Hi,
    In the article you have stated “Firstly we will create new collection, and then create database in that collection”. Does it mean that there is a collection and there could be multiple databases in that collection? If so from the MS document picture it shows the other way. Database has collections and collections have documents. Documents have attachments.
    Which one is correct?

      1. First we will have a Cosmos DB account, then you create a collection along with database and in the creation window you mention db.
        But in the portal when you see that Database and collection are on same level, we get confused.
        We create database first and then create collections in it.
        I am referring to the button create collection, which is also in the official documentation, if you want to create database you click on create collection.
        I hope this would clear up the confusion.

Leave a Reply