left-icon

Azure Cosmos DB and DocumentDB Succinctly®
by Ed Freitas

Previous
Chapter

of
A
A
A

CHAPTER 4

Client-Side Development

Client-Side Development


Introduction

In the previous chapters, we had a great introduction to the DocumentDB API. We created a database and a collection, added documents, and queried data using a familiar SQL flavored syntax. We also explored briefly how to migrate existing data using the Data Migration Tool.

In this chapter, we’ll focus our attention on writing client-side code using the .NET Framework and C# to interact with DocumentDB.

Although it is possible to write client-side code using DocumentDB’s REST API, Microsoft provides SDKs for the most popular programming languages, making it much easier to interact with DocumentDB. So we won’t be exploring the REST API, but instead using the .NET SDK and writing code with C#.

We’ll start by looking at how to connect to DocumentDB from client-side code, talking about master keys and resources, and writing code examples that work with databases, collections, and documents.

The same principles that will be applied and demonstrated with the .NET SDK should be equally applicable to any other programming language SDK provided by Microsoft for DocumentDB, but syntactical differences will exist. We won’t cover any other SDKs in this chapter, though.

I highly encourage you to keep exploring the site’s excellent documentation to learn how to use any of the other SDKs that exist. There are native SDKs for Node.js, Python, and Java.

Let’s not wait any longer to get started. Have fun!

Master keys

In order to be able to do anything with DocumentDB, it is essential to connect to it. Establishing a connection is the first and main step before we can perform any operation on DocumentDB.

Creating a connection to DocumentDB requires an endpoint and a key. The endpoint is the URL to the DocumentDB account, which has the form of https://accountname.documents.azure.com.

The key contains your credentials to DocumentDB. There are two types of keys: a master key and resource tokens.

The master key grants total access to DocumentDB and you can do pretty much anything with it. You can think of it as the sa account in the SQL Server world. It provides full access to the entire DocumentDB account and should not be distributed to end user machines. There are actually two types of master keys: a primary and secondary key.

Having a primary and secondary master key is a great way to enable key rotation and change the master key without affecting any running application.

Furthermore, DocumentDB provides keys for read-only applications. Let’s have a quick look on the Azure Portal to see where we can find the keys.

Keys for a Cosmos DB Account

Figure 4-a: Keys for a Cosmos DB Account

Both the read-write and read-only keys can be found by clicking Keys on the main blade of the Cosmos DB account within the Azure Portal.

Granular access

In addition to master keys that provide full access to DocumentDB, resource tokens also let you connect. This provides granular control over security. Resource tokens can only access specific resources within DocumentDB, not all of them.

Resource tokens are based on user permissions. First it is necessary to create one or more users for the database, and then permissions are added for each user. Each permission has a resource token for all read or full access to a single user resource, which may apply to a collection, document, attachment, stored procedure, user-defined function, or trigger. Access to administrative resources (database account, databases, and users and permissions) is not allowed using resource tokens, but only when using a master key.

Resource tokens are a great way to allow granular access to specific resources based on permissions granted to specific users for certain things.

Introduction to the .NET SDK

Working with the DocumentDB .NET SDK is very straightforward. You get started by creating a DocumentClient instance and then supplying the connection information: an endpoint and a key.

Once you have an instance, you can invoke methods to access DocumentDB resources. At this point, you can create, modify, and delete databases, collections, documents, and other resources.

Let’s go ahead and install the .NET SDK from NuGet so we can start coding. Create a new Visual Studio 2017 Console Application project and add the NuGet package.

Installing the .NET SDK as a NuGet Package with Visual Studio 2017

Figure 4-b: Installing the .NET SDK as a NuGet Package with Visual Studio 2017

Once the .NET SDK has been installed, we’ll have the Microsoft.Azure.Documents.Client and Newtonsoft.Json assemblies referenced in our Visual Studio solution.

In the real world, you probably won’t be creating a console application, but will likely use a different Visual Studio project such as a Web API acting as a middle-tier or web application. In any case, the DocumentDB code will be just the same. It’s also easier to understand the functionality using a console application project.

In the sample application we’ll be writing, we’ll initially focus on connecting to DocumentDB, then displaying the names of the available databases and the collections for each one.

We’ll also have a method to display the documents stored within a collection. Let’s look at how we can achieve this. First, let’s display the list of databases on our DocumentDB account.

Listing 4-a: Displaying a List of Databases

using Microsoft.Azure.Documents.Client;

using System;

namespace DocDbClientCode

{

    class Program

    {

        public const string cStrEndPoint = "<< Your Endpoint >>";

        public const string cStrKey = "<< Your Primary Key >>";

        static void Main(string[] args)

        {

            ListDbs();

            Console.ReadLine();

        }

        public static void ListDbs()

        {

            using (var client = new DocumentClient(

                   new Uri(cStrEndPoint), cStrKey))

            {

                var dbs = client.CreateDatabaseQuery();

                foreach (var db in dbs)

                {

                    Console.WriteLine(

                    "Database Id: {0}; Rid {1}", db.Id, db.ResourceId);

                }

            }

        }

    }

}

Notice how we’ve had to include the Microsoft.Azure.Documents.Client namespace in order to be able to create an instance of DocumentClient. We also need the System namespace in order to create an instance of Uri, used for passing the DocumentDB endpoint.

With the DocumentClient instance created, we can then call the CreateDatabaseQuery method, which returns a list of objects, each containing information about a DocumentDB database. The list is then written to the console using the Id and ResourceId properties.

Running this program produces the following output.

Output of the Program Listing DocumentDB Databases

Figure 4-c: Output of the Program Listing DocumentDB Databases

That was quite straightforward. Let’s now explore collections and documents.

Accessing collections

Now that we have some basic code that connects to DocumentDB and is also able to retrieve the name of the databases present on the DocumentDB account, we can look at accessing collections. First, let’s modify a bit of the code we already have.

Code Listing 4-b: Displaying a List of Collections

using Microsoft.Azure.Documents;

using Microsoft.Azure.Documents.Client;

using System;

using System.Collections.Generic;

using System.Linq;

namespace DocDbClientCode

{

    class Program

    {

        public const string cStrEndPoint = "<< Your Endpoint >>";

        public const string cStrKey = "<< Your Primary Key >>";

        static void Main(string[] args)

        {

            ListDbs();

            Console.ReadLine();

        }

        public static void ListDbs()

        {

            using (var client = new DocumentClient(new Uri(cStrEndPoint),

                   cStrKey))

            {

                var dbs = client.CreateDatabaseQuery();

                foreach (var db in dbs)

                {

                    Console.WriteLine(

                    "Database Id: {0}; Rid {1}", db.Id, db.ResourceId);

                    ListCollections(client, db, db.Id);

                }

            }

        }

        public static void ListCollections(DocumentClient client,

        Database db, string dbname)

        {

            if (client != null && db != null)

            {

                List<DocumentCollection> collections =               

                client.CreateDocumentCollectionQuery

                (db.SelfLink).ToList();

                Console.WriteLine(

                "{0} collections for database: {1}",

                collections.Count.ToString(), dbname);

               

                foreach (DocumentCollection col in collections)

                {

                    Console.WriteLine("Collection Id: {0}; Rid {1}",

                    col.Id, col.ResourceId);

                }

            }

        }

    }

}

The main difference between the previous code example and this one is that we’ve now included a method called ListCollections that is responsible for retrieving the list of collections that exists for each DocumentDB database.

This method is called from the ListDbs method inside the foreach loop for every DocumentDB database.

Because we already have the DocumentClient and Database instances available, we pass them along with the name of the current DocumentDB database to the ListCollections method.

Now let’s look at the ListCollections method in detail. This method internally invokes the CreateDocumentCollectionQuery method, using the resource URI of the current Database (db.SelfLink) in order to get a List<DocumentCollection> object, which represents all the collections available for the dbname database.

The List<DocumentCollection> object is then looped with a foreach and each DocumentCollection instance is then written to the console, using the Id and ResourceId properties.

If we execute this code, we’ll get the following result.

Output of the Program Listing DocumentDB Databases and Collections

Figure 4-d: Output of the Program Listing DocumentDB Databases and Collections

Accessing documents

We’ve seen how to access collections within a DocumentDB database, so we’ll now look at accessing documents within collections. Let’s modify our code to achieve this.

We’ll simply create a new method called ListDocuments and modify ListCollections in order to invoke ListDocuments.

Because the rest of the previous code doesn’t change, we’ll include in the following listing these two methods only and not the full code.

Code Listing 4-c: Displaying a List of Documents

public static void ListCollections(DocumentClient client, Database db, string dbname)

{

    if (client != null && db != null)

    {

        List<DocumentCollection> collections =    

        client.CreateDocumentCollectionQuery(db.SelfLink).ToList();

        Console.WriteLine("{0} collections for database: {1}",

        collections.Count.ToString(), dbname);

        foreach (DocumentCollection col in collections)

        {

            Console.WriteLine("Collection Id: {0}; Rid {1}",

            col.Id, col.ResourceId);

            ListDocuments(client, dbname, col.Id);

        }

    }

}

public static void ListDocuments(DocumentClient client, string dbName, string collName)

{

    if (client != null)

    {

        IEnumerable<Document> docs =

        from c in client.CreateDocumentQuery(

            "dbs" + "/" + dbName + "/colls/" + collName)

        select c;

        if (docs != null)

        {

            Console.WriteLine("Documents for collection {0}", collName);

            foreach (var doc in docs)

            {

                Console.WriteLine(

                "Document Id: {0}; Rid {1} ", doc.Id, doc.ResourceId);

            }

        }

    }

}

Let’s explore the ListDocuments method quickly. By using the DocumentClient instance, we invoke the CreateDocumentQuery method.

The CreateDocumentQuery method receives as a parameter a string that represents a relative URI to the location of all documents within a specific collection. This string has two fixed parts: "dbs" and "colls".

After "dbs", the name of the DocumentDB database is concatenated, using the variable dbName. After "colls", the name of the collection to be queried is also concatenated, using the variable collName.

This allows the CreateDocumentQuery method to retrieve all documents contained within the collection collName. The list of documents is assigned to an IEnumerable<Document> object, which is then looped with a foreach, writing to the console each document’s Id and ResourceId. Running the updated program with this latest code outputs the following results.

Output of the Program Listing DocumentDB Databases, Collections, and Documents

Figure 4-e: Output of the Program Listing DocumentDB Databases, Collections, and Documents

Querying documents

We’ve seen so far how to connect to DocumentDB and list databases, collections, and documents. However, we haven’t seen yet how to retrieve information that is specific to certain document types. This is what we’ll be focusing on now.

In order to retrieve information specific to certain document types, we need to be able to specify exactly what type of data we want to retrieve. The way we do that is by defining a C# class that represents the structure of the type of document (with the property names) we want to retrieve.

So far throughout this e-book we’ve added three document types to our only DocumentDB collection. Two of them are quite similar and are related to food, and the third one is totally unrelated, containing data for the famous soccer player Cristiano Ronaldo.

So if we want to retrieve the properties for the document that contains Cristiano Ronaldo’s document type details, we need to define a C# class as follows. We can do this inside the DocDbClientCode namespace. I use the sealed modifier here on my class to prevent other classes from inheriting from it, but it's not required.

Listing 4-d: Definition Class for Cristiano Ronaldo’s Document Type

public sealed class CR7DocType

{

    public string id { get; set; }

    public string Name { get; set; }

    public string LastName { get; set; }

    public string Nationality { get; set; }

    public string BirthPlace { get; set; }

}

This class definition matches exactly the properties that the Cristiano Ronaldo document type contains. Let’s quickly look at this document using Data Explorer to refresh our memories.

The CR7 Document as Seen with Data Explorer

Figure 4-f: The CR7 Document as Seen with Data Explorer

Now that we’ve defined the C# class that defines its properties, we can write a method to retrieve it. We won’t modify any other part of the code that has been written so far, so we’ll only add this new method. Let’s have a look.

Code Listing 4-e: Method to List Cristiano Ronaldo’s Documents

public static void ListCR7DocType(CR7DocType cr7, DocumentClient client, string dbName, string collName)

{

    if (client != null)

    {

        IEnumerable<CR7DocType> docs =

            from c in client.CreateDocumentQuery<CR7DocType>(

                "dbs" + "/" + dbName + "/colls/" + collName)

            where c.Name.ToUpper().

                Contains(cr7.Name.ToUpper())

            where c.LastName.ToUpper().

                Contains(cr7.LastName.ToUpper())

            select c;

        if (docs != null)

        {

            foreach (var doc in docs)

            {

                Console.WriteLine("id: {0}", doc.id);

                Console.WriteLine("Name: {0}", doc.Name);

                Console.WriteLine("LastName: {0}", doc.LastName);

                Console.WriteLine("Nationality: {0}", doc.Nationality);

                Console.WriteLine("Birthplace: {0}", doc.Birthplace);

            }

        }

    }

}

This method pretty much works the same way as the ListDocuments method. The main difference is that when we invoke the CreateDocumentQuery method, we are now explicitly telling it that its T is a CR7DocType class. This allows us to focus the query to look only at CR7DocType documents.

The result is an IEnumerable<CR7DocType> object that we can loop through and use to output to the console each document’s properties. On the ListCollections method, let’s replace the call to ListDocuments with a call to ListCR7DocType.

Code Listing 4-f: ListCollections Invoking the ListCR7DocType Method

public static void ListCollections(DocumentClient client, Database db, string dbname)

{

    if (client != null && db != null)

    {

        List<DocumentCollection> collections =

            client.CreateDocumentCollectionQuery(db.SelfLink).ToList();

        Console.WriteLine("{0} collections for database: {1}",

            collections.Count.ToString(), dbname);

       

        foreach (DocumentCollection col in collections)

        {

            Console.WriteLine(

                "Collection Id: {0}; Rid {1}", col.Id, col.ResourceId);

                ListCR7DocType(new CR7DocType { Name = "Ronaldo",

                LastName = "Aveiro"}, client, dbname, col.Id);

        }

    }

}

If we now run the updated program with these changes, we get the following output.

Output of the Program Invoking the ListCR7DocType Method

Figure 4-g: Output of the Program Invoking the ListCR7DocType Method

Notice how we are passing a CR7DocType object with abbreviated string values for the Name and LastName properties. The LINQ query on the ListCR7DocType method is able to return the resulting document because it performs a Contains string search rather than a complete string comparison.

Now let’s do the same for one of the food document types, just like we did with CR7. Let’s go ahead and define some C# definition classes for one of the food document types, inside the DocDbClientCode namespace.

Code Listing 4-g: Definition Classes for One of the Food Document Types

public sealed class Tags

{

    public string name { get; set; }

}

public sealed class Servings

{

    public int amount { get; set; }

    public string description { get; set; }

    public int weightInGrams { get; set; }

}

public sealed class FoodDocType

{

    public string id { get; set; }

    public string description { get; set; }

    public int version { get; set; }

    public bool isFromSurvey { get; set; }

    public string foodGroup { get; set; }

    public Tags[] tags { get; set; }

    public Servings[] servings { get; set; }

}

Now let’s create a method to list these food document types.

Listing 4-h: Method to List Food Type Documents

public static void ListFoodDocType(FoodDocType fd, DocumentClient client, string dbName, string collName)

{

    if (client != null)

    {

        IEnumerable<FoodDocType> docs =

            from c in client.CreateDocumentQuery<FoodDocType>(

            "dbs" + "/" + dbName + "/colls/" + collName)

            where c.description.ToUpper().

                Contains(fd.description.ToUpper())

            select c;

        if (docs != null)

        {

            foreach (var doc in docs)

            {

                Console.WriteLine("id: {0}", doc.id);

                Console.WriteLine("description: {0}", doc.description);

                Console.WriteLine("Version: {0}", doc.version);

                Console.WriteLine("isFromSurvey: {0}",

                    doc.isFromSurvey.ToString());

                Console.WriteLine("foodGroup: {0}", doc.foodGroup);

            }

        }

    }

}

Let’s now modify the ListCollections method so it can invoke this newly created ListFoodDocType method.

Listing 4-i: ListCollections invoking the ListFoodDocType Method

public static void ListCollections(DocumentClient client, Database db, string dbname)

{

    if (client != null && db != null)

    {

        List<DocumentCollection> collections =

            client.CreateDocumentCollectionQuery(db.SelfLink).ToList();

        Console.WriteLine("{0} collections for database: {1}",

            collections.Count.ToString(), dbname);

       

        foreach (DocumentCollection col in collections)

        {

            Console.WriteLine("Collection Id: {0}; Rid {1}", col.Id,

                col.ResourceId);

            ListFoodDocType(new FoodDocType { description = "Snacks" },

                client, dbname, col.Id);

        }

    }

}

If we execute the updated program, we get the following output.

Output of the Program Invoking the ListFoodDocType Method

Figure 4-h: Output of the Program Invoking the ListFoodDocType Method

If we quickly analyze the ListFoodDocType method, we can see that it is almost identical to the ListCR7DocType method, with the exception that the LINQ query is returning an IEnumerable<FoodDocType> object instead of an IEnumerable<CR7DocType> one. The rest is pretty much the same.

The main difference is the definition class we pass as a T parameter to the CreateDocumentQuery method in order to be able to retrieve the right document type we expect to get.

Now that we’ve seen how to query documents, let’s briefly explore how to add a document to a collection before wrapping up this chapter.

Adding a document

Adding a document to an existing collection is quite easy. However, it is an asynchronous operation, so it’s best to wrap this up nicely in two methods. One method creates the document and the other creates the asynchronous task that invokes the method that creates the document on the collection. Let’s see how we can implement this.

Let’s start off by adding a using statement to our existing code. This is because we’ll be using a Task object to invoke the asynchronous method that will create the new document.

Code Listing 4-j: Adding the Threading .NET Library

using System.Threading.Tasks;

The rest of the previous using statements, as mentioned in Code Listing 4-b, remain the same. Now, let’s create the method that will create the document. We’ll name it CreateDocType.

Code Listing 4-k: The New CreateDocType Method

public static async Task<Document> CreateDocType(FoodDocType fd, DocumentClient client, string dbName, string collName)

{

    if (client != null)

    {

        string url = "dbs" + "/" + dbName + "/colls/" + collName;

        Document id = await client.CreateDocumentAsync(url, fd);

        return (id != null) ? client.CreateDocumentQuery(url).

        Where(d => d.Id == id.Id).AsEnumerable().FirstOrDefault() : null;

    }

    else

        return null;

}

The important part of the CreateDocType method, and the one we will be focusing on, is the call to CreateDocumentAsync, which is really the one responsible for creating the new document on the collection specified by the url string.

Because CreateDocumentAsync is an asynchronous method, we have to await it and also mark the CreateDocType method as async. Once the document has been created, a call to CreateDocumentQuery is carried out to actually verify that the document has indeed been created within the collection.

With this in place, we can then create a wrapper method we will call CreateDoc to execute asynchronous code that will invoke CreateDocType.

Code Listing 4-l: The New CreateDoc Wrapper Method

public static async void CreateDoc(string dbName, string collName)

{

    await Task.Run(

    async () =>

    {

        using (var client = new DocumentClient(

            new Uri(cStrEndPoint), cStrKey))

        {

            FoodDocType fd = new FoodDocType { id = "TestFoodDoc",

                description = "Organic food",

                isFromSurvey = false,

                foodGroup = "Organic", version = 1 };

            Document issue = await CreateDocType(fd, client,

                dbName, collName);

        }

    });

}

The CreateDoc method simply invokes Task.Run and an anonymous async method is passed as a lambda expression. This creates a FoodDocType object with some properties, representing the document that will be created using CreateDocType.

Finally, we can modify the Main method of the program to invoke CreateDoc. It would look as follows.

Code Listing 4-m: The Updated Main Program Method

static void Main(string[] args)

{

    CreateDoc("ToDoList", "Items");           

    Console.ReadLine();

}

If we execute this code and then open Data Explorer on the Azure Portal, we can see that the document has been created.

The TestFoodDoc Document Added Through C# Code

Figure 4-i: The TestFoodDoc Document Added Through C# Code

Great! So we’ve now seen how to add a document using C#. The following code listing is the full updated source code of the program we’ve created so far.

Code Listing 4-n: The Full Program Code

using Microsoft.Azure.Documents;

using Microsoft.Azure.Documents.Client;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace DocDbClientCode

{

    public sealed class CR7DocType

    {

        public string id { get; set; }

        public string Name { get; set; }

        public string LastName { get; set; }

        public string Nationality { get; set; }

        public string Birthplace { get; set; }

    }

    public sealed class Tags

    {

        public string name { get; set; }

    }

    public sealed class Servings

    {

        public int amount { get; set; }

        public string description { get; set; }

        public int weightInGrams { get; set; }

    }

    public sealed class FoodDocType

    {

        public string id { get; set; }

        public string description { get; set; }

        public int version { get; set; }

        public bool isFromSurvey { get; set; }

        public string foodGroup { get; set; }

        public Tags[] tags { get; set; }

        public Servings[] servings { get; set; }

    }

    class Program

    {

        public const string cStrEndPoint = ""<< Your Endpoint >>"";

        public const string cStrKey = "Your Primary Key";

        static void Main(string[] args)

        {

            //Comment out the line below and uncomment ListDbs();

            CreateDoc("ToDoList", "Items");

           

            //Uncomment and comment out CreateDoc(…);

            //ListDbs();

            Console.ReadLine();

        }

        public static async void CreateDoc(string dbName, string

        collName)

        {

            await Task.Run(

            async () =>

            {

                using (var client = new DocumentClient(new

                Uri(cStrEndPoint), cStrKey))

                {

                    FoodDocType fd = new FoodDocType { id =

                        "TestFoodDoc", description = "Organic food",

                        isFromSurvey = false, foodGroup = "Organic",

                        version = 1 };

                    Document issue = await CreateDocType(fd, client,

                      dbName, collName);

                }

            });

        }

        public static async Task<Document> CreateDocType(FoodDocType fd,

        DocumentClient client, string dbName, string collName)

        {

            if (client != null)

            {

                string url = "dbs" + "/" + dbName + "/colls/" + collName;

                Document id = await client.CreateDocumentAsync(url, fd);

                return (id != null) ? client.CreateDocumentQuery(url).

                    Where(d => d.Id ==

                    id.Id).AsEnumerable().FirstOrDefault() : null;

            }

            else

                return null;

        }

        public static void ListDbs()

        {

            using (var client = new DocumentClient(

                new Uri(cStrEndPoint), cStrKey))

            {

                var dbs = client.CreateDatabaseQuery();

                foreach (var db in dbs)

                {

                    Console.WriteLine("Database Id: {0}; Rid {1}",

                        db.Id, db.ResourceId);

                    ListCollections(client, db, db.Id);

                }

            }

        }

        public static void ListCollections(DocumentClient client,

        Database db, string dbname)

        {

            if (client != null && db != null)

            {

                List<DocumentCollection> collections =

                    client.CreateDocumentCollectionQuery

                    (db.SelfLink).ToList();

                Console.WriteLine("{0} collections for database: {1}",

                    collections.Count.ToString(), dbname);

                foreach (DocumentCollection col in collections)

                {

                    Console.WriteLine("Collection Id: {0}; Rid {1}",

                        col.Id, col.ResourceId);

                   

                    // Comment out each List instruction one at a time          

                    // to see the different results :)

                   

                    //ListDocuments(client, dbname, col.Id);

                    //ListCR7DocType(new CR7DocType { Name = "Ronaldo",

                    //    LastName = "Aveiro"}, client, dbname, col.Id);

                   

                    //ListFoodDocType(new FoodDocType { description =

                    //    "Snacks" }, client, dbname, col.Id);

                }

            }

        }

        public static void ListDocuments(DocumentClient client, string

        dbName, string collName)

        {

            if (client != null)

            {

                IEnumerable<Document> docs =

                    from c in client.CreateDocumentQuery(

                    "dbs" + "/" + dbName + "/colls/" + collName)

                    select c;

                if (docs != null)

                {

                    Console.WriteLine("Documents for collection {0}",

                        collName);

                    foreach (var doc in docs)

                    {

                        Console.WriteLine("Document Id: {0}; Rid {1} ",

                            doc.Id, doc.ResourceId);

                    }

                }

            }

        }

        public static void ListFoodDocType(FoodDocType fd, DocumentClient

        client, string dbName, string collName)

        {

            if (client != null)

            {

                IEnumerable<FoodDocType> docs =

                    from c in

                    client.CreateDocumentQuery<FoodDocType>

                        ("dbs" + "/" + dbName + "/colls/" + collName)

                    where c.description.ToUpper().

                        Contains(fd.description.ToUpper())

                    select c;

                if (docs != null)

                {

                    foreach (var doc in docs)

                    {

                        Console.WriteLine("id: {0}", doc.id);

                        Console.WriteLine("description: {0}",

                            doc.description);

                        Console.WriteLine("Version: {0}", doc.version);

                        Console.WriteLine("isFromSurvey: {0}",

                            doc.isFromSurvey.ToString());

                        Console.WriteLine("foodGroup: {0}",

                            doc.foodGroup);

                    }

                }

            }

        }

        public static void ListCR7DocType(CR7DocType cr7, DocumentClient

        client, string dbName, string collName)

        {

            if (client != null)

            {

                IEnumerable<CR7DocType> docs =

                    from c in client.CreateDocumentQuery<CR7DocType>

                        ("dbs" + "/" + dbName + "/colls/" + collName)

                    where c.Name.ToUpper().

                        Contains(cr7.Name.ToUpper())

                    where c.LastName.ToUpper().

                        Contains(cr7.LastName.ToUpper())

                    select c;

                if (docs != null)

                {

                    foreach (var doc in docs)

                    {

                        Console.WriteLine("id: {0}", doc.id);

                        Console.WriteLine("Name: {0}", doc.Name);

                        Console.WriteLine("LastName: {0}", doc.LastName);

                        Console.WriteLine("Nationality: {0}",

                            doc.Nationality);

                        Console.WriteLine("Birthplace: {0}",

                            doc.Birthplace);

                    }

                }

            }

        }

    }

}

Summary

Throughout this chapter, we’ve explored how to interact with DocumentDB from C#. We’ve explained how to list various object types, such as databases, collections, and documents. We’ve also shown how to create documents.

However, we’ve just scratched the surface of what is possible with the .NET DocumentDB SDK.

The DocumentDB documentation website contains invaluable information on how to interact with the service and the .NET section is particularly rich and well documented. I highly encourage you to keep exploring and studying this subject with this great tutorial.

Furthermore, I’ve written another e-book for Syncfusion called Customer Success for C# Developers Succinctly that has a chapter devoted to writing a simple CRM app using DocumentDB along with C#. It is worth exploring.

In the next chapter we’ll focus on exploring the server-side features of DocumentDB and how to write server code in JavaScript that performs operations on databases, collections, and documents.

Hopefully this chapter has been an eye-opener to what is possible with DocumentDB and C#, and the examples have been fun to follow and implement. Thanks for reading!

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.