DocumentDB – Create Account

DocumentDB – Create Account ”; Previous Next To use Microsoft Azure DocumentDB, you must create a DocumentDB account. In this chapter, we will create a DocumentDB account using Azure portal. Step 1 − Log in to the online https://portal.azure.com if you already have an Azure subscription otherwise you need to sign in first. You will see the main Dashboard. It is fully customizable so you can arrange these tiles any way you like, resize them, add and remove tiles for things you frequently use or no longer do. Step 2 − Select the ‘New’ option on the top left side of the page. Step 3 − Now select Data + Storage > Azure DocumentDB option and you see the following New DocumentDB account section. We need to come up with a globally unique name (ID), which combined with .documents.azure.com is the publicly addressable endpoint to our DocumentDB account. All the databases we create beneath that account can be accessed over the internet using this endpoint. Step 4 − Let’s name it azuredocdbdemo and click on Resource Group → new_resource. Step 5 − Choose the location i.e., which Microsoft data center you want this account to be hosted. Select the location and choose your region. Step 6 − Check Pin to dashboard checkbox and just go ahead and click Create button. You can see that the tile has already been added to the Dashboard, and it”s letting us know that the account is being created. It can actually take a few minutes to set things up for a new account while DocumentDB allocates the endpoint, provisions replicas, and performs other work in the background. Once it is done, you will see the dashboard. Step 7 − Now click on the created DocumentDB account and you will see a detailed screen as the following image. Print Page Previous Next Advertisements ”;

DocumentDB – Connect Account

DocumentDB – Connect Account ”; Previous Next When you start programming against DocumentDB, the very first step is to connect. So to connect to your DocumentDB account you will need two things; Endpoint Authorization Key Endpoint Endpoint is the URL to your DocumentDB account and it is constructed by combining your DocumentDB account name with .documents.azure.com. Let’s go to the Dashboard. Now, click on the created DocumentDB account. You will see the details as shown in the following image. When you select the ‘Keys’ option, it will display additional information as shown in the following image. You will also see the URL to your DocumentDB account, which you can use as your endpoint. Authorization Key Authorization key contains your credentials and there are two types of keys. The master key allows full access to all resources within the account, while resource tokens permit restricted access to specific resources. Master Keys There”s nothing you can”t do with a master key. You can blow away your entire database if you want, using the master key. For this reason, you definitely don”t want to be sharing the master key or distributing it to client environments. As an added security measure, it”s a good idea to change it frequently. There are actually two master keys for each database account, the primary and the secondary as highlighted in the above screenshot. Resource Tokens You can also use resource tokens instead of a master key. Connections based on resource tokens can only access the resources specified by the tokens and no other resources. Resource tokens are based on user permissions, so first you create one or more users, and these are defined at the database level. You create one or more permissions for each user, based on the resources that you want to allow each user to access. Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database. Let’s go to console application created in chapter 3. Step 1 − Add the following references in the Program.cs file. using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; Step 2 − Now add Endpoint URL and Authorization key. In this example we will be using primary key as Authorization key. Note that in your case both Endpoint URL and authorization key should be different. private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; Step 3 − Create a new instance of the DocumentClient in asynchronous task called CreateDocumentClient and instantiate new DocumentClient. Step 4 − Call your asynchronous task from your Main method. Following is the complete Program.cs file so far. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); } } } In this chapter, we have learnt how to connect to a DocumentDB account and create an instance of the DocumentClient class. Print Page Previous Next Advertisements ”;

DocumentDB – Environment Setup

DocumentDB – Environment Setup ”; Previous Next Microsoft provides a free version of Visual Studio which also contains SQL Server and it can be downloaded from https://www.visualstudio.com Installation Step 1 − Once downloading is completed, run the installer. The following dialog will be displayed. Step 2 − Click on the Install button and it will start the installation process. Step 3 − Once the installation process is completed successfully, you will see the following dialog. Step 4 − Close this dialog and restart your computer if required. Step 5 − Now open Visual studio from start Menu which will open the below dialog. It will take some time for the first time only for preparation. Once all is done, you will see the main window of Visual Studio. Step 6 − Let’s create a new project from File → New → Project. Step 7 − Select Console Application, enter DocumentDBDemo in the Name field and click OK button. Step 8 − In solution Explorer, right-click on your project. Step 9 − Select Manage NuGet Packages which will open the following window in Visual Studio and in the Search Online input box, search for DocumentDB Client Library. Step 10 − Install the latest version by clicking the install button. Step 11 − Click “I Accept”. Once installation is done you will see the message in your output window. You are now ready to start your application. Print Page Previous Next Advertisements ”;

DocumentDB – Create Collection

DocumentDB – Create Collection ”; Previous Next In this chapter, we will learn how to create a collection. It is similar to creating a database. You can create a collection either from the portal or from the code using .Net SDK. Step 1 − Go to main dashboard on Azure portal. Step 2 − Select myfirstdb from the databases list. Step 3 − Click on the ‘Add Collection’ option and specify the ID for collection. Select the Pricing Tier for different option. Step 4 − Let’s select S1 Standard and click Select → OK button. As you can see that MyCollection is added to the myfirstdb. You can also create collection from the code by using .Net SDK. Let’s have a look at the following steps to add collections from the code. Step 1 − Open the Console application in Visual Studio. Step 2 − To create a collection, first retrieve the myfirstdb database by its ID in the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); await CreateCollection(client, “MyCollection1”); await CreateCollection(client, “MyCollection2”, “S2”); } } Following is the implementation for CreateCollection task. private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = “S1”) { Console.WriteLine(); Console.WriteLine(“**** Create Collection {0} in {1} ****”, collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine(“Created new collection”); ViewCollection(collection); } We create a new DocumentCollection object that defines the new collection with the desired Id for the CreateDocumentCollectionAsync method which also accepts an options parameter that we”re using here to set the performance tier of the new collection, which we”re calling offerType. This defaults to S1 and since we didn”t pass in an offerType, for MyCollection1, so this will be an S1 collection and for MyCollection2 we have passed S2 which make this one an S2 as shown above. Following is the implementation of the ViewCollection method. private static void ViewCollection(DocumentCollection collection) { Console.WriteLine(“Collection ID: {0} “, collection.Id); Console.WriteLine(“Resource ID: {0} “, collection.ResourceId); Console.WriteLine(“Self Link: {0} “, collection.SelfLink); Console.WriteLine(“Documents Link: {0} “, collection.DocumentsLink); Console.WriteLine(“UDFs Link: {0} “, collection.UserDefinedFunctionsLink); Console.WriteLine(” StoredProcs Link: {0} “, collection.StoredProceduresLink); Console.WriteLine(“Triggers Link: {0} “, collection.TriggersLink); Console.WriteLine(“Timestamp: {0} “, collection.Timestamp); } Following is the complete implementation of program.cs file for collections. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; private static Database database; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); await CreateCollection(client, “MyCollection1”); await CreateCollection(client, “MyCollection2”, “S2”); //await CreateDatabase(client); //GetDatabases(client); //await DeleteDatabase(client); //GetDatabases(client); } } private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = “S1”) { Console.WriteLine(); Console.WriteLine(“**** Create Collection {0} in {1} ****”, collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine(“Created new collection”); ViewCollection(collection); } private static void ViewCollection(DocumentCollection collection) { Console.WriteLine(“Collection ID: {0} “, collection.Id); Console.WriteLine(“Resource ID: {0} “, collection.ResourceId); Console.WriteLine(“Self Link: {0} “, collection.SelfLink); Console.WriteLine(“Documents Link: {0} “, collection.DocumentsLink); Console.WriteLine(“UDFs Link: {0} “, collection.UserDefinedFunctionsLink); Console.WriteLine(“StoredProcs Link: {0} “, collection.StoredProceduresLink); Console.WriteLine(“Triggers Link: {0} “, collection.TriggersLink); Console.WriteLine(“Timestamp: {0} “, collection.Timestamp); } } } When the above code is compiled and executed, you will receive the following output which contains all the information related to collection. **** Create Collection MyCollection1 in myfirstdb **** Created new collection Collection ID: MyCollection1 Resource ID: Ic8LAPPvnAA= Self Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/ Documents Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/docs/ UDFs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/udfs/ StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/sprocs/ Triggers Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/triggers/ Timestamp: 12/10/2015 4:55:36 PM **** Create Collection MyCollection2 in myfirstdb **** Created new collection Collection ID: MyCollection2 Resource ID: Ic8LAKGHDwE= Self Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/ Documents Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/docs/ UDFs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/udfs/ StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/sprocs/ Triggers Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/triggers/ Timestamp: 12/10/2015 4:55:38 PM Print Page Previous Next Advertisements ”;

DocumentDB – Data Modeling

DocumentDB – Data Modeling ”; Previous Next While schema-free databases, like DocumentDB, make it super easy to embrace changes to your data model, you should still spend some time thinking about your data. You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time. You can also work with real C# objects, or Entities as they are called, which might be your business domain classes. Relationships Let’s take a look at the document”s hierarchal structure. It has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties. { “id”: “AndersenFamily”, “lastName”: “Andersen”, “parents”: [ { “firstName”: “Thomas”, “relationship”: “father” }, { “firstName”: “Mary Kay”, “relationship”: “mother” } ], “children”: [ { “firstName”: “Henriette Thaulow”, “gender”: “female”, “grade”: 5, “pets”: [ { “givenName”: “Fluffy”, “type”: “Rabbit” } ] } ], “location”: { “state”: “WA”, “county”: “King”, “city”: “Seattle”}, “isRegistered”: true } For instance, the parents property is supplied as a JSON array as denoted by the square brackets. We also have another array for children, even though there”s only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document. You simply use arrays where each element in the array could be a simple value or another complex object, even another array. So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets. For the location property, we”re combining three related properties, the state, county, and city into an object. Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database. Embedding Data When you start modeling data in a document store, such as DocumentDB, try to treat your entities as self-contained documents represented in JSON. When working with relational databases, we always normalize data. Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses. To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time. Now let”s take a look at how we would model the same data as a self-contained entity in a document database. { “id”: “1”, “firstName”: “Mark”, “lastName”: “Upston”, “addresses”: [ { “line1”: “232 Main Street”, “line2”: “Unit 1”, “city”: “Brooklyn”, “state”: “NY”, “zip”: 11229 } ], “contactDetails”: [ {“email”: “[email protected]”}, {“phone”: “+1 356 545-86455”, “extension”: 5555} ] } As you can see that we have denormalized the customer record where all the information of the customer is embedded into a single JSON document. In NoSQL we have a free schema, so you can add contact details and addresses in different format as well. In NoSQL, you can retrieve a customer record from the database in a single read operation. Similarly, updating a record is also a single write operation. Following are the steps to create documents using .Net SDK. Step 1 − Instantiate DocumentClient. Then we will query for the myfirstdb database and also query for MyCollection collection, which we store in this private variable collection so that”s it”s accessible throughout the class. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); await CreateDocuments(client); } } Step 2 − Create some documents in CreateDocuments task. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); dynamic document1Definition = new { name = “New Customer 1”, address = new { addressType = “Main Office”, addressLine1 = “123 Main Street”, location = new { city = “Brooklyn”, stateProvinceName = “New York” }, postalCode = “11229”, countryRegionName = “United States” }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine(“Created document {0} from dynamic object”, document1.Id); Console.WriteLine(); } The first document will be generated from this dynamic object. This might look like JSON, but of course it isn”t. This is C# code and we”re creating a real .NET object, but there”s no class definition. Instead the properties are inferred from the way the object is initialized. You can notice also that we haven”t supplied an Id property for this document. Step 3 − Now let”s take a look at the CreateDocument and it looks like the same pattern we saw for creating databases and collections. private async static Task<Document> CreateDocument(DocumentClient client, object documentObject) { var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject); var document = result.Resource; Console.WriteLine(“Created new document: {0}rn{1}”, document.Id, document); return result; } Step 4 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties. In the following CreateDocuments task, we have created three documents. In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); dynamic document1Definition = new { name = “New Customer 1”, address = new { addressType = “Main Office”, addressLine1 = “123 Main Street”, location = new { city = “Brooklyn”, stateProvinceName = “New York” }, postalCode = “11229”, countryRegionName = “United States” }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine(“Created document {0}

DocumentDB – List Databases

DocumentDB – List Databases ”; Previous Next So far, we have created two databases in our DocumentDB account, first one is created using Azure portal while the second database is created using .Net SDK. Now to view these databases, you can use Azure portal. Go to your DocumentDB account on Azure portal and you will see two databases now. You can also view or list the databases from your code using .Net SDK. Following are the steps involved. Step 1 − Issue a database Query with no parameters which returns a complete list, but you can also pass in a query to look for a specific database or specific databases. private static void GetDatabases(DocumentClient client) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine(“******** Get Databases List ********”); var databases = client.CreateDatabaseQuery().ToList(); foreach (var database in databases) { Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); } Console.WriteLine(); Console.WriteLine(“Total databases: {0}”, databases.Count); } You will see that there are a bunch of these CreateQuery methods for locating collections, documents, users, and other resources. These methods don”t actually execute the query, they just define the query and return an iterateable object. It”s the call to ToList() that actually executes the query, iterates the results, and returns them in a list. Step 2 − Call GetDatabases method from the CreateDocumentClient task after DocumentClient is instantiated. Step 3 − You also need to comment the CreateDatabase task or change the database id, otherwise you will get an error message that the database exists. using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { //await CreateDatabase(client); GetDatabases(client); } Following is the complete Program.cs file so far. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { await CreateDatabase(client); GetDatabases(client); } } private async static Task CreateDatabase(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“******** Create Database *******”); var databaseDefinition = new Database { Id = “mynewdb” }; var result = await client.CreateDatabaseAsync(databaseDefinition); var database = result.Resource; Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); Console.WriteLine(“******** Database Created *******”); } private static void GetDatabases(DocumentClient client) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine(“******** Get Databases List ********”); var databases = client.CreateDatabaseQuery().ToList(); foreach (var database in databases) { Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); } Console.WriteLine(); Console.WriteLine(“Total databases: {0}”, databases.Count); } } } When the above code is compiled and executed you will receive the following output which contains the Database and Resources IDs of both the databases. In the end you will also see the total number of databases. ******** Get Databases List ******** Database Id: myfirstdb; Rid: Ic8LAA== Database Id: mynewdb; Rid: ltpJAA== Total databases: 2 Print Page Previous Next Advertisements ”;

DocumentDB – Home

DocumentDB Tutorial PDF Version Quick Guide Resources Job Search Discussion DocumentDB is Microsoft”s newest NoSQL document database platform that runs on Azure. DocumentDB is designed keeping in mind the requirements of managing data for latest applications. This tutorial explains the basics of DocumentDB with illustrative examples. Audience This tutorial is designed for beginners, i.e., for developers who want to get acquainted with how DocumentDB works. Prerequisites It is an elementary tutorial that explains the basics of DocumentDB and there are no prerequisites as such. However, it will certainly help if you have some prior exposure to NoSQL technologies. Print Page Previous Next Advertisements ”;