You can try CosmosDB for free on Azure or you can setup the CosmosDB on your local environment by following my previous blog. I am becoming a fan of .NET Core with all the features and it is getting better day by day . In this blog post i just wanted to take that initial steps of how to work with CosmosDB from .NET Core Client context. After reading this blog, you should be able to do the following with CosmosDB programmatically,
- Create Database
- Create Collection
- Create Documents
- Query a Document
- Delete Database
Pre-Requisities Needed:
- Windows 10 OS
- Azure CosmosDB Emulator
- Visual Studio Code editor with C# plugin
- .NET Core 2.0
Step 1: Create .Net Core Console Application :
As other tutorials, to make it simple I will be creating a dotnetcore console app to work with CosmosDB . With Net Core , we now have a CLI. Lets create the new app with the following steps. (I’ve mentioned in the previous blog)
- Open command prompt or poweshell (Administrator Mode)
- Navigate to your folder where you need to create the app
- Execute the following command
dotnet new console -n CosmosCoreClient -o CosmosCoreClient
Open the newly created project in Visual Studio Code. Execute the following command
Here is a screenshot of how it should look on your end:
<LangVersion>latest</LangVersion>
- Open a command prompt and navigate to root of your project.
- Execute the following command
dotnet add package Microsoft.Azure.DocumentDB.Core
- Course
- Session
- Teacher
- Student
using Microsoft.Azure.Documents; using Newtonsoft.Json; using System; using System.Collections.Generic; public class Course : Document { [JsonProperty(PropertyName = "CourseId")] public Guid CourseId { get; set; } [JsonProperty(PropertyName = "Name")] public string Name { get { return GetPropertyValue<string>("Name"); } set { SetPropertyValue("Name", value); } } [JsonProperty(PropertyName = "Sessions")] public List<Session> Sessions { get; set; } [JsonProperty(PropertyName = "Teacher")] public Teacher Teacher { get; set; } [JsonProperty(PropertyName = "Students")] public List<Student> Students { get; set; } }
using System; public class Session { public Guid SessionId { get; set; } public string Name { get; set; } public int MaterialsCount { get; set; } }
using System; public class Teacher { public Guid TeacherId { get; set; } public string FullName { get; set; } public int Age { get; set; } }
using System; public class Student { public Guid StudentId { get; set; } public string FullName { get; set; } }
- URL of the CosmosDb instane
- Authentication key needed to authenticate.
As stated above, When you start the CosmosDb local emulator, the db instance is available at https://localhost:8081. The authkey for local emulator is a static key and you can find it here in this article(https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator#authenticating-requests). This key works only with the local emulator and wont work with your Azure instance, you can find the key if you are using azure instance from the portal as mentioned in the answer. Here is the code snippet to instantiate the client:
static string endpointUri = "https://localhost:8081"; static string authKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; string dbName = "CourseDB"; string collectionName = "Courses"; static void Main(string[] args) { Console.WriteLine("Press any key to run"); Console.ReadLine(); Run(); Console.ReadLine(); } private static async void Run() { DocumentClient documentClient = new DocumentClient(new Uri(endpointUri), authKey); }
When the method Run is exectued the Client is instantiated with the local CosmosDB emulator.
Next step is to build the features as listed above. Lets add the methods inside the Async method.
private static async Task<Database> CreateDatabase(DocumentClient documentClient) { Database database = documentClient.CreateDatabaseQuery().Where(c => c.Id == "courseDatabase").AsEnumerable().FirstOrDefault(); if (database == null) { database = await documentClient.CreateDatabaseAsync(new Database() { Id = "courseDatabase" }); } return database; }
private static async Task<DocumentCollection> CreateDocumentCollection(DocumentClient documentClient, Database database) { DocumentCollection documentCollection = documentClient.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "courseDocumentCollection").AsEnumerable().FirstOrDefault(); if (documentCollection == null) { documentCollection = await documentClient.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection() { Id = "courseDocumentCollection" }); } return documentCollection; }
Now you should the the Collection for Course is created as follows,
Creating Document :
After creating the database and collection, we can now create the documents. We make use of CreateDocumentAsync() for this purpose. We will need to pass the URI of the collection under which we want to create the document and the document data itself. In this example we make use of the Course data mode i showed earlier and pass it to the create method. Here is the code snippet:
private static async Task CreateCourse(DocumentClient documentClient, DocumentCollection documentCollection) { Course course = new Course() { CourseId = Guid.NewGuid(), Name = "En", Teacher = new Teacher() { TeacherId = Guid.NewGuid(), FullName = "Scott Hanselman", Age = 44 }, Students = new List<Student>() { new Student(){ FullName = "Trump", StudentId = Guid.NewGuid() } }, Sessions = new List<Session>(){ new Session(){ SessionId = Guid.NewGuid(), Name = "CosmosDB", MaterialsCount = 10 }, new Session(){ SessionId = Guid.NewGuid(), Name = "Ch1", MaterialsCount = 3 } } }; Document document = await documentClient.CreateDocumentAsync(documentCollection.DocumentsLink, course); }
private Course QueryCourse(Guid guid, String dbName, DocumentClient documentClient, string collectionName) { Course selectedCourse = documentClient.CreateDocumentQuery<Course>( UriFactory.CreateDocumentCollectionUri(dbName, collectionName)) .Where(v => v.Name == "CosmosDB") .AsEnumerable() .FirstOrDefault(); return selectedCourse; }
Note that you will need to import System.Linq for the LINQ expression to work.
await documentClient.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(dbName));
Well, those are the main features that Azure CosmosDB client provides and if you are stuck with any of the steps above , you can check out the repository i have added with the samples.
Happy Coding! Lets spread Azure’s CosmosDB to the world.
Nice coddling
LikeLike