|
| 1 | +--- |
| 2 | +title: Manage Azure Cosmos DB SQL API resources using .Net V4 SDK |
| 3 | +description: Quickstart to build a console app using .Net V4 SDK to manage Azure Cosmos DB SQL API account resources. |
| 4 | +author: ealsur |
| 5 | +ms.author: maquaran |
| 6 | +ms.service: cosmos-db |
| 7 | +ms.subservice: cosmosdb-sql |
| 8 | +ms.devlang: dotnet |
| 9 | +ms.topic: quickstart |
| 10 | +ms.date: 11/04/2019 |
| 11 | +--- |
| 12 | +# Quickstart: Build a console app using the .Net V4 SDK to manage Azure Cosmos DB SQL API account resources. |
| 13 | + |
| 14 | +> [!div class="op_single_selector"] |
| 15 | +> * [.NET V3](create-sql-api-dotnet.md) |
| 16 | +> * [.NET V4](create-sql-api-dotnet-V4.md) |
| 17 | +> * [Java](create-sql-api-java.md) |
| 18 | +> * [Node.js](create-sql-api-nodejs.md) |
| 19 | +> * [Python](create-sql-api-python.md) |
| 20 | +> * [Xamarin](create-sql-api-xamarin-dotnet.md) |
| 21 | +
|
| 22 | +Get started with the Azure Cosmos DB SQL API client library for .NET. Follow the steps in this doc to install the .NET V4 (Azure.Cosmos) package, build an app, and try out the example code for basic CRUD operations on the data stored in Azure Cosmos DB. |
| 23 | + |
| 24 | +Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. You can use Azure Cosmos DB to quickly create and query key/value, document, and graph databases. Use the Azure Cosmos DB SQL API client library for .NET to: |
| 25 | + |
| 26 | +* Create an Azure Cosmos database and a container |
| 27 | +* Add sample data to the container |
| 28 | +* Query the data |
| 29 | +* Delete the database |
| 30 | + |
| 31 | +## Prerequisites |
| 32 | + |
| 33 | +* Azure subscription - [create one for free](https://azure.microsoft.com/free/) or you can [Try Azure Cosmos DB for free](https://azure.microsoft.com/try/cosmosdb/) without an Azure subscription, free of charge and commitments. |
| 34 | +* [NET Core 3 SDK](https://dotnet.microsoft.com/download/dotnet-core). You can verify which version is available in your environment by running `dotnet --version`. |
| 35 | + |
| 36 | +## Setting up |
| 37 | + |
| 38 | +This section walks you through creating an Azure Cosmos account and setting up a project that uses Azure Cosmos DB SQL API client library for .NET to manage resources. The example code described in this article creates a `FamilyDatabase` database and family members (each family member is an item) within that database. Each family member has properties such as `Id, FamilyName, FirstName, LastName, Parents, Children, Address,`. The `LastName` property is used as the partition key for the container. |
| 39 | + |
| 40 | +### <a id="create-account"></a>Create an Azure Cosmos account |
| 41 | + |
| 42 | +If you use the [Try Azure Cosmos DB for free](https://azure.microsoft.com/try/cosmosdb/) option to create an Azure Cosmos account, you must create an Azure Cosmos DB account of type **SQL API**. An Azure Cosmos DB test account is already created for you. You don't have to create the account explicitly, so you can skip this section and move to the next section. |
| 43 | + |
| 44 | +If you have your own Azure subscription or created a subscription for free, you should create an Azure Cosmos account explicitly. The following code will create an Azure Cosmos account with session consistency. The account is replicated in `South Central US` and `North Central US`. |
| 45 | + |
| 46 | +You can use Azure Cloud Shell to create the Azure Cosmos account. Azure Cloud Shell is an interactive, authenticated, browser-accessible shell for managing Azure resources. It provides the flexibility of choosing the shell experience that best suits the way you work, either Bash or PowerShell. For this quickstart, choose **Bash** mode. Azure Cloud Shell also requires a storage account, you can create one when prompted. |
| 47 | + |
| 48 | +Select the **Try It** button next to the following code, choose **Bash** mode select **create a storage account** and login to Cloud Shell. Next copy and paste the following code to Azure cloud shell and run it. The Azure Cosmos account name must be globally unique, make sure to update the `mysqlapicosmosdb` value before you run the command. |
| 49 | + |
| 50 | +```azurecli-interactive |
| 51 | +
|
| 52 | +# Set variables for the new SQL API account, database, and container |
| 53 | +resourceGroupName='myResourceGroup' |
| 54 | +location='southcentralus' |
| 55 | +
|
| 56 | +# The Azure Cosmos account name must be globally unique, make sure to update the `mysqlapicosmosdb` value before you run the command |
| 57 | +accountName='mysqlapicosmosdb' |
| 58 | +
|
| 59 | +# Create a resource group |
| 60 | +az group create \ |
| 61 | + --name $resourceGroupName \ |
| 62 | + --location $location |
| 63 | +
|
| 64 | +# Create a SQL API Cosmos DB account with session consistency and multi-master enabled |
| 65 | +az cosmosdb create \ |
| 66 | + --resource-group $resourceGroupName \ |
| 67 | + --name $accountName \ |
| 68 | + --kind GlobalDocumentDB \ |
| 69 | + --locations regionName="South Central US" failoverPriority=0 --locations regionName="North Central US" failoverPriority=1 \ |
| 70 | + --default-consistency-level "Session" \ |
| 71 | + --enable-multiple-write-locations true |
| 72 | +
|
| 73 | +``` |
| 74 | + |
| 75 | +The creation of the Azure Cosmos account takes a while, once the operation is successful, you can see the confirmation output. After the command completes successfully, sign into the [Azure portal](https://portal.azure.com/) and verify that the Azure Cosmos account with the specified name exists. You can close the Azure Cloud Shell window after the resource is created. |
| 76 | + |
| 77 | +### <a id="create-dotnet-core-app"></a>Create a new .NET app |
| 78 | + |
| 79 | +Create a new .NET application in your preferred editor or IDE. Open the Windows command prompt or a Terminal window from your local computer. You will run all the commands in the next sections from the command prompt or terminal. Run the following dotnet new command to create a new app with the name `todo`. The --langVersion parameter sets the LangVersion property in the created project file. |
| 80 | + |
| 81 | + ```bash |
| 82 | + dotnet new console –langVersion:8 -n todo |
| 83 | + ``` |
| 84 | + |
| 85 | +Change your directory to the newly created app folder. You can build the application with: |
| 86 | + |
| 87 | + ```bash |
| 88 | + cd todo |
| 89 | + dotnet build |
| 90 | + ``` |
| 91 | + |
| 92 | +The expected output from the build should look something like this: |
| 93 | + |
| 94 | +```bash |
| 95 | + Restore completed in 100.37 ms for C:\Users\user1\Downloads\CosmosDB_Samples\todo\todo.csproj. |
| 96 | + todo -> C:\Users\user1\Downloads\CosmosDB_Samples\todo\bin\Debug\netcoreapp3.0\todo.dll |
| 97 | + |
| 98 | +Build succeeded. |
| 99 | + 0 Warning(s) |
| 100 | + 0 Error(s) |
| 101 | + |
| 102 | +Time Elapsed 00:00:34.17 |
| 103 | +``` |
| 104 | + |
| 105 | +### <a id="install-package"></a>Install the Azure Cosmos DB package |
| 106 | + |
| 107 | +While still in the application directory, install the Azure Cosmos DB client library for .NET Core by using the dotnet add package command. |
| 108 | + |
| 109 | + ```bash |
| 110 | + dotnet add package Azure.Cosmos --version 1.0.0-preview1 |
| 111 | + ``` |
| 112 | + |
| 113 | +### Copy your Azure Cosmos account credentials from the Azure portal |
| 114 | + |
| 115 | +The sample application needs to authenticate to your Azure Cosmos account. To authenticate, you should pass the Azure Cosmos account credentials to the application. Get your Azure Cosmos account credentials by following these steps: |
| 116 | + |
| 117 | +1. Sign in to the [Azure portal](https://portal.azure.com/). |
| 118 | + |
| 119 | +1. Navigate to your Azure Cosmos account. |
| 120 | + |
| 121 | +1. Open the **Keys** pane and copy the **URI** and **PRIMARY KEY** of your account. You will add the URI and keys values to an environment variable in the next step. |
| 122 | + |
| 123 | +## <a id="object-model"></a>Object model |
| 124 | + |
| 125 | +Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB and the object model used to create and access these resources. The Azure Cosmos DB creates resources in the following order: |
| 126 | + |
| 127 | +* Azure Cosmos account |
| 128 | +* Databases |
| 129 | +* Containers |
| 130 | +* Items |
| 131 | + |
| 132 | +To learn in more about the hierarchy of different entities, see the [working with databases, containers, and items in Azure Cosmos DB](databases-containers-items.md) article. You will use the following .NET classes to interact with these resources: |
| 133 | + |
| 134 | +* CosmosClient - This class provides a client-side logical representation for the Azure Cosmos DB service. The client object is used to configure and execute requests against the service. |
| 135 | +* CreateDatabaseIfNotExistsAsync - This method creates (if doesn't exist) or gets (if already exists) a database resource as an asynchronous operation. |
| 136 | +* CreateContainerIfNotExistsAsync - This method creates (if it doesn't exist) or gets (if it already exists) a container as an asynchronous operation. You can check the status code from the response to determine whether the container was newly created (201) or an existing container was returned (200). |
| 137 | +* CreateItemAsync - This method creates an item within the container. |
| 138 | +* UpsertItemAsync - This method creates an item within the container if it doesn't already exist or replaces the item if it already exists. |
| 139 | +* GetItemQueryIterator - This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values. |
| 140 | +* DeleteAsync - Deletes the specified database from your Azure Cosmos account. `DeleteAsync` method only deletes the database. |
| 141 | + |
| 142 | + ## <a id="code-examples"></a>Code examples |
| 143 | + |
| 144 | +The sample code described in this article creates a family database in Azure Cosmos DB. The family database contains family details such as name, address, location, the associated parents, children, and pets. Before populating the data to your Azure Cosmos account, define the properties of a family item. Create a new class named `Family.cs` at the root level of your sample application and add the following code to it: |
| 145 | + |
| 146 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Family.cs)] |
| 147 | + |
| 148 | +### Add the using directives & define the client object |
| 149 | + |
| 150 | +From the project directory, open the `Program.cs` file in your editor and add the following using directives at the top of your application: |
| 151 | + |
| 152 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=Usings)] |
| 153 | + |
| 154 | + |
| 155 | +Add the following global variables in your `Program` class. These will include the endpoint and authorization keys, the name of the database, and container that you will create. Make sure to replace the endpoint and authorization keys values according to your environment. |
| 156 | + |
| 157 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=Constants)] |
| 158 | + |
| 159 | +Finally, replace the `Main` method: |
| 160 | + |
| 161 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=Main)] |
| 162 | + |
| 163 | +### Create a database |
| 164 | + |
| 165 | +Define the `CreateDatabaseAsync` method within the `program.cs` class. This method creates the `FamilyDatabase` if it doesn't already exist. |
| 166 | + |
| 167 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=CreateDatabaseAsync)] |
| 168 | + |
| 169 | +### Create a container |
| 170 | + |
| 171 | +Define the `CreateContainerAsync` method within the `Program` class. This method creates the `FamilyContainer` if it doesn't already exist. |
| 172 | + |
| 173 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=CreateContainerAsync)] |
| 174 | + |
| 175 | +### Create an item |
| 176 | + |
| 177 | +Create a family item by adding the `AddItemsToContainerAsync` method with the following code. You can use the `CreateItemAsync` or `UpsertItemAsync` methods to create an item: |
| 178 | + |
| 179 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=AddItemsToContainerAsync)] |
| 180 | + |
| 181 | +### Query the items |
| 182 | + |
| 183 | +After inserting an item, you can run a query to get the details of "Andersen" family. The following code shows how to execute the query using the SQL query directly. The SQL query to get the "Anderson" family details is: `SELECT * FROM c WHERE c.LastName = 'Andersen'`. Define the `QueryItemsAsync` method within the `Program` class and add the following code to it: |
| 184 | + |
| 185 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=QueryItemsAsync)] |
| 186 | + |
| 187 | +### Replace an item |
| 188 | + |
| 189 | +Read a family item and then update it by adding the `ReplaceFamilyItemAsync` method with the following code. |
| 190 | + |
| 191 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=ReplaceFamilyItemAsync)] |
| 192 | + |
| 193 | +### Delete an item |
| 194 | + |
| 195 | +Delete a family item by adding the `DeleteFamilyItemAsync` method with the following code. |
| 196 | + |
| 197 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=DeleteFamilyItemAsync)] |
| 198 | + |
| 199 | +### Delete the database |
| 200 | + |
| 201 | +Finally you can delete the database adding the `DeleteDatabaseAndCleanupAsync` method with the following code: |
| 202 | + |
| 203 | +[!code-csharp[Main](~/cosmos-dotnet-v4-getting-started/src/Program.cs?name=DeleteDatabaseAndCleanupAsync)] |
| 204 | + |
| 205 | +After you add all the required methods, save the `Program` file. |
| 206 | + |
| 207 | +## Run the code |
| 208 | + |
| 209 | +Next build and run the application to create the Azure Cosmos DB resources. |
| 210 | + |
| 211 | + ```bash |
| 212 | + dotnet run |
| 213 | + ``` |
| 214 | + |
| 215 | +The following output is generated when you run the application. You can also sign into the Azure portal and validate that the resources are created: |
| 216 | + |
| 217 | + ```bash |
| 218 | + Created Database: FamilyDatabase |
| 219 | + |
| 220 | + Created Container: FamilyContainer |
| 221 | + |
| 222 | + Created item in database with id: Andersen.1 |
| 223 | + |
| 224 | + Running query: SELECT * FROM c WHERE c.LastName = 'Andersen' |
| 225 | + |
| 226 | + Read {"id":"Andersen.1","LastName":"Andersen","Parents":[{"FamilyName":null,"FirstName":"Thomas"},{"FamilyName":null "FirstName":"Mary Kay"}],"Children":[{"FamilyName":null,"FirstName":"Henriette Thaulow","Gender":"female","Grade":5,"Pets": [{"GivenName":"Fluffy"}]}],"Address":{"State":"WA","County":"King","City":"Seattle"},"IsRegistered":false} |
| 227 | + |
| 228 | + Updated Family [Wakefield,Wakefield.7]. |
| 229 | + Body is now: {"id":"Wakefield.7","LastName":"Wakefield","Parents":[{"FamilyName":"Wakefield","FirstName":"Robin"} {"FamilyName":"Miller","FirstName":"Ben"}],"Children":[{"FamilyName":"Merriam","FirstName":"Jesse","Gender":"female","Grade":6 "Pets":[{"GivenName":"Goofy"},{"GivenName":"Shadow"}]},{"FamilyName":"Miller","FirstName":"Lisa","Gender":"female","Grade":1 "Pets":null}],"Address":{"State":"NY","County":"Manhattan","City":"NY"},"IsRegistered":true} |
| 230 | + |
| 231 | + Deleted Family [Wakefield,Wakefield.7] |
| 232 | + |
| 233 | + Deleted Database: FamilyDatabase |
| 234 | + |
| 235 | + End of demo, press any key to exit. |
| 236 | + ``` |
| 237 | + |
| 238 | +You can validate that the data is created by signing into the Azure portal and see the required items in your Azure Cosmos account. |
| 239 | + |
| 240 | +## Clean up resources |
| 241 | + |
| 242 | +When no longer needed, you can use the Azure CLI or Azure PowerShell to remove the Azure Cosmos account and the corresponding resource group. The following command shows how to delete the resource group by using the Azure CLI: |
| 243 | + |
| 244 | +```azurecli |
| 245 | +az group delete -g "myResourceGroup" |
| 246 | +``` |
| 247 | + |
| 248 | +## Next steps |
| 249 | + |
| 250 | +In this quickstart, you learned how to create an Azure Cosmos account, create a database and a container using a .NET Core app. You can now import additional data to your Azure Cosmos account with the instructions int the following article. |
| 251 | + |
| 252 | +> [!div class="nextstepaction"] |
| 253 | +> [Import data into Azure Cosmos DB](import-data.md) |
0 commit comments