├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── CosmosGettingStartedDotnetCoreTutorial.sln ├── CosmosGettingStartedDotnetCoreTutorial ├── CosmosGettingStartedDotnetCoreTutorial.csproj ├── Family.cs └── Program.cs ├── LICENSE.md └── README.md /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [project-title] Changelog 2 | 3 | 4 | # x.y.z (yyyy-mm-dd) 5 | 6 | *Features* 7 | * ... 8 | 9 | *Bug Fixes* 10 | * ... 11 | 12 | *Breaking Changes* 13 | * ... 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [project-title] 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.microsoft.com. 6 | 7 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | - [Code of Conduct](#coc) 16 | - [Issues and Bugs](#issue) 17 | - [Feature Requests](#feature) 18 | - [Submission Guidelines](#submit) 19 | 20 | ## Code of Conduct 21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 22 | 23 | ## Found an Issue? 24 | If you find a bug in the source code or a mistake in the documentation, you can help us by 25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can 26 | [submit a Pull Request](#submit-pr) with a fix. 27 | 28 | ## Want a Feature? 29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub 30 | Repository. If you would like to *implement* a new feature, please submit an issue with 31 | a proposal for your work first, to be sure that we can use it. 32 | 33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). 34 | 35 | ## Submission Guidelines 36 | 37 | ### Submitting an Issue 38 | Before you submit an issue, search the archive, maybe your question was already answered. 39 | 40 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 41 | Help us to maximize the effort we can spend fixing issues and adding new 42 | features, by not reporting duplicate issues. Providing the following information will increase the 43 | chances of your issue being dealt with quickly: 44 | 45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 46 | * **Version** - what version is affected (e.g. 0.1.2) 47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you 48 | * **Browsers and Operating System** - is this a problem with all browsers? 49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps 50 | * **Related Issues** - has a similar issue been reported before? 51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 52 | causing the problem (line of code or commit) 53 | 54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. 55 | 56 | ### Submitting a Pull Request (PR) 57 | Before you submit your Pull Request (PR) consider the following guidelines: 58 | 59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR 60 | that relates to your submission. You don't want to duplicate effort. 61 | 62 | * Make your changes in a new git fork: 63 | 64 | * Commit your changes using a descriptive commit message 65 | * Push your fork to GitHub: 66 | * In GitHub, create a pull request 67 | * If we suggest changes then: 68 | * Make the required updates. 69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): 70 | 71 | ```shell 72 | git rebase master -i 73 | git push -f 74 | ``` 75 | 76 | That's it! Thank you for your contribution! 77 | -------------------------------------------------------------------------------- /CosmosGettingStartedDotnetCoreTutorial.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27813.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CosmosGettingStartedDotnetCoreTutorial", "CosmosGettingStartedDotnetCoreTutorial\CosmosGettingStartedDotnetCoreTutorial.csproj", "{54B29E2A-EF32-48FD-A51B-41E5D07DEBB3}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {54B29E2A-EF32-48FD-A51B-41E5D07DEBB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {54B29E2A-EF32-48FD-A51B-41E5D07DEBB3}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {54B29E2A-EF32-48FD-A51B-41E5D07DEBB3}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {54B29E2A-EF32-48FD-A51B-41E5D07DEBB3}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {E51C0FBD-EBE8-4F7C-914F-D503B18CB601} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /CosmosGettingStartedDotnetCoreTutorial/CosmosGettingStartedDotnetCoreTutorial.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp2.0 6 | latest 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /CosmosGettingStartedDotnetCoreTutorial/Family.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace CosmosGettingStartedDotnetCoreTutorial 4 | { 5 | public class Family 6 | { 7 | [JsonProperty(PropertyName = "id")] 8 | public string Id { get; set; } 9 | public string LastName { get; set; } 10 | public Parent[] Parents { get; set; } 11 | public Child[] Children { get; set; } 12 | public Address Address { get; set; } 13 | public bool IsRegistered { get; set; } 14 | public override string ToString() 15 | { 16 | return JsonConvert.SerializeObject(this); 17 | } 18 | } 19 | 20 | public class Parent 21 | { 22 | public string FamilyName { get; set; } 23 | public string FirstName { get; set; } 24 | } 25 | 26 | public class Child 27 | { 28 | public string FamilyName { get; set; } 29 | public string FirstName { get; set; } 30 | public string Gender { get; set; } 31 | public int Grade { get; set; } 32 | public Pet[] Pets { get; set; } 33 | } 34 | 35 | public class Pet 36 | { 37 | public string GivenName { get; set; } 38 | } 39 | 40 | public class Address 41 | { 42 | public string State { get; set; } 43 | public string County { get; set; } 44 | public string City { get; set; } 45 | } 46 | } -------------------------------------------------------------------------------- /CosmosGettingStartedDotnetCoreTutorial/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using System.Collections.Generic; 4 | using System.Net; 5 | using Microsoft.Azure.Cosmos; 6 | 7 | namespace CosmosGettingStartedDotnetCoreTutorial 8 | { 9 | public class Program 10 | { 11 | private static readonly string EndpointUri = ""; 12 | // The primary key for the Azure Cosmos account. 13 | private static readonly string PrimaryKey = ""; 14 | 15 | // The Cosmos client instance 16 | private CosmosClient cosmosClient; 17 | 18 | // The database we will create 19 | private Database database; 20 | 21 | // The container we will create. 22 | private Container container; 23 | 24 | // The name of the database and container we will create 25 | private string databaseId = "FamilyDatabase"; 26 | private string containerId = "FamilyContainer"; 27 | 28 | public static async Task Main(string[] args) 29 | { 30 | try 31 | { 32 | Console.WriteLine("Beginning operations...\n"); 33 | Program p = new Program(); 34 | await p.GetStartedDemoAsync(); 35 | } 36 | catch (CosmosException de) 37 | { 38 | Exception baseException = de.GetBaseException(); 39 | Console.WriteLine("{0} error occurred: {1}\n", de.StatusCode, de); 40 | } 41 | catch (Exception e) 42 | { 43 | Console.WriteLine("Error: {0}\n", e); 44 | } 45 | finally 46 | { 47 | Console.WriteLine("End of demo, press any key to exit."); 48 | Console.ReadKey(); 49 | } 50 | } 51 | 52 | /* 53 | Entry point to call methods that operate on Azure Cosmos DB resources in this sample 54 | */ 55 | public async Task GetStartedDemoAsync() 56 | { 57 | // Create a new instance of the Cosmos Client 58 | this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey); 59 | await this.CreateDatabaseAsync(); 60 | await this.CreateContainerAsync(); 61 | await this.AddItemsToContainerAsync(); 62 | await this.QueryItemsAsync(); 63 | await this.ReplaceFamilyItemAsync(); 64 | await this.DeleteFamilyItemAsync(); 65 | await this.DeleteDatabaseAndCleanupAsync(); 66 | } 67 | 68 | /* 69 | Create the database if it does not exist 70 | */ 71 | private async Task CreateDatabaseAsync() 72 | { 73 | // Create a new database 74 | this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId); 75 | Console.WriteLine("Created Database: {0}\n", this.database.Id); 76 | } 77 | 78 | /* 79 | Create the container if it does not exist. 80 | Specifiy "/LastName" as the partition key since we're storing family information, to ensure good distribution of requests and storage. 81 | */ 82 | private async Task CreateContainerAsync() 83 | { 84 | // Create a new container 85 | this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, "/LastName"); 86 | Console.WriteLine("Created Container: {0}\n", this.container.Id); 87 | } 88 | 89 | /* 90 | Add Family items to the container 91 | */ 92 | private async Task AddItemsToContainerAsync() 93 | { 94 | // Create a family object for the Andersen family 95 | Family andersenFamily = new Family 96 | { 97 | Id = "Andersen.1", 98 | LastName = "Andersen", 99 | Parents = new Parent[] 100 | { 101 | new Parent { FirstName = "Thomas" }, 102 | new Parent { FirstName = "Mary Kay" } 103 | }, 104 | Children = new Child[] 105 | { 106 | new Child 107 | { 108 | FirstName = "Henriette Thaulow", 109 | Gender = "female", 110 | Grade = 5, 111 | Pets = new Pet[] 112 | { 113 | new Pet { GivenName = "Fluffy" } 114 | } 115 | } 116 | }, 117 | Address = new Address { State = "WA", County = "King", City = "Seattle" }, 118 | IsRegistered = false 119 | }; 120 | 121 | // Read the item to see if it exists. Note ReadItemAsync will not throw an exception if an item does not exist. Instead, we check the StatusCode property off the response object. 122 | ItemResponse andersenFamilyResponse = await this.container.ReadItemAsync(andersenFamily.Id, new PartitionKey(andersenFamily.LastName)); 123 | 124 | if (andersenFamilyResponse.StatusCode == HttpStatusCode.NotFound) 125 | { 126 | // Create an item in the container representing the Andersen family. Note we provide the value of the partition key for this item, which is "Andersen" 127 | andersenFamilyResponse = await this.container.CreateItemAsync(andersenFamily, new PartitionKey(andersenFamily.LastName)); 128 | 129 | // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request. 130 | Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", andersenFamilyResponse.Resource.Id, andersenFamilyResponse.RequestCharge); 131 | } 132 | else 133 | { 134 | Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Resource.Id); 135 | } 136 | 137 | // Create a family object for the Wakefield family 138 | Family wakefieldFamily = new Family 139 | { 140 | Id = "Wakefield.7", 141 | LastName = "Wakefield", 142 | Parents = new Parent[] 143 | { 144 | new Parent { FamilyName = "Wakefield", FirstName = "Robin" }, 145 | new Parent { FamilyName = "Miller", FirstName = "Ben" } 146 | }, 147 | Children = new Child[] 148 | { 149 | new Child 150 | { 151 | FamilyName = "Merriam", 152 | FirstName = "Jesse", 153 | Gender = "female", 154 | Grade = 8, 155 | Pets = new Pet[] 156 | { 157 | new Pet { GivenName = "Goofy" }, 158 | new Pet { GivenName = "Shadow" } 159 | } 160 | }, 161 | new Child 162 | { 163 | FamilyName = "Miller", 164 | FirstName = "Lisa", 165 | Gender = "female", 166 | Grade = 1 167 | } 168 | }, 169 | Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, 170 | IsRegistered = true 171 | }; 172 | 173 | // Read the item to see if it exists 174 | ItemResponse wakefieldFamilyResponse = await this.container.ReadItemAsync(wakefieldFamily.Id, new PartitionKey(wakefieldFamily.LastName)); 175 | 176 | if (wakefieldFamilyResponse.StatusCode == HttpStatusCode.NotFound) 177 | { 178 | // Create an item in the container representing the Wakefield family. Note we provide the value of the partition key for this item, which is "Wakefield" 179 | wakefieldFamilyResponse = await this.container.CreateItemAsync(wakefieldFamily, new PartitionKey(wakefieldFamily.LastName)); 180 | 181 | // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request. 182 | Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", wakefieldFamilyResponse.Resource.Id, wakefieldFamilyResponse.RequestCharge); 183 | } 184 | else 185 | { 186 | Console.WriteLine("Item in database with id: {0} already exists\n", wakefieldFamilyResponse.Resource.Id); 187 | } 188 | } 189 | 190 | /* 191 | Run a query (using Azure Cosmos DB SQL syntax) against the container 192 | */ 193 | private async Task QueryItemsAsync() 194 | { 195 | var sqlQueryText = "SELECT * FROM c WHERE c.LastName = 'Andersen'"; 196 | 197 | Console.WriteLine("Running query: {0}\n", sqlQueryText); 198 | 199 | QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText); 200 | FeedIterator queryResultSetIterator = this.container.GetItemQueryIterator(queryDefinition); 201 | 202 | List families = new List(); 203 | 204 | while (queryResultSetIterator.HasMoreResults) 205 | { 206 | FeedResponse currentResultSet = await queryResultSetIterator.ReadNextAsync(); 207 | foreach (Family family in currentResultSet) 208 | { 209 | families.Add(family); 210 | Console.WriteLine("\tRead {0}\n", family); 211 | } 212 | } 213 | } 214 | 215 | /* 216 | Update an item in the container 217 | */ 218 | private async Task ReplaceFamilyItemAsync() 219 | { 220 | ItemResponse wakefieldFamilyResponse = await this.container.ReadItemAsync("Wakefield.7", new PartitionKey("Wakefield")); 221 | var itemBody = wakefieldFamilyResponse.Resource; 222 | 223 | // update registration status from false to true 224 | itemBody.IsRegistered = true; 225 | // update grade of child 226 | itemBody.Children[0].Grade = 6; 227 | 228 | // replace the item with the updated content 229 | wakefieldFamilyResponse = await this.container.ReplaceItemAsync(itemBody, itemBody.Id, new PartitionKey(itemBody.LastName)); 230 | Console.WriteLine("Updated Family [{0},{1}]\n. Body is now: {2}\n", itemBody.LastName, itemBody.Id, wakefieldFamilyResponse.Resource); 231 | } 232 | 233 | /* 234 | Delete an item in the container 235 | */ 236 | private async Task DeleteFamilyItemAsync() 237 | { 238 | var partitionKeyValue = "Wakefield"; 239 | var familyId = "Wakefield.7"; 240 | 241 | // Delete an item. Note we must provide the partition key value and id of the item to delete 242 | ItemResponse wakefieldFamilyResponse = await this.container.DeleteItemAsync(familyId, new PartitionKey(partitionKeyValue)); 243 | Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, familyId); 244 | } 245 | 246 | /* 247 | Delete the database and dispose of the Cosmos Client instance 248 | */ 249 | private async Task DeleteDatabaseAndCleanupAsync() 250 | { 251 | DatabaseResponse databaseResourceResponse = await this.database.DeleteAsync(); 252 | // Also valid: await this.cosmosClient.Databases["FamilyDatabase"].DeleteAsync(); 253 | 254 | Console.WriteLine("Deleted Database: {0}\n", this.databaseId); 255 | 256 | //Dispose of CosmosClient 257 | this.cosmosClient.Dispose(); 258 | } 259 | } 260 | } 261 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 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 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | languages: 3 | - csharp 4 | products: 5 | - azure 6 | - azure-cosmos-db 7 | - dotnet 8 | page_type: sample 9 | description: "This sample shows you how to use the Azure Cosmos DB service to store and access data from a .NET Core console application." 10 | --- 11 | 12 | # Developing a .NET Core console app using Azure Cosmos DB 13 | This sample shows you how to use the Azure Cosmos DB service to store and access data from a .NET Core console application. 14 | 15 | For a complete end-to-end walkthrough of creating this application, please refer to the [full tutorial on the Azure Cosmos DB documentation page](https://aka.ms/CosmosDotnetCoreGetStarted). 16 | 17 | ## Running this sample 18 | 19 | 1. Before you can run this sample, you must have the following prerequisites: 20 | - An active Azure Cosmos DB account - If you don't have an account, refer to the [Create a database account](https://docs.microsoft.com/azure/cosmos-db/create-sql-api-dotnet#create-a-database-account) article. 21 | - Visual Studio 2015 (or higher). 22 | 23 | 1. Clone this repository using Git for Windows (http://www.git-scm.com/), or download the zip file. 24 | 25 | 1. From Visual Studio, open the **CosmosGettingStartedDotnetCoreTutorial.sln** file from the root directory. 26 | 27 | 1. In Visual Studio Build menu, select **Build Solution** (or Press **Ctrl+Shift+B**). 28 | 29 | 1. Retrieve the URI and PRIMARY KEY (or SECONDARY KEY) values from the Keys blade of your Azure Cosmos DB account in the Azure portal. For more information on obtaining endpoint & keys for your Azure Cosmos DB account refer to [View, copy, and regenerate access keys and passwords](https://docs.microsoft.com/azure/cosmos-db/manage-account#keys) 30 | 31 | If you don't have an account, see [Create a database account](https://docs.microsoft.com/azure/cosmos-db/create-sql-api-dotnet#create-a-database-account) to set one up. 32 | 33 | 1. In the **Program.cs** file, located in the src directory, find **EndPointUri** and **PrimaryKey** and replace the placeholder values with the values obtained for your account. 34 | 35 | 36 | 37 | 38 | 1. You can now run and debug the application locally by pressing **F5** in Visual Studio. 39 | 40 | ## About the code 41 | The code included in this sample is intended to get you quickly started with a .NET Core console application that connects to Azure Cosmos DB. 42 | 43 | ## More information 44 | 45 | - [Azure Cosmos DB Documentation](https://docs.microsoft.com/azure/cosmos-db/index) 46 | - [Azure Cosmos DB .NET SDK for SQL API](https://docs.microsoft.com/azure/cosmos-db/sql-api-sdk-dotnet) 47 | - [Azure Cosmos DB .NET SDK Reference Documentation](https://docs.microsoft.com/dotnet/api/overview/azure/cosmosdb?view=azure-dotnet) 48 | --------------------------------------------------------------------------------