{"id":80384,"date":"2018-08-15T15:52:04","date_gmt":"2018-08-15T15:52:04","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=80384"},"modified":"2022-04-24T21:31:21","modified_gmt":"2022-04-24T21:31:21","slug":"developing-client-applications-using-the-sdk-and-azure-cosmos-db-emulator","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/developing-client-applications-using-the-sdk-and-azure-cosmos-db-emulator\/","title":{"rendered":"Developing Client Applications Using the SDK and Azure Cosmos DB Emulator"},"content":{"rendered":"<p>In this article, I am going to describe how to use the .NET SDK to build Cosmos DB client applications with the SQL API. You will see how .NET SDKs are useful for efficient programming and how to leverage them to perform various operations on Azure Cosmos DB. <a href=\"https:\/\/www.red-gate.com\/simple-talk\/cloud\/cloud-data\/introduction-to-azure-cosmos-db-emulator-for-creating-applications\/#comments\">My last article<\/a> covered core concepts in Cosmos DB and how to setup the Local Emulator to imitate creating collections and documents. This article will focus on creating and querying the collections and documents through the .NET SDK using C# code. It will also go over how to consume the Azure Cosmos DB Emulator through a client application.<\/p>\n<h2>Why Use an SDK?<\/h2>\n<p>Let\u2019s begin with a brief overview of the .NET SDK and its importance in the world of application development. Microsoft Azure provides a platform that can be used to build highly scalable and reliable applications with ease. Like almost every other service in the cloud, Cosmos DB supports building web-scale applications.<\/p>\n<p>You might be aware that almost every service on Azure uses REST (Representational State Transfer) APIs that supports HTTP operations. These HTTP requests provide an ability to create, update, delete and retrieve access to a service\u2019s resources. You can use any HTTP client to perform any operation on Cosmos DB as long as you use the correct resource URL to point to a valid Cosmos DB resource you want to work on and the HTTP headers contain the proper authentication. The most primitive way to access the resources in the Cosmos DB is to issue REST calls, these REST requests are very tedious to create. You will have to keep track of very small details such as constructing a proper header messages and the body of the message so that it is accepted by the receiving Azure services. Additionally, you will also have to take care of deconstructing the responses received from the services.<\/p>\n<p>To make a developer\u2019s life more hassle-free, we have SDKs. As defined on Microsoft Documentation, .NET\/.NET Core Software Development kit (SDK) is a set libraries and tools that allows developers to create applications and libraries. Today Microsoft provides SDKs for .NET\/.Net Core, Python, Node.JS and JAVA. If you are developing an application on any of these platforms, then using the SDK makes your development experience much smoother as compared to making the REST and HTTP calls. SDKs abstract away the low-level details. Behind the scenes SDKs will take care of setting up the HTTP headers, making the REST calls and deconstructing the response back from Cosmos DB.<\/p>\n<p>Let\u2019s first go over the main components that we will be heavily relying on to create an application which connects and performs various operations on Cosmos DB emulator. In the next section, I will give you a brief overview of these components and you will see how they are helpful for creating a client .NET application.<\/p>\n<h2>What\u2019s Needed to Create the Application?<\/h2>\n<p>This application is not difficult to create, but it relies on a handful of technologies and techniques described in this section.<\/p>\n<p><a id=\"post-80384-OLE_LINK1\"><\/a><a id=\"post-80384-OLE_LINK2\"><\/a><a id=\"post-80384-OLE_LINK3\"><\/a><a id=\"post-80384-OLE_LINK4\"><\/a><strong>Azure Cosmos DB .NET SDK &#8211; The<\/strong> <strong>Azure Cosmos DB \/ Document DB (SQL) API.NET SDK<\/strong> added to your project through the <em>NuGet Package Manager<\/em>.<\/p>\n<p><strong>DocumentClient instance &#8211; <\/strong>For accessing the Cosmos DB account through your client application, you will need to create a DocumentClient instance. You will have to supply endpoint and keys to the Cosmos DB account to the DocumentClient constructor. Once you have the DocumentClient, instance you simply call methods to perform various operations on the database such as Create\/Modify\/Delete Databases and Collections, Query Documents and Stored Procedures.<\/p>\n<div class=\"note\">\n<p><em>NOTE: See my previous <a href=\"https:\/\/www.red-gate.com\/simple-talk\/cloud\/cloud-data\/introduction-to-azure-cosmos-db-emulator-for-creating-applications\/\">article<\/a> on setting up a Cosmos DB database in the local Cosmos DB Emulator.<\/em><\/p>\n<\/div>\n<p><strong>Asynchronous operations &#8211;<\/strong> Post Operations to the Cosmos DB will be Asynchronous so the client code does not get blocked waiting for Cosmos DB after issuing requests. This article will use the <strong>useTask<\/strong> Parallel Library\u2019s task objects as well as the <strong>async<\/strong> and <strong>await<\/strong> keywords. Let me give you a brief overview of what exactly <strong>async<\/strong> and <strong>await<\/strong> are.<\/p>\n<p><strong>Async<\/strong> and <strong>await<\/strong> are the main keywords used in asynchronous programming. Through asynchronous programming you can make your application much more responsive, and it also helps in reducing performance bottlenecks. Using async\/await you can write asynchronous code that looks synchronous. Your code will wait for the method to finish its job even though, normally, it wouldn\u2019t because this is asynchronous call. For async to work you have to mark the method as having asynchronous behavior with the <strong>async<\/strong> keyword. You will have to call these methods using <strong>await<\/strong> keywords. Remember that every <strong>async<\/strong> method always returns a <strong>Task<\/strong> object. If that method has nothing to return then, it just returns the <strong>Task<\/strong> object. For instance, in the code below, the <strong>Foo()<\/strong> method is marked as <strong>async.<\/strong> Since it returns nothing, the return type is the plain <strong>Task<\/strong> object, which is practically same as returning a void. If you have some value to return such as <strong>bool<\/strong> or <strong>string<\/strong>, then you will use a generic form of <strong>Task<\/strong> object such as <strong>Task&lt;bool&gt;<\/strong> or <strong>Task&lt;string&gt;.<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"647\" height=\"203\" class=\"wp-image-80385\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-49.png\" \/><\/p>\n<p><strong>LINQ: <\/strong>Language Integrated-Query can be used to write a query expression with standard query operators in a declarative way in .NET supported programming languages. If you prefer to use LINQ over SQL then, .NET SDK supports a LINQ provider that can translate LINQ queries into Cosmos DB SQL for execution.<\/p>\n<p>I assume at this point you might have a basic idea of all the important ingredients you need to cook your recipe, i.e. to develop a Client application and perform various operations on Cosmos DB.<\/p>\n<h2>Creating an Application with the Azure Cosmos DB .NET SDK:<\/h2>\n<p>Here I am going to demonstrate how to create a .Net console application and use the <strong>Azure Cosmos DB<\/strong> .NET SDK. Start with a new Console application in Visual studio. For this go to <em>File -&gt; New -&gt; Project<\/em> which opens a new window. Select <em>Visual C# -&gt; Console App (.NET Framework). <\/em>Provide a name for your Application, such <em>as CosmosAppDemo<\/em>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1179\" height=\"815\" class=\"wp-image-80386\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A22.jpg\" \/><\/p>\n<p>Once you click <em>OK,<\/em> you will see a new project is created. First add keys to the <em>app.config<\/em> file and then grab the the Endpoint and Primary key from the Local Emulator so that you can update and store them at the right place in <em>app.config <\/em>file.<\/p>\n<pre class=\"lang:c# theme:vs2012\">  &lt;appSettings&gt;\r\n    &lt;add key=\"CosmosDBEndpointAddress\" value=\"\"\/&gt;\r\n    &lt;add key=\"CosmosDBPrimaryKey\" value=\"\"\/&gt;\r\n  &lt;\/appSettings&gt;<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1430\" height=\"568\" class=\"wp-image-80387\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-1.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A23.jpg\" \/><\/p>\n<p>To get the Endpoint address and Primary key, you need to have Azure Cosmos DB Emulator running. Search for and run the Azure Cosmos DB Emulator. Once it\u2019s running, you can access your Azure Cosmos DB Emulator using the local host address <a href=\"https:\/\/localhost:8081\/_explorer\/index.html\">https:\/\/localhost:8081\/_explorer\/index.html<\/a>. Copy the URI and Primary Key from the Emulator and paste them in the respective value fields you just added to the keys.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"427\" height=\"203\" class=\"wp-image-80388\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-50.png\" \/><\/p>\n<p>After you add the key, your <em>app.config<\/em> will look something like this:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1430\" height=\"304\" class=\"wp-image-80389\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-2.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A25new.jpg\" \/><\/p>\n<p>Now to access the settings you just added to <em>app.config, <\/em>you will need to add a reference to <em>System.Configuration<\/em> to the project. To do this go to the <em>Solution Explorer <\/em>Window, right-click on <em>References. <\/em>Click <em>Add reference<\/em> and expand <em>Assemblies. <\/em>Select <em>Framework<\/em> from the top right corner. Scroll down and select <em>System.Configuration<\/em>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1465\" height=\"864\" class=\"wp-image-80390\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-3.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A2SysrefSelectEdited.jpg\" \/><\/p>\n<p>Once you click <em>OK<\/em> you will see <em>System.Configuration<\/em> added to the project\u2019s references as shown below.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"423\" height=\"500\" class=\"wp-image-80391\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-4.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A2FinalSysyrefedited.jpg\" \/><\/p>\n<p>Next, you\u2019ll need to get the Azure Cosmos DB .NET SDK in place which you can grab from NuGet. Right-click the project in <em>Solution Explorer<\/em> and select <em>Manage NuGet Packages<\/em>. Look for the package with the title <em>Microsoft.Azure.DocumentDB<\/em>. In this article you are going to use SQL APIs. Make sure you select a package that says <em>SQL API<\/em> in the description. You might have noticed that the name of the package still uses <em>DocumentDB<\/em> which is now called Cosmos DB. This might get changed in future. Although the API name is going to be changed at some point, it is still being called Document DB in order to maintain backwards compatibility with existing applications.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"328\" height=\"292\" class=\"wp-image-80392\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-51.png\" \/><\/p>\n<p>Once you select the package, click the <em>Install<\/em> button. You will see that the installation pulls <em>Newtonsoft.Json<\/em> which is a JSON serializer and also the <em>Microsoft.Azure.DocumentDB.1.22.0<\/em> package. Now just click <em>OK<\/em> and accept the Licence aggrement.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1476\" height=\"694\" class=\"wp-image-80393\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-5.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A2NugetInstallingEdited.jpg\" \/><\/p>\n<p>After the installation has finished, you will see the assembly reference in your project.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"577\" height=\"447\" class=\"wp-image-80394\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-6.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A2AssemblyReferenceedited.jpg\" \/><\/p>\n<h2>Using Azure Cosmos DB .NET SDK to work with Cosmos DB Emulator:<\/h2>\n<p>For making you aware of all the features available in the <em>CosmosDemoApp<\/em> project, I have created a menu option so that you can easily pick whether you want to work on the Database methods, Collection methods, or Document methods. When you have created the project, you will notice that the <em>Program.cs<\/em> class file is auto created. This project will contain a Menu option which will help you navigate through the app. This demo first creates the Database and uses that Database to create Collection. Then it creates a new Document using these newly created Database and Collection.<\/p>\n<p>From Cosmos DB, the three important components that you are going to create and display in this demo are Databases, Collections, and Documents. Create a separate folder called <em>DemoClasses<\/em> in the project and add class files <em>DatabaseOperations.cs<\/em> for Database methods, <em>CollectionOperations.cs<\/em> for Collection Methods and <em>DocumentOperations.cs<\/em> for Document methods. Your project should look like the figure below.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"396\" height=\"301\" class=\"wp-image-80395\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-7.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A22FOlderStructreed.jpg\" \/><\/p>\n<p>The class files are invoked these Class files depending on what input user provides. The code in <em>Program.cs,<\/em> shown below, is self-explanatory. I won\u2019t go into much details of this code as we need to focus more on Database, Collection and Document methods in details.<\/p>\n<div class=\"note\">\n<p><em>Note: I have shown the output at each stage of the program, but I would recommend that if you are running the code on your computer that you create all the Class files beforehand with the final code so that you don\u2019t see many errors during runtime. (You can download the class files from the link at the bottom of the article.) Also, make sure you have your local emulator running.<\/em><\/p>\n<\/div>\n<p>Here is the code from the <em>Program.cs<\/em> file:<\/p>\n<pre class=\"lang:c# theme:vs2012\">using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Configuration;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing CosmosAppDemo.<a id=\"post-80384-_Hlk521950566\"><\/a>DemoClasses;\r\nusing Microsoft.Azure.Documents;\r\nusing Microsoft.Azure.Documents.Client;\r\nnamespace CosmosAppDemo\r\n{\r\n    class Program\r\n    {\r\n        private static IDictionary&lt;string, Func&lt;Task&gt;&gt; methods;\r\n        static void Main(string[] args)\r\n        {\r\n            methods = new Dictionary&lt;string, Func&lt;Task&gt;&gt;();\r\n            methods.Add(\"A\", DatabaseOperations.Run);\r\n            methods.Add(\"B\", CollectionOperations.Run);\r\n            methods.Add(\"C\", DocumentOperations.Run);\r\n            Task.Run(async () =&gt;\r\n            {\r\n                MenuOptions();\r\n                while (true)\r\n                {\r\n                    Console.Write(\"Choice: \");\r\n                    var input = Console.ReadLine();\r\n                    var demoId = input.ToUpper().Trim();\r\n                    if (methods.Keys.Contains(demoId))\r\n                    {\r\n                        var methodId = methods[demoId];\r\n                        await ExecuteDemo(methodId);\r\n                    }\r\n                    else if (demoId == \"Q\")\r\n                    {\r\n                        break;\r\n                    }\r\n                    else\r\n                    {\r\n                        Console.WriteLine($\"?{input}\");\r\n                    }\r\n                }\r\n            }).Wait();\r\n        }\r\n        private static void MenuOptions()\r\n        {\r\n            Console.WriteLine(@\"Select an option\r\n                    A Create or Display Databases\r\n                    B Create or Display Collections\r\n                    C Create or Display Documents\r\n                    Q Quit\r\n                    \");\r\n        }\r\n        private async static Task ExecuteDemo(Func&lt;Task&gt; demoMethod)\r\n        {\r\n            try\r\n            {\r\n                await demoMethod();\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                var message = ex.Message;\r\n                while (ex.InnerException != null)\r\n                {\r\n                    ex = ex.InnerException;\r\n                    message += Environment.NewLine + ex.Message;\r\n                }\r\n                Console.WriteLine($\"Error: {ex.Message}\");\r\n            }\r\n            Console.WriteLine();\r\n            Console.Write(\"Press any key to continue...\");\r\n            Console.ReadKey(true);\r\n            Console.Clear();\r\n            MenuOptions();\r\n        }\r\n    }\r\n}<\/pre>\n<p>Once you run the app, this code will produce results in the Console Window:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1103\" height=\"638\" class=\"wp-image-80396\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-52.png\" \/><\/p>\n<h2>Database operations<\/h2>\n<p>First, I am going to demonstrate how different operations such as creation, deletion and displaying the Cosmos DB database is done. In the below code, I have created different methods to perform easy operations such as<strong> DisplayDatabases(client) <\/strong>to display,<strong> CreateNewDatabase(client) <\/strong>to create a new database, and<strong> DeleteDatabase(client) <\/strong>to delete the database from Cosmos DB. These are very basic tasks, but you will be using such tasks for consuming almost every Azure service.<\/p>\n<p>The code itself is very descriptive, but let me give you a brief overview of the implementation. You are going to create a Document Client object by passing the Cosmos DB endpoint details and primary key to<strong> DocumentClient<\/strong>. It good practice to create just one instance of this object and use it wherever it\u2019s needed. This will save several lines of code, and you don\u2019t have to keep on creating and deleting the objects. Here you are using the <strong>using<\/strong> keyword that will make sure it is properly disposed of when execution of the inside code is done. Here are the three Main methods which are implemented in the below code:<\/p>\n<ul>\n<li><strong>DisplayDatabases<\/strong>: This issues a database query called <strong>CreateDatabaseQuery()<\/strong> with no parameters. This query would return the result of all the Databases present in the Cosmos DB.<\/li>\n<li><strong>CreateNewDatabase<\/strong>: This method is used to create a new database by passing the database name\/details to the CreateDatabaseAsync method.<\/li>\n<\/ul>\n<h3>Implementation for Database Operations from DatabaseOperations.cs:<\/h3>\n<pre class=\"lang:c# theme:vs2012\"><a id=\"post-80384-OLE_LINK8\"><\/a>using System;\r\nusing System.Collections.Generic;\r\nusing System.Configuration;\r\nusing System.Diagnostics;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Azure.Documents;\r\nusing Microsoft.Azure.Documents.Client;\r\nnamespace CosmosAppDemo\r\n{\r\n    class DatabaseOperations\r\n    {\r\n        public async static Task Run()\r\n        {\r\n            Debugger.Break();\r\n            \/\/get the keys from app.config\r\n            var endpointAddress = ConfigurationManager.AppSettings[\"CosmosDBEndpointAddress\"];\r\n            var primaryKey = ConfigurationManager.AppSettings[\"CosmosDBPrimaryKey\"];\r\n            using (var client = new DocumentClient(new Uri(endpointAddress), primaryKey))\r\n            {\r\n                \/\/Display all databases in CosmosDB\r\n                DisplayDatabases(client);\r\n                \/\/creates new database\r\n                await CreateNewDatabase(client);\r\n                \/\/Display all the databases\r\n                DisplayDatabases(client);\r\n            }\r\n        }\r\n        private static void DisplayDatabases(DocumentClient client)\r\n        {\r\n            \/\/get list of all the databases\r\n            Console.WriteLine(\"Displaying all databases\");\r\n            var databaseList = client.CreateDatabaseQuery().ToList();\r\n            foreach (var database in databaseList)\r\n            {\r\n                \/\/list out the database one by one\r\n                Console.WriteLine($\" Database Id is : {database.Id}; Resource Id is : {database.ResourceId}\");\r\n            }\r\n            Console.WriteLine();\r\n        }\r\n        private static async Task CreateNewDatabase(DocumentClient client)\r\n        {\r\n            Console.WriteLine(\"Please provide the name of the database which you want to create\");\r\n            var name = Console.ReadLine();\r\n            \/\/create new database\r\n            Console.WriteLine(\"Creating new database\");\r\n            var newDatabase = new Database {Id = name};\r\n            var details = await client.CreateDatabaseAsync(newDatabase);\r\n            var databaseDetails = details.Resource;\r\n            \/\/print details for the newly created database\r\n            Console.WriteLine(\r\n                $\"Created new database with Database Id is : {databaseDetails.Id}; Resource Id is : {databaseDetails.ResourceId}\");\r\n            Console.WriteLine();\r\n            \r\n        }\r\n    }\r\n}<\/pre>\n<p>First select an option to create or display Database. Once you move further, you will hit the breakpoint at the beginning of <em>DatabaseOperations.cs<\/em> file. After you debug the application you will see the list of databases being displayed through DisplayDatabases method. Further you will be prompted to provide the database name that you want for your new database. I am providing <em>DemoNewDB<\/em> as the name of my database as shown below and you will see that the database is successfully created.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1103\" height=\"639\" class=\"wp-image-80397\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-8.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A22DBcreateedited.jpg\" \/><\/p>\n<h3>Exception During Code Execution<\/h3>\n<p>If by mistake you put the same name as that of an already existing database or collection, in a further demo the code in <em>Program.cs<\/em> will handle the exception and display it on Console window as shown below. All the exceptions coming from Cosmos DB are caught and shown by the code. Try creating database named <em>DemoNewDB<\/em>again.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1102\" height=\"639\" class=\"wp-image-80398\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-9.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A22DBerroredited.jpg\" \/><\/p>\n<h2>Collections Operations<\/h2>\n<p>As I said earlier, the API calls to the services would look similar, but the parameters would change depending on the type of feature you are using. In the case of a database query, you have used<strong> CreateDatabaseQuery<\/strong>. In the case of collections, you will use <strong>CreateDocumentCollectionQuery<\/strong>. Let\u2019s walk through the main areas of the code to understand how Collections are implemented using the Azure Cosmos DB .NET SDK.<\/p>\n<ul>\n<li><strong>Creating Database URI<\/strong>: For performing almost every operation on a collection, you need the Uri for the database on which you want to create a collection. As you can see in the code below, it creates a Database Uri for the database using the <strong>UriFactory.CreateDatabaseUri()<\/strong> method.<\/li>\n<li><strong>Creating Collection<\/strong>: For creating a new Collection, I have added a <strong>CreateCollections<\/strong> method which issues a client call for the <strong>CreateDocumentCollectionAsync<\/strong> method. This method needs three mandatory details which are name of the Collection, Throughput and the Primary key. If you remember, these are the details that we had to provide on the Cosmos DB UI when creating the new Collection in the previous article.<\/li>\n<li><strong>Displaying the Collection<\/strong>: This is done by issuing the <strong>CreateDocumentCollectionQuery<\/strong> method on the <strong>DocumentClient<\/strong> object.<\/li>\n<\/ul>\n<p>There are some more terms that you might remember from my previous articles such as Throughput and partition key. Here I have provided a default value of 1000 Request units per second and partition on a default property called partition key.<\/p>\n<h3>Code Implementation for Collection Operations from CollectonOperations.cs :<\/h3>\n<pre class=\"lang:c# theme:vs2012\">using System;\r\nusing System.Collections.Generic;\r\nusing System.Configuration;\r\nusing System.Diagnostics;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Azure.Documents;\r\nusing Microsoft.Azure.Documents.Client;\r\nnamespace CosmosAppDemo.DemoClasses\r\n{\r\n    class CollectionOperations\r\n    {\r\n        public async static Task Run()\r\n        {\r\n            Debugger.Break();\r\n            \/\/get the keys from app.config\r\n            var endpointAddress = ConfigurationManager.AppSettings[\"CosmosDBEndpointAddress\"];\r\n            var primaryKey = ConfigurationManager.AppSettings[\"CosmosDBPrimaryKey\"];\r\n            using (var client = new DocumentClient(new Uri(endpointAddress), primaryKey))\r\n            {\r\n                Console.WriteLine();\r\n                \/\/Ask for databse name in which you want to create a collection\r\n                Console.WriteLine(\"Which database you want to use to create a Collection?\");\r\n                var databaseName = Console.ReadLine();\r\n                \/\/get the URI for the existing database\r\n                var databaseUri = UriFactory.CreateDatabaseUri(databaseName);\r\n                Console.WriteLine();\r\n                \/\/Ask for databse name in which you want to create a collection\r\n                Console.WriteLine(\"What is the name of the Collection that you want to create?\");\r\n                var collectionName = Console.ReadLine();\r\n                \r\n                \/\/create new collection\r\n                \/\/set name of the new collection, throughput and partiion key\r\n                var newcollectionId = collectionName;\r\n                var throughput = 1000;\r\n                string partitionKey = \"\/partitionKey\";\r\n                await CreateCollections(client, databaseUri, newcollectionId, throughput, partitionKey);\r\n                \/\/Display all Collection in CosmosDB\r\n                DisplayCollections(client, databaseUri);\r\n            }\r\n        }\r\n        private static async Task CreateCollections(DocumentClient client, Uri databaseUri, string collectionId, int RUs, string partitionKey)\r\n        {\r\n            \r\n            \/\/create new Collection\r\n            Console.WriteLine(\"Creating new Collection\");\r\n            var partitionKeyDefinition = new PartitionKeyDefinition();\r\n            partitionKeyDefinition.Paths.Add(partitionKey);\r\n            var newCollection = new DocumentCollection { Id = collectionId, PartitionKey = partitionKeyDefinition };\r\n            var requestOptions = new RequestOptions { OfferThroughput = RUs };\r\n            var details = await client.CreateDocumentCollectionAsync(databaseUri, newCollection, requestOptions);\r\n            var collection = details.Resource;\r\n            \/\/print details for the newly created Collection\r\n            Console.WriteLine($\" Created new Collection with Id  : {collection.Id}; and  Resource Id is : {collection.ResourceId}\");\r\n            Console.WriteLine();\r\n        }\r\n        \r\n        private static void DisplayCollections(DocumentClient client, Uri databaseUri)\r\n        {\r\n            \/\/get list of all the Collection\r\n            Console.WriteLine(\"Displaying Collection details\");\r\n            var collectionList = client.CreateDocumentCollectionQuery(databaseUri).ToList();\r\n            foreach (var collection in collectionList)\r\n            {\r\n                \/\/list out the Collections one by one\r\n                Console.WriteLine($\" Collection Id is : {collection.Id}\");\r\n                Console.WriteLine($\"Collection Resource Id is : {collection.ResourceId}\");\r\n                Console.WriteLine($\"Collection E-Tag is : {collection.ETag}\");\r\n            }\r\n            Console.WriteLine();\r\n        }\r\n    }\r\n}<\/pre>\n<p>Here you will be asked to provide the Database name so that the code can generate Uri that can feed to method to create the collection in that database. Just provide the new database <em>DemoNewDB<\/em> for now. Further you need to specify the name of the collection. I have provided <em>DemoNewCollection<\/em>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1102\" height=\"643\" class=\"wp-image-80399\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-10.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A22Collctioncreaededited.jpg\" \/><\/p>\n<h2>Creating and Querying Documents<\/h2>\n<p>Like the <strong>DatabaseUri<\/strong> property in the last demo, you have to create a <strong>CollectionUri<\/strong> property for creating the documents. You will have to specify both <strong>DatabaseUri<\/strong> and <strong>CollectionUri<\/strong> to perform any operations related to Documents. The key points for this implementation are:<\/p>\n<ul>\n<li><strong>Creating Database Collection URI<\/strong>: For performing almost every operation on a Document, you need a Uri for the Collection. As you can see in the code below, there is a Collection Uri for the database <em>DemoNewDB<\/em> and Collection <em>DemoNewCollection<\/em> using<strong> UriFactory.CreateDocumentCollectionUri()<\/strong>.<\/li>\n<li><strong>Creating Documents<\/strong>: The code uses a Dynamic object C# feature to build the document object. This feature lets you bind to properties at run time without compiling the class at compile time. So, this may look like JSON but it isn\u2019t. This is C# code and, it\u2019s creating a .NET object but there is no class definition. Instead properties are inferred from the way the object is utilized. Another thing to notice here is that the ID property for this document hasn\u2019t been supplied as this will be automatically generated by Cosmos DB in the form of GUID. It calls the <strong>CreateDocumentAsync<\/strong> method and the <strong>CollectionURI<\/strong> and <strong>Document<\/strong> objects are passed in to create a new Document.<\/li>\n<li><strong>Querying the Documents<\/strong>: For querying documents, the query is created and passed to on to the <strong>CreateDocumentQuery<\/strong> method call. Also, you need to pass a parameter option that will dictate if you want to enable or disable cross Partition queries by making <strong>EnableCrossPartitionQuery<\/strong> true or false. This flag is basically made true if there are multiple queries being fired from your application and these queries are using different Partition Keys. For demo purposes, I have kept it enabled. You can write any type of SQL query according to your needs, and <strong>CreateDocumentQuery<\/strong> will bring in the data for you based on the requirements mentioned.<\/li>\n<\/ul>\n<h3>Code Implementation for Document Operations from DocumentOperations.cs:<\/h3>\n<pre class=\"lang:c# theme:vs2012\">using System;\r\nusing System.Collections.Generic;\r\nusing System.Configuration;\r\nusing System.Diagnostics;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Azure.Documents;\r\nusing Microsoft.Azure.Documents.Client;\r\nnamespace CosmosAppDemo.DemoClasses\r\n{\r\n    class DocumentOperations\r\n    {\r\n        public async static Task Run()\r\n        {\r\n            Debugger.Break();\r\n            \/\/get the keys from app.config\r\n            var endpointAddress = ConfigurationManager.AppSettings[\"CosmosDBEndpointAddress\"];\r\n            var primaryKey = ConfigurationManager.AppSettings[\"CosmosDBPrimaryKey\"];\r\n            using (var client = new DocumentClient(new Uri(endpointAddress), primaryKey))\r\n            {\r\n                Console.WriteLine();\r\n                \/\/Ask for databse name in which you want to create a collection\r\n                Console.WriteLine(\"Which database you want to use to create a Document?\");\r\n                var databaseName = Console.ReadLine();\r\n                Console.WriteLine();\r\n                \/\/Ask for databse name in which you want to create a collection\r\n                Console.WriteLine(\"Which Collection you want to use to create a Document?\");\r\n                var collectionName = Console.ReadLine();\r\n                \/\/create Collection Uri\r\n                var collectionUri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName);\r\n                \/\/create new Document\r\n                await CreateDocuments(client, collectionUri);\r\n                \/\/Display all Collection in CosmosDB\r\n                QueryDocuments(client, collectionUri);\r\n            }\r\n        }\r\n        private static async Task CreateDocuments(DocumentClient client, Uri collectionUri)\r\n        {\r\n            \/\/create new Collection\r\n            Console.WriteLine(\"Creating new Document\");\r\n            dynamic documentInput = new\r\n            {\r\n                name = \"Tom Taylor\",\r\n                age = 60,\r\n                address = new\r\n                {\r\n                    Street = \"Main Street\",\r\n                    Apt = 45,\r\n                    City = \"Austin\",\r\n                    State = \"TX\",\r\n                    ZipCode = 75032\r\n                }\r\n            };\r\n            Document newDocument = await client.CreateDocumentAsync(collectionUri, documentInput);\r\n            \/\/print details for the newly created Document\r\n            Console.WriteLine($\"Created new Document with Id  : {newDocument.Id};\");\r\n            Console.WriteLine(newDocument);\r\n            Console.WriteLine();\r\n        }\r\n        private static void QueryDocuments(DocumentClient client, Uri collectionUri)\r\n        {\r\n            \/\/Query the documentsusing SQL queries\r\n            Console.WriteLine(\"Displaying Documents details\");\r\n            var query = \"SELECT * FROM c\";\r\n            \/\/Enable cross partition key\r\n            var crossPartition = new FeedOptions { EnableCrossPartitionQuery = true };\r\n            var documentsList = client.CreateDocumentQuery(collectionUri, query, crossPartition).ToList();\r\n            foreach (var document in documentsList)\r\n            {\r\n                \/\/list out the documents one by one\r\n                Console.WriteLine(document);\r\n            }\r\n            Console.WriteLine();\r\n        }\r\n    }\r\n}<\/pre>\n<p>For creating the Document, just choose option <em>C<\/em>. This time, you need both the name of the database and name of the collection. Provide the new database <em>DemoNewDB<\/em> and collection <em>DemoNewCollection<\/em> that was just created.<\/p>\n<p>As mentioned earlier, the ID is autogenerated for the newly created Document by Cosmos DB.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1339\" height=\"846\" class=\"wp-image-80400\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/c-users-spande-appdata-local-microsoft-windows-in-11.jpeg\" alt=\"C:\\Users\\spande\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\A22DocumentEdit.jpg\" \/><\/p>\n<p>After you have created the document, you can check the Local Cosmos DB Emulator which will look something like the image below. A new Collection called <em>DemoNewCollection<\/em> is created in <em>DemoNewDB.<\/em> Additionally, a new document is added.<\/p>\n<p><strong><img loading=\"lazy\" decoding=\"async\" width=\"403\" height=\"264\" class=\"wp-image-80401\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-53.png\" \/><\/strong><\/p>\n<p>This demo used the Endpoint Address and Primary key for the Local DB Emulator so that you are able to reap all the benefits of Azure Portal through emulator without any cost overhead. If you wish to use Cosmos DB from your Azure Portal, you will just need to replace the value fields of both<strong> CosmosDBEndpointAddress <\/strong>and <strong>CosmosDBPrimaryKey<\/strong> to the actual keys from your Azure Cosmos DB account in the <em>app.config<\/em> file.<\/p>\n<h2>Conclusion<\/h2>\n<p>Through Azure .NET SDK, you can make use of various method calls to Azure services without going deep into the details of REST APIs and HTTP requests. Creating the Database, Collections, and Documents is very convenient by using Azure service packages. Additionally, you can make use of local the Cosmos DB emulator for most of your application development phase for no added costs and without an Azure Subscription. When the application is ready to deploy, just switch the Connection Strings to the real Azure Cosmos DB account.<\/p>\n<p><strong>References<\/strong><\/p>\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/sql-api-dotnetcore-get-started\">https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/sql-api-dotnetcore-get-started<\/a><\/p>\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/rest\/api\/azure\/\">https:\/\/docs.microsoft.com\/en-us\/rest\/api\/azure\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Azure Cosmos DB Emulator can be used to develop Cosmos DB applications without a cost for the Azure service. In this article, Suhas Pande demonstrates several common tasks using C# and the emulator: creating databases, collections, and documents.&hellip;<\/p>\n","protected":false},"author":320462,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538,137091],"tags":[],"coauthors":[60465],"class_list":["post-80384","post","type-post","status-publish","format-standard","hentry","category-dotnet-development","category-azure"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/80384","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/320462"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=80384"}],"version-history":[{"count":11,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/80384\/revisions"}],"predecessor-version":[{"id":80408,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/80384\/revisions\/80408"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=80384"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=80384"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=80384"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=80384"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}