Document DB in Azure using C# Console Application

Document DB is a cloud service provided by Microsoft Azure. Document DB is NoSQL database. NoSQL database supports schema-less data and can handle structured, semi-structures and non-structured data. There are four types of NoSQL databases namely Document Oriented, Graph based, Column based and Key Value databases. Here we will be creating Document DB in Azure using C# console application.

Step 1: Sign in to Azure Portal, click New-> Databases -> NoSQL (Document DB)


Step 2: Here, we can configure Document DB account with NoSQL API set as Document DB


Step 3: Once created, it will be deployed and will be visible in resources list. Click on “azurenosqldb” that we have created.


Step 4: Here select Keys from left side pane, and make a note of URI and Primary Key provided for Document DB.


Step 5: Start Visual Studio 2015, Select Visual C# -> Console Application. Enter Name and location and hit ‘Ok’.


Step 6: After creation, right click on Console Application of Solution Explorer and select “Manage NuGet Packages for solution”.


Step 7: Under Browse tab, search for Azure Document DB and select “Microsoft.Azure.DocumentDB”


Select Install in right pane.


Step 8: Now we will create a Document DB and Collection in Azure. Also, we would be replacing the content here.

Copy and paste the following code (I have included comments for better understanding) and run it.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Net;

using Microsoft.Azure.Documents;

using Microsoft.Azure.Documents.Client;

using Newtonsoft.Json;

 

namespace DocumentDB

{

class Program

 

{

private const string EndpointUri = “https://azurenosqldb.documents.azure.com:XXX/”;

//URI has to be entered here

private const string PrimaryKey = “XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==”;

//Primary Key has to be entered here

private DocumentClient client;

static void Main(string[] args)

{

try

{

Program p = new Program();

p.GetStartedDemo().Wait();

}

catch (DocumentClientException de)

{

Exception baseException = de.GetBaseException();

Console.WriteLine(“{0} error occurred: {1}, Message: {2}”, de.StatusCode, de.Message, baseException.Message);

}

catch (Exception e)

{

Exception baseException = e.GetBaseException();

Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message);

}

finally

{

Console.WriteLine(“End of demo, press any key to exit.”);

Console.ReadKey();

}

}

private async Task GetStartedDemo()

{

this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

await this.CreateDatabaseIfNotExists(“Document_DB”);

await this.CreateDocumentCollectionIfNotExists(“Document_DB”, “EmployeeCollection”);

//Creates JSON document

Employee A1 = new Employee

{

Id = “A1”,

FirstName = “John”,

LastName = “Mathew”,

supervisordetails = new Supervisor[]

{

new Supervisor { Designation = “Supervisor” ,FirstName = “Tom” , Id=”34″},

new Supervisor { Designation = “Manager” , FirstName = “Chris”, Id=”12″ }

},

reporteedetails = new Reportees[]

{

new Reportees

{

FirstName = “Henry”,

ProjectDetail = new Project[]

{

new Project { ProjectId = “A101″ , ProjectName=”HelathCare”, Location=”Newyork”},

 

}

}

},

};

 

Employee A2 = new Employee

{

Id = “A2”,

FirstName = “Antony”,

LastName = “George”,

supervisordetails = new Supervisor[]

{

new Supervisor { Designation = “Supervisor” ,FirstName = “Gabriel” , Id=”45″},

new Supervisor { Designation = “Manager” , FirstName = “Mark”, Id=”22″ }

},

reporteedetails = new Reportees[]

{

new Reportees

{

FirstName = “Jane”,

ProjectDetail = new Project[]

{

new Project { ProjectId = “A111″ , ProjectName=”Insurance”, Location=”Washington”}

 

}

},

new Reportees

{

FirstName = “Andrew”,

ProjectDetail = new Project[]

{

new Project { ProjectId = “A111″ , ProjectName=”Insurance”, Location=”Washington”}

 

}

}

}

};

//Call to create Document if not exists

await this.CreateEmployeeDocumentIfNotExists(“Document_DB”, “EmployeeCollection”, A1);

await this.CreateEmployeeDocumentIfNotExists(“Document_DB”, “EmployeeCollection”, A2);

//Executes Query

this.ExecuteSimpleQuery(“Document_DB”, “EmployeeCollection”);

//Replacement values

A1.supervisordetails[0].FirstName = “Troy”;

A1.supervisordetails[0].Id = “32”;

//Call for Replacement

await this.ReplaceFamilyDocument(“Document_DB”, “EmployeeCollection”, “A1”, A1);

//Executes Query

 

this.ExecuteSimpleQuery(“Document_DB”, “EmployeeCollection”);

//Deletes Document

await this.DeleteEmployeeDocument(“Document_DB”, “EmployeeCollection”, “A1”);

await this.DeleteEmployeeDocument(“Document_DB”, “EmployeeCollection”, “A2”);

await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(“Document_DB”));

}

 

private void WriteToConsoleAndPromptToContinue(string format, params object[] args)

{

Console.WriteLine(format, args);

Console.WriteLine(“Press any key to continue …”);

Console.ReadKey();

}

//Class Ccreation

public class Employee

{

[JsonProperty(PropertyName = “id”)]

public string Id { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public Supervisor[] supervisordetails { get; set; }

public Reportees[] reporteedetails { get; set; }

public override string ToString()

{

return JsonConvert.SerializeObject(this);

}

}

 

public class Supervisor

{

public string Designation { get; set; }

public string FirstName { get; set; }

public string Id { get; set; }

}

 

public class Reportees

{

 

public string FirstName { get; set; }

public Project[] ProjectDetail { get; set; }

}

 

public class Project

{

public string ProjectId { get; set; }

public string ProjectName { get; set; }

public string Location { get; set; }

}

//Creates DB

private async Task CreateDatabaseIfNotExists(string databaseName)

{

// Check whether DB exists already

try

{

await this.client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));

this.WriteToConsoleAndPromptToContinue(“Found {0}”, databaseName);

}

catch (DocumentClientException de)

{

// If DB does not exist, Create a new database

if (de.StatusCode == HttpStatusCode.NotFound)

{

await this.client.CreateDatabaseAsync(new Database { Id = databaseName });

this.WriteToConsoleAndPromptToContinue(“Created {0}”, databaseName);

}

else

{

throw;

}

}

}

// Creates Collection

private async Task CreateDocumentCollectionIfNotExists(string databaseName, string collectionName)

{

try

{

await this.client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));

this.WriteToConsoleAndPromptToContinue(“Found {0}”, collectionName);

}

catch (DocumentClientException de)

{

// If the document collection does not exist, create a new collection

if (de.StatusCode == HttpStatusCode.NotFound)

{

DocumentCollection collectionInfo = new DocumentCollection();

collectionInfo.Id = collectionName;

 

// create and Configure collections

 

collectionInfo.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });

 

await this.client.CreateDocumentCollectionAsync(

UriFactory.CreateDatabaseUri(databaseName),

collectionInfo,

new RequestOptions { OfferThroughput = 400 });

 

this.WriteToConsoleAndPromptToContinue(“Created {0}”, collectionName);

}

else

{

throw;

}

}

}

private async Task CreateEmployeeDocumentIfNotExists(string databaseName, string collectionName, Employee employee)

{

try

{

await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, employee.Id));

this.WriteToConsoleAndPromptToContinue(“Found {0}”, employee.Id);

}

catch (DocumentClientException de)

{

if (de.StatusCode == HttpStatusCode.NotFound)

{

await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), employee);

this.WriteToConsoleAndPromptToContinue(“Created details for Employee {0}”, employee.Id);

}

else

{

throw;

}

}

}

private void ExecuteSimpleQuery(string databaseName, string collectionName)

{

 

FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };

 

IQueryable<Employee> employeeQuery = this.client.CreateDocumentQuery<Employee>(

UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)

.Where(f => f.Id == “A1”);

 

Console.WriteLine(“Running LINQ query…”);

foreach (Employee family in employeeQuery)

{

Console.WriteLine(“\tRead {0}”, family);

}

IQueryable<Employee> employeeQueryInSql = this.client.CreateDocumentQuery<Employee>(

UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),

“SELECT * FROM Employee”,

queryOptions);

 

Console.WriteLine(“Running direct SQL query…”);

foreach (Employee employee in employeeQueryInSql)

{

Console.WriteLine(“\tRead {0}”, employee);

}

 

Console.WriteLine(“Press any key to continue …”);

Console.ReadKey();

}

//Replacement function

private async Task ReplaceFamilyDocument(string databaseName, string collectionName, string EmployeeName, Employee UpdatedEmployee)

{

try

{

await this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, EmployeeName), UpdatedEmployee);

this.WriteToConsoleAndPromptToContinue(“Replaced Employee {0}”, EmployeeName);

}

catch (DocumentClientException de)

{

throw de;

}

}

private async Task DeleteEmployeeDocument(string databaseName, string collectionName, string documentName)

{

try

{

await this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentName));

Console.WriteLine(“Deleted Employee {0}”, documentName);

}

catch (DocumentClientException de)

{

throw de;

}

}

}

}

On Running,

  • First Document DB, Collection for two employees A1 and A2 will be created.
  • LINQ and SQL Query will display values populated
  • Employee A1 will be replaced with new Supervisor details here
  • LINQ and SQL Query will display values populated
  • Collection for two employees A1 and A2 will be deleted.


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s