Sunday 9 September 2018

Azure Document Db CRUD operation



Introduction This article explains how to create documents in SQL (DocumentDB) API. Before starting, we need to understand what is documentDb and how it works. SQL (DocumentDB) API is one of the APIs that comes under Azure COSMOS DB.
Azure Cosmos DbThis is one of the most important parts of Microsoft Azure. Azure Cosmos Db has a globally distributed database. It has lots of features available like global distribution, which means turnkey distribution in more than 30 regions, you can scale it horizontally (scale storage and throughput), low latency, which means it gives high performance (99.999% read in < 10ms and 99.99% write in <15ms), also it is highly available.
Cosmos Db has the following multi-model APIs,
  1. SQL API(DocumentDB)
  2. MongoDB API
  3. Gremlin API(GraphDB)
  4. Table API
  5. Cassandra API
So, let’s start with DocumentDB
Azure Cosmos Db SQL API has all the features as mentioned above.
  1. Create Azure Cosmos DB database

    Click Create a resource > Databases > Azure Cosmos DB.




  1. Create a Cosmos DB account.
    • Enter the Account ID
    • API as SQL API
    • Subscription whatever you have
    • Resource Group. 
    • Location etc
                                   
  1. Now, we will create a collection. Collections are like containers in which we can create documents, and documents are JSON objects.
Enter the Database Id, Collection Id and throughput as shown in the below screenshot.           
We created resources manually over the Azure portal, you can also create them by coding. Let’s start the coding for creating documents into the ToDoList Collection.
  1. Create a console application. I have created it in the dot net core 2.0.
          

  5. Install NuGet for SQL API into DocumentDbDemo project. So we can connect with the Azure                document DB.
                            


         6. Get the connection string of cosmos DB (we have created earlier ) from the Azure portal.
                    
                           


    7. Create a appsetting.json file. I have created an environment specific file for the development environment. So we can check in the program file, and we will see in the code.
                       


    8. We will create a Config.cs class that will contain the properties to get the values of the appsettings.dev.json file.
  1. public class Config  
  2.     {  
  3.         public DocDbConnectionString docDb { get; set; }  
  4.     }  
  5.     public class DocDbConnectionString  
  6.     {  
  7.         public string EndPoint { get; set; }  
  8.         public string AuthKey { get; set; }  
  9.         public string Database { get; set; }  
  10.         public string Collection { get; set; }  
  11.     }   
  1. Let’s come to program.cs file and do the basic configuration code.

    First, set the environment variable --  right click on DocumentDbDemo>Debug>Add>ASPNETCORE_ENVIRONMENT=devSo you will get the dev environment file in program.cs.
    1. class Program  
    2.     {  
    3.         private static IConfiguration Configuration { get; set; }  
    4.         private static Config configs;  
    5.         private DocumentClient client;  
    6.         static void Main(string[] args)  
    7.         {  
    8.             // Setup Configuration  
    9.             var builder = new ConfigurationBuilder()  
    10.                 .SetBasePath(Directory.GetCurrentDirectory())  
    11.                    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);  
    12.             Configuration = builder.Build();  
    13.             configs = new Config();  
    14.             Configuration.Bind(configs);  
    15.   
    16.             Program obj = new Program();  
    17.             obj.CRUDOperation().Wait();  
    18.   
    19.         }  
    20. //Get a single instance of Document client and reuse  
    21. public DocumentClient Client  
    22. {  
    23.             get  
    24.             {  
    25.                 if (client == null)  
    26.                 {  
    27.                     Uri endpointUri = new Uri(configs.docDb.EndPoint);  
    28.                     client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);  
    29.                     client.OpenAsync();  
    30.                 }  
    31.                 return client;  
    32.             }  
    33.   }  
    34. }  
    In the above class we have defined some static properties and variables, also we've created the client of Document DB. It will create a single instance and will reuse or we can say singleton design pattern.

 10.  Next , we will code to create a document into the collection of documentDB.
  1. var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database,  configs.docDb.Collection);  
  2.           
  3.             // create jobject which contain the employee details  
  4.             Console.WriteLine("\nCreating document");  
  5.             JObject emp = new JObject();  
  6.             emp.Add("id""V001");  
  7.             emp.Add("name""virendra");  
  8.             emp.Add("address""Indore");  
  9.             emp.Add("Country""India");  
  10.             // create the document  
  11.             var createResponse = await Client.CreateDocumentAsync(collection, emp);  
  12.             var createdDocument = createResponse.Resource;  
  13.   
  14.             Console.WriteLine("Document with id {0} created", createdDocument.Id);  
Now, you can check the document in the collection ToDoList as shown in the below image,
  

    
         11. Now , we can read that created document by Id
  1. //Read document by Id  
  2. eadResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));  
  3.       var readDocument = readResponse.Resource;  
  4.       Console.WriteLine("Read Document {0}: ",readResponse.Resource.ToString());  
          See the below as output,
        


        12. Now , we will go for updating the document by changing the value of address property.
  1. // create jObject which contain the employee  
  2.                 JObject updateEmp = new JObject();  
  3.                 updateEmp.Add("id""V001");  
  4.                 updateEmp.Add("name""virendra");  
  5.                 updateEmp.Add("address""pune");  
  6.                 updateEmp.Add("Country""India");  
  7.   
  8.                 Console.WriteLine("\nUpdating and Adding new property to document");  
  9.                 //now update the document   
  10.                 var updateResponse = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"), updateEmp);  
  11.                 var updated = updateResponse.Resource;  
  12.                 Console.WriteLine("Document with id {0} Updated", updated.Id);  
           See the below image of the updated document.


        13. Now, we will finally delete that document from the collection.
  1. // Delete the Document  
  2. var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));  
  3. Console.WriteLine("Document Deleted");  
          See, deleted V001 document from the collection.
  

  1. Below is the complete code of program.cs class.
    1. class Program  
    2.  {  
    3.      private static IConfiguration Configuration { get; set; }  
    4.      private static Config configs;  
    5.      private DocumentClient client;  
    6.      static void Main(string[] args)  
    7.      {  
    8.          // Setup Configuration  
    9.          var builder = new ConfigurationBuilder()  
    10.              .SetBasePath(Directory.GetCurrentDirectory())  
    11.              .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);  
    12.          Configuration = builder.Build();  
    13.          configs = new Config();  
    14.          Configuration.Bind(configs);  
    15.   
    16.          Program obj = new Program();  
    17.          obj.CRUDOperation().Wait();  
    18.   
    19.      }  
    20.      //CRUD Operation  
    21.      private async Task CRUDOperation()  
    22.      {  
    23.          var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);  
    24.          try  
    25.          {  
    26.              // create jobject which contain the employee details  
    27.              Console.WriteLine("\nCreating document");  
    28.              JObject emp = new JObject();  
    29.              emp.Add("id""V001");  
    30.              emp.Add("name""virendra");  
    31.              emp.Add("address""Indore");  
    32.              emp.Add("Country""India");  
    33.              // create the document  
    34.              var createResponse = await Client.CreateDocumentAsync(collection, emp);  
    35.              var createdDocument = createResponse.Resource;  
    36.   
    37.              Console.WriteLine("Document with id {0} created", createdDocument.Id);  
    38.          }  
    39.          catch (DocumentClientException docEx)  
    40.          {  
    41.              if (docEx.StatusCode == HttpStatusCode.Conflict)  
    42.              {  
    43.                  // create jObject which contain the employee  
    44.                  JObject updateEmp = new JObject();  
    45.                  updateEmp.Add("id""V001");  
    46.                  updateEmp.Add("name""virendra");  
    47.                  updateEmp.Add("address""pune");  
    48.                  updateEmp.Add("Country""India");  
    49.   
    50.                  Console.WriteLine("\nUpdating and Adding new property to document");  
    51.                  //now update the document   
    52.                  var updateResponse = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"), updateEmp);  
    53.                  var updated = updateResponse.Resource;  
    54.                  Console.WriteLine("Document with id {0} Updated", updated.Id);  
    55.              }  
    56.          }  
    57.          catch (Exception ex)  
    58.          {  
    59.              throw ex;  
    60.          }  
    61.          //Read document by Id  
    62.          var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));  
    63.          var readDocument = readResponse.Resource;  
    64.          Console.WriteLine("Read Document {0}: ",readResponse.Resource.ToString());  
    65.   
    66.   
    67.   
    68.          // Delete the Document  
    69.          var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));  
    70.          Console.WriteLine("Document Deleted");  
    71.          Console.ReadKey();  
    72.      }  
    73.   
    74.      //Get a single instance of Document client and reuse  
    75.      public DocumentClient Client  
    76.      {  
    77.          get  
    78.          {  
    79.              if (client == null)  
    80.              {  
    81.                  Uri endpointUri = new Uri(configs.docDb.EndPoint);  
    82.                  client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);  
    83.                  client.OpenAsync();  
    84.              }  
    85.              return client;  
    86.          }  
    87.      }  
    88.  }  
I hope this code will help you J.
Thank you.

No comments:

Post a Comment