├── .gitattributes ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── project.json └── src └── Program.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Visual Studio 3 | ################# 4 | 5 | ## Ignore Visual Studio temporary files, build results, and 6 | ## files generated by popular Visual Studio add-ons. 7 | 8 | # User-specific files 9 | *.suo 10 | *.user 11 | *.sln.docstates 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Rr]elease/ 16 | x64/ 17 | build/ 18 | [Bb]in/ 19 | [Oo]bj/ 20 | 21 | # Debug.config files 22 | *.Debug.config 23 | *.Release.config 24 | 25 | # ReSharper is a .NET coding add-in 26 | _ReSharper*/ 27 | *.[Rr]e[Ss]harper 28 | 29 | # Publish Web Output 30 | *.Publish.xml 31 | *.pubxml 32 | 33 | # NuGet Packages Directory 34 | packages/ 35 | .nuget/ 36 | 37 | # Windows Azure Build Output 38 | csx 39 | *.build.csdef 40 | 41 | # RIA/Silverlight projects 42 | Generated_Code/ 43 | 44 | # Backup & report files from converting an old project file to a newer 45 | # Visual Studio version. Backup files are not needed, because we have git ;-) 46 | _UpgradeReport_Files/ 47 | Backup*/ 48 | UpgradeLog*.XML 49 | UpgradeLog*.htm 50 | 51 | 52 | ############# 53 | ## Windows detritus 54 | ############# 55 | 56 | # Windows image file caches 57 | Thumbs.db 58 | ehthumbs.db 59 | 60 | # Folder config file 61 | Desktop.ini 62 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Azure samples 2 | 3 | Thank you for your interest in contributing to Azure samples! 4 | 5 | ## Ways to contribute 6 | 7 | You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways: 8 | 9 | - Submit feedback on [this sample page](https://azure.microsoft.com/documentation/samples/documentdb-dotnet-getting-started/) whether it was helpful or not. 10 | - Submit issues through [issue tracker](https://github.com/Azure-Samples/documentdb-dotnet-getting-started/issues) on GitHub. We are actively monitoring the issues and improving our samples. 11 | - If you wish to make code changes to samples, or contribute something new, please follow the [GitHub Forks / Pull requests model](https://help.github.com/articles/fork-a-repo/): Fork the sample repo, make the change and propose it back by submitting a pull request. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Aravind Ramachandran 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | languages: 4 | - csharp 5 | products: 6 | - azure 7 | description: "This sample shows you how to use the Microsoft Azure DocumentDB service to store and access data from a .NET Core console application." 8 | urlFragment: documentdb-dotnet-core-getting-started 9 | --- 10 | 11 | # Developing a .NET Core console app using DocumentDB 12 | This sample shows you how to use the Microsoft Azure DocumentDB service to store and access data from a .NET Core console application. 13 | 14 | For a complete end-to-end walkthrough of creating this application, please refer to the [full tutorial on the Azure documentation page](https://azure.microsoft.com/documentation/articles/documentdb-dotnetcore-get-started/). 15 | 16 | ## Running this sample 17 | 18 | 1. Before you can run this sample, you must have the following prerequisites: 19 | * An active Azure account. If you don't have one, you can sign up for a [free account](https://azure.microsoft.com/free/). 20 | * Alternatively, you can use the [Azure DocumentDB Emulator](https://azure.microsoft.com/documentation/articles/documentdb-nosql-local-emulator) for this tutorial. 21 | * [Visual Studio 2015 Update 3](https://go.microsoft.com/fwlink/?LinkId=691129) and [.NET Core 1.0.1 - VS 2015 Tooling Preview 2](https://go.microsoft.com/fwlink/?LinkID=827546) 22 | * If you're working on MacOS or Linux, you can develop .NET Core apps from the command-line by installing the [.NET Core SDK](https://www.microsoft.com/net/core#macos) for the plaform of your choice. 23 | * If you're working on Windows, you can develop .NET Core apps from the command-line by installing the [.NET Core SDK](https://www.microsoft.com/net/core#windows). 24 | * You can use your own editor, or download [Visual Studio Code](https://code.visualstudio.com/) which is free and works on Windows, Linux, and MacOS. 25 | 26 | 2. Clone this repository using Git for Windows (http://www.git-scm.com/), or download the zip file. 27 | 28 | 3. If using the DocumentDB Emulator, please follow instructions at [Azure DocumentDB Emulator](https://azure.microsoft.com/documentation/articles/documentdb-nosql-local-emulator) to install and start the emulator. 29 | 30 | If using your Azure DocumentDB account, please substitute the endpoint and authorization key in Program.cs with your account's details. 31 | 32 | 4. From a command prompt or shell, run `dotnet restore` followed by `dotnet run` to run the sample. 33 | 34 | ## About the code 35 | The code included in this sample is intended to get you quickly started with a .NET Core console application that connects to Azure DocumentDB. 36 | 37 | ## More information 38 | 39 | - [Azure DocumentDB Documentation](https://azure.microsoft.com/documentation/services/documentdb/) 40 | - [Azure DocumentDB .NET SDK](https://www.nuget.org/packages/Microsoft.Azure.DocumentDB/) 41 | - [Azure DocumentDB .NET SDK Reference Documentation](https://msdn.microsoft.com/library/azure/dn948556.aspx) 42 | -------------------------------------------------------------------------------- /project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "buildOptions": { 4 | "debugType": "portable", 5 | "emitEntryPoint": true 6 | }, 7 | "dependencies": { 8 | "Microsoft.Azure.DocumentDB.Core": "*" 9 | }, 10 | "frameworks": { 11 | "netcoreapp1.0": { 12 | "dependencies": { 13 | "Microsoft.NETCore.App": { 14 | "type": "platform", 15 | "version": "1.0.1" 16 | } 17 | }, 18 | "imports": "dnxcore50" 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Program.cs: -------------------------------------------------------------------------------- 1 | //--------------------------------------------------------------------------------- 2 | // 3 | // Microsoft (R) Azure SDK 4 | // Software Development Kit 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // 8 | // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 9 | // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 10 | // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. 11 | // 12 | //--------------------------------------------------------------------------------- 13 | 14 | namespace DocumentDB.GetStarted 15 | { 16 | using System; 17 | using System.Diagnostics.CodeAnalysis; 18 | using System.Linq; 19 | using System.Net; 20 | using System.Threading.Tasks; 21 | using Microsoft.Azure.Documents; 22 | using Microsoft.Azure.Documents.Client; 23 | using Newtonsoft.Json; 24 | 25 | /// 26 | /// This GetStarted sample demonstrates the creation of resources and execution of simple queries. 27 | /// 28 | [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "For illustration purposes.")] 29 | public class Program 30 | { 31 | /// 32 | /// The Azure DocumentDB endpoint for running this GetStarted sample. 33 | /// 34 | private const string EndpointUrl = Environment.GetEnvironmentVariable("EndpointUrl"); 35 | 36 | /// 37 | /// The primary key for the Azure DocumentDB account. 38 | /// 39 | private const string PrimaryKey = Environment.GetEnvironmentVariable("PrimaryKey"); 40 | 41 | /// 42 | /// The DocumentDB client instance. 43 | /// 44 | private DocumentClient client; 45 | 46 | /// 47 | /// The main method for the demo 48 | /// 49 | /// Command line arguments 50 | public static void Main(string[] args) 51 | { 52 | Console.WriteLine("Starting"); 53 | 54 | try 55 | { 56 | Program p = new Program(); 57 | p.GetStartedDemo().Wait(); 58 | } 59 | catch (DocumentClientException de) 60 | { 61 | Exception baseException = de.GetBaseException(); 62 | Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message); 63 | } 64 | catch (Exception e) 65 | { 66 | Exception baseException = e.GetBaseException(); 67 | Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message); 68 | } 69 | finally 70 | { 71 | Console.WriteLine("End of demo, press any key to exit."); 72 | Console.ReadKey(); 73 | } 74 | } 75 | 76 | /// 77 | /// Run the get started demo for Azure DocumentDB. This creates a database, collection, two documents, executes a simple query 78 | /// and cleans up. 79 | /// 80 | /// The Task for asynchronous completion. 81 | private async Task GetStartedDemo() 82 | { 83 | // Create a new instance of the DocumentClient 84 | this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey); 85 | 86 | await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB" }); 87 | 88 | await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("FamilyDB"), new DocumentCollection { Id = "FamilyCollection" }); 89 | 90 | // Insert a document, here we create a Family object 91 | Family andersenFamily = new Family 92 | { 93 | Id = "Andersen.1", 94 | LastName = "Andersen", 95 | Parents = new Parent[] 96 | { 97 | new Parent { FirstName = "Thomas" }, 98 | new Parent { FirstName = "Mary Kay" } 99 | }, 100 | Children = new Child[] 101 | { 102 | new Child 103 | { 104 | FirstName = "Henriette Thaulow", 105 | Gender = "female", 106 | Grade = 5, 107 | Pets = new Pet[] 108 | { 109 | new Pet { GivenName = "Fluffy" } 110 | } 111 | } 112 | }, 113 | District = "WA5", 114 | Address = new Address { State = "WA", County = "King", City = "Seattle" }, 115 | IsRegistered = true 116 | }; 117 | 118 | await this.CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", andersenFamily); 119 | 120 | Family andersonFamilyDocument = await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri("FamilyDB", "FamilyCollection", andersenFamily.Id)); 121 | 122 | Console.WriteLine("\nRead family {0}", andersonFamilyDocument.Id); 123 | 124 | this.WriteToConsoleAndPromptToContinue("{0}", andersonFamilyDocument); 125 | 126 | Family wakefieldFamily = new Family 127 | { 128 | Id = "Wakefield.7", 129 | LastName = "Wakefield", 130 | Parents = new Parent[] 131 | { 132 | new Parent { FamilyName = "Wakefield", FirstName = "Robin" }, 133 | new Parent { FamilyName = "Miller", FirstName = "Ben" } 134 | }, 135 | Children = new Child[] 136 | { 137 | new Child 138 | { 139 | FamilyName = "Merriam", 140 | FirstName = "Jesse", 141 | Gender = "female", 142 | Grade = 8, 143 | Pets = new Pet[] 144 | { 145 | new Pet { GivenName = "Goofy" }, 146 | new Pet { GivenName = "Shadow" } 147 | } 148 | }, 149 | new Child 150 | { 151 | FamilyName = "Miller", 152 | FirstName = "Lisa", 153 | Gender = "female", 154 | Grade = 1 155 | } 156 | }, 157 | District = "NY23", 158 | Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, 159 | IsRegistered = false 160 | }; 161 | 162 | await this.CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", wakefieldFamily); 163 | 164 | Family wakefieldFamilyDocument = await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri("FamilyDB", "FamilyCollection", wakefieldFamily.Id)); 165 | 166 | Console.WriteLine("\nRead family {0}", wakefieldFamilyDocument.Id); 167 | 168 | this.WriteToConsoleAndPromptToContinue("{0}", wakefieldFamilyDocument); 169 | 170 | this.ExecuteSimpleQuery("FamilyDB", "FamilyCollection"); 171 | 172 | // Clean up/delete the database and client 173 | await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri("FamilyDB")); 174 | } 175 | 176 | /// 177 | /// Create the Family document in the collection if another by the same ID doesn't already exist. 178 | /// 179 | /// The name/ID of the database. 180 | /// The name/ID of the collection. 181 | /// The family document to be created. 182 | /// The Task for asynchronous execution. 183 | private async Task CreateFamilyDocumentIfNotExists(string databaseName, string collectionName, Family family) 184 | { 185 | try 186 | { 187 | await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, family.Id)); 188 | } 189 | catch (DocumentClientException de) 190 | { 191 | if (de.StatusCode == HttpStatusCode.NotFound) 192 | { 193 | await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), family); 194 | this.WriteToConsoleAndPromptToContinue("\nCreated Family {0}", family.Id); 195 | } 196 | else 197 | { 198 | throw; 199 | } 200 | } 201 | } 202 | 203 | /// 204 | /// Execute a simple query using LINQ and SQL. Here we filter using the "LastName" property. 205 | /// 206 | /// The name/ID of the database. 207 | /// The name/ID of the collection. 208 | private void ExecuteSimpleQuery(string databaseName, string collectionName) 209 | { 210 | // Set some common query options 211 | FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true }; 212 | 213 | // Run a simple query via LINQ. DocumentDB indexes all properties, so queries can be completed efficiently and with low latency. 214 | // Here we find the Andersen family via its LastName 215 | IQueryable familyQuery = this.client.CreateDocumentQuery( 216 | UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions) 217 | .Where(f => f.LastName == "Andersen"); 218 | 219 | // The query is executed synchronously here, but can also be executed asynchronously via the IDocumentQuery interface 220 | Console.WriteLine("\nRunning LINQ query..."); 221 | foreach (Family family in familyQuery) 222 | { 223 | Console.WriteLine("\nRead {0}", family); 224 | } 225 | 226 | // Now execute the same query via direct SQL 227 | IQueryable familyQueryInSql = this.client.CreateDocumentQuery( 228 | UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), 229 | "SELECT * FROM Family WHERE Family.LastName = 'Andersen'", 230 | queryOptions); 231 | 232 | Console.WriteLine("\nRunning direct SQL query..."); 233 | foreach (Family family in familyQueryInSql) 234 | { 235 | Console.WriteLine("\nRead {0}", family); 236 | } 237 | 238 | Console.WriteLine("Press any key to continue ..."); 239 | Console.ReadKey(); 240 | } 241 | 242 | /// 243 | /// Write to the console, and prompt to continue. 244 | /// 245 | /// The string to be displayed. 246 | /// Optional arguments. 247 | private void WriteToConsoleAndPromptToContinue(string format, params object[] args) 248 | { 249 | Console.WriteLine(format, args); 250 | Console.WriteLine("Press any key to continue ..."); 251 | Console.ReadKey(); 252 | } 253 | 254 | /// 255 | /// A Family class, e.g. storing census data about families within the United States. We use this data model throughout the 256 | /// sample to show how you can store objects within your application logic directly as JSON within Azure DocumentDB. 257 | /// 258 | public class Family 259 | { 260 | [JsonProperty(PropertyName = "id")] 261 | public string Id { get; set; } 262 | 263 | public string LastName { get; set; } 264 | 265 | public string District { get; set; } 266 | 267 | public Parent[] Parents { get; set; } 268 | 269 | public Child[] Children { get; set; } 270 | 271 | public Address Address { get; set; } 272 | 273 | public bool IsRegistered { get; set; } 274 | 275 | public override string ToString() 276 | { 277 | return JsonConvert.SerializeObject(this); 278 | } 279 | } 280 | 281 | /// 282 | /// A parent class used within Family 283 | /// 284 | public class Parent 285 | { 286 | public string FamilyName { get; set; } 287 | 288 | public string FirstName { get; set; } 289 | } 290 | 291 | /// 292 | /// A child class used within Family 293 | /// 294 | public class Child 295 | { 296 | public string FamilyName { get; set; } 297 | 298 | public string FirstName { get; set; } 299 | 300 | public string Gender { get; set; } 301 | 302 | public int Grade { get; set; } 303 | 304 | public Pet[] Pets { get; set; } 305 | } 306 | 307 | /// 308 | /// A pet class that belongs to a Child 309 | /// 310 | public class Pet 311 | { 312 | public string GivenName { get; set; } 313 | } 314 | 315 | /// 316 | /// An address class containing data attached to a Family. 317 | /// 318 | public class Address 319 | { 320 | public string State { get; set; } 321 | 322 | public string County { get; set; } 323 | 324 | public string City { get; set; } 325 | } 326 | } 327 | } 328 | --------------------------------------------------------------------------------