Sunteți pe pagina 1din 28

Lab 4 - Building Globally Distributed Databases

with Cosmos DB
Estimated Time: 90 minutes

Pre-requisites: It is assumed that the case study for this lab has already been read. It is assumed that the
content and lab for module 1: Azure for the Data Engineer has also been completed

Lab files: The files for this lab are located in the Allfiles\Labfiles\Starter\DP-200.4 folder.

Lab overview

The students will be able to describe and demonstrate the capabilities that Azure Cosmos DB can bring to an
organization. They will be able to create a Cosmos DB instance and show how to upload and query data
through a portal and through a .Net application. They will then be able to demonstrate how to enable global
scale of the Cosmos DB database.

Lab objectives

After completing this lab, you will be able to:

1. Create an Azure Cosmos DB database built to scale


2. Insert and query data in your Azure Cosmos DB database
3. Distribute your data globally with Azure Cosmos DB
4. (optional) Build a .NET Core app for Azure Cosmos DB in Visual Studio Code

Scenario

The developers and Information Services department at AdventureWorks are aware that a new service
known as Cosmos DB recently released on Azure can provided planetary scale access to data in near real-
time. They want to understand the capability that the service can offer and how it can bring value to
AdventureWorks, and in what circumstances.

The Information Services department want to understand how the service can be setup and how data can be
uploaded. The developers would like to see an example of an application that can be used to upload data to
the Cosmos. Both would like to understand how the claim of planetary scale can be met.

At the end of this lab, you will:

1. Created an Azure Cosmos DB database built to scale


2. Inserted and queried data in your Azure Cosmos DB database
3. Distributed your data globally with Azure Cosmos DB
4. (optional) Built a .NET Core app for Azure Cosmos DB in Visual Studio Code

IMPORTANT: As you go through this lab, make a note of any issue(s) that you have encountered in any
provisioning or configuration tasks and log it in the table in the document located at \Labfiles\DP-200-
Issues-Doc.docx. Document the Lab number, note the technology, Describe the issue, and what was the
resolution. Save this document as you will refer back to it in a later module.

Exercise 1: Create an Azure Cosmos DB database built to scale

Estimated Time: 10 minutes

Individual exercise

The main task for this exercise are as follows:

1. Create an Azure Cosmos DB instance

Task 1: Create an Azure Cosmos DB instance

1. In the Azure portal, if neccesary click on the Home hyperlink.

2. Navigate to the + Create a resource icon.

3. In the New screen, click in the Search the Marketplace text box, and type the word Cosmos.
Click Azure Cosmos DB in the list that appears.

4. In the Azure Cosmos DB screen, click Create.

5. From the Create Azure Cosmos DB Account screen, create an Azure Cosmos DB Account with the
following settings:

o In the Project details of the screen, type in the following information

 Subscription: the name of the subscription you are using in this lab

 Resource group: awrgstudxx, where xx are your initials

o In the Instance details of the screen, type in the following information

 Account name: awcdbstudxx, where xx are your initials.

 API: Core(SQL)

 Apache Spark: None

 Location: the name of the Azure region which is closest to the lab location and
where you can provision Azure VMs.

 Leave the remaining options to the default settings


6. In the Create Azure Cosmos DB Account blade, click Review + create.

7. After the validation of the Create Azure Cosmos DB Account blade, click Create.

Note: The provision will takes approximately 5 minutes. What is often avoided in these labs is a
description of the additional tabs when you provision any service in Azure. You may notice that in
the provisioning screen there will be additional tabs such as Network, Tags or Advanced. This
enables you to define any customized settings for a service. For example, the network tab of many
services enables you to define the configuration of virtual networks, so that you are able to control
and secure the network traffic against a given data service. The Tags option are name/value pairs
that enable you to categorize resources and view consolidated billing by applying the same tag to
multiple resources and resource groups. Advanced tabs will vary dependant on the service that has
it. But it is important to note that you have control over these areas and you wil want to collaborate
with your Network admins or indeed your finance department to see how these options should be
configured.

8. When the provisioning is complete, the "Your deployment is complete" screen appears, click on Go
to resource and move onto the next exercise.

Result In this exercise, you have provisioned an Azure Cosmos DB Account


Exercise 2: Insert and query data in your Azure Cosmos DB
database

Estimated Time: 20 minutes

Individual exercise

The main tasks for this exercise are as follows:

1. Setup your Azure Cosmos DB database and container

2. Add data using the portal

3. Run queries in the Azure portal

4. Run complex operations on your data

Task 1: Setup your Azure Cosmos DB container and database

1. In the Azure portal, once the deployment of Cosmos DB is completed, click on the Go to
resources button.

2. In the Cosmos DB screen, click on the Overview button.

3. In the awcdbstudxx screen, click + Add Container. This opens up the awcdbstudxx Data


Explorer screen with the Add Container blade.

4. In the Add Container blade, create a Products database with a container named Clothing with the
following settings:

o Database id: Products

o Throughput: 400

o Container id: Clothing

o Partition key: /productId

o Leave the remaining options with their default values


5. In the Add Container screen, click OK

Task 2: Add data using the portal

1. In the awcdbstudcto - Data Explorer screen, on the Data Explorer toolbar, opposite the button for
New Container, click on the Open Full Screen button. In the Open Full Screen dialog box,
click Open. A new tab opens up in Microsoft Edge.

2. In the SQL API pane, click in the refresh icon, and then expand Products, followed by Clothing and
click on Items.

3. In the Documents pane, click on the icon for New Item. A new document appears with a sample
JSON that you will now replace.

4. Copy the following code and paste it into the Documents tab:

5. {
6. "id": "1",
7. "productId": "33218896",
8. "category": "Women's Clothing",
9. "manufacturer": "Contoso Sport",
10. "description": "Quick dry crew neck t-shirt",
11. "price": "14.99",
12. "shipping": {
13. "weight": 1,
14. "dimensions": {
15. "width": 6,
16. "height": 8,
17. "depth": 1
18. }
19. }
}

20. Once you've added the JSON to the Documents tab, click Save.

21. In the Documents pane, click on the icon for New Item.

22. Copy the following code and paste it into the Items tab:

23. {
24. "id": "2",
25. "productId": "33218897",
26. "category": "Women's Outerwear",
27. "manufacturer": "Contoso",
28. "description": "Black wool pea-coat",
29. "price": "49.99",
30. "shipping": {
31. "weight": 2,
32. "dimensions": {
33. "width": 8,
34. "height": 11,
35. "depth": 3
36. }
37. }
}
38. Once you've added the JSON to the Documents tab, click Save.

39. You can see each document that has been saved by clicking each document on the left-hand menu.
The first item with id of 1, will have a value of 33218896, which is named after the productid, the
second item will be 33218897

Task 3: Run queries in the Azure portal.

1. In the Azure portal, in the Items screen, click on the button New SQL Query that is above the SQL
API Blade.

Note: A Query 1 screen tab appears which shows the query SELECT * FROM c .

2. Replace the query that returns a JSON file showing details for productId 1.

3. SELECT *
4. FROM Products p
WHERE p.id ="1"

5. Click on the Execute Query icon. The following result is returned

6. [
7. {
8. "id": "1",
9. "productId": "33218896",
10. "category": "Women's Clothing",
11. "manufacturer": "Contoso Sport",
12. "description": "Quick dry crew neck t-shirt",
13. "price": "14.99",
14. "shipping": {
15. "weight": 1,
16. "dimensions": {
17. "width": 6,
18. "height": 8,
19. "depth": 1
20. }
21. },
22. "_rid": "I2YsALxG+-EBAAAAAAAAAA==",
23. "_self": "dbs/I2YsAA==/colls/I2YsALxG+-E=/docs/I2YsALxG+-EBAAAAAAAAAA==/",
24. "_etag": "\"0000844e-0000-1a00-0000-5ca79f840000\"",
25. "_attachments": "attachments/",
26. "_ts": 1554489220
27. }
]

28. In the existing query window. Write a query that returns the id, manufacturer and description in a
JSON file for productId

29. SELECT
30. p.id,
31. p.manufacturer,
32. p.description
33. FROM Products p
WHERE p.id ="1"

34. Click on the Execute Query icon. The following result is returned

35. [
36. {
37. "id": "1",
38. "manufacturer": "Contoso Sport",
39. "description": "Quick dry crew neck t-shirt"
40. }
]

41. In the existing query window, write a query that returns returns the price, description, and product ID
for all products, ordered by price, in ascending order.

42. SELECT p.price, p.description, p.productId


43. FROM Products p
ORDER BY p.price ASC

44. Click on the Execute Query icon. The following result is returned

45. [
46. {
47. "price": "14.99",
48. "description": "Quick dry crew neck t-shirt",
49. "productId": "33218896"
50. },
51. {
52. "price": "49.99",
53. "description": "Black wool pea-coat",
54. "productId": "33218897"
55. }
]

Task 4: Run complex operations on your data

1. In the Azure portal, in the Items screen, click on the button New Stored Procedure.

Note: A New Stored Procedure screen appears which shows a sample stored procedure .

2. In the New Stored Procedure screen, in the Stored Procedure Id text box,


type createMyDocument.

3. Use the following code to create a stored procedure in the Stored Procedure Body.

4. function createMyDocument() {
5. var context = getContext();
6. var collection = context.getCollection();
7.
8. var doc = {
9. "id": "3",
10. "productId": "33218898",
11. "description": "Contoso microfleece zip-up jacket",
12. "price": "44.99"
13. };
14.
15. var accepted = collection.createDocument(collection.getSelfLink(),
16. doc,
17. function (err, documentCreated) {
18. if (err) throw new Error('Error' + err.message);
19. context.getResponse().setBody(documentCreated)
20. });
21. if (!accepted) return;
}

22. In the New Stored Procedure screen, click Save.

23. In the New Stored Procedure screen, click Execute.

24. In the Input Parameters screen, type should be set to string, and value set to 33218898 in


the Partition Key Value text box, and then click Execute.

The following result is returned

```JSON
{
"id": "3",
"productId": "33218898",
"description": "Contoso microfleece zip-up jacket",
"price": "44.99",
"_rid": "I2YsALxG+-EDAAAAAAAAAA==",
"_self": "dbs/I2YsAA==/colls/I2YsALxG+-E=/docs/I2YsALxG+-EDAAAAAAAAAA==/",
"_etag": "\"0000874e-0000-1a00-0000-5ca7a7050000\"",
"_attachments": "attachments/"
}
```

1. In the Azure portal, in the Data Explorer full screen, click on the drop down button for New Stored
Procedure and click New UDF .

Note: A New UDF 1 screen appears which shows function userDefinedFunction(){}

2. In the New Defined Function screen, in the User Defined Function Id text box, type producttax.

3. Use the following code to create a user defined function in the user defined function Body.

4. function producttax(price) {
5. if (price == undefined)
6. throw 'no input';
7.
8. var amount = parseFloat(price);
9.
10. if (amount < 1000)
11. return amount * 0.1;
12. else if (amount < 10000)
13. return amount * 0.2;
14. else
15. return amount * 0.4;
}

16. In the New UDF 1 screen, click Save.

17. Click on the Query 1 tab, and replace the existing query with the following query:

SELECT c.id, c.productId, c.price, udf.producttax(c.price) AS producttax FROM c

18. In the Query 1 screen, click Execute Query.

The following result is returned

```JSON
[
{
"id": "1",
"productId": "33218896",
"price": "14.99",
"producttax": 1.499
},
{
"id": "2",
"productId": "33218897",
"price": "49.99",
"producttax": 4.9990000000000005
},
{
"id": "3",
"productId": "33218898",
"price": "44.99",
"producttax": 4.4990000000000005
}
]
```

Exercise 3: Distribute your data globally with Azure Cosmos DB

Estimated Time: 15 minutes

Individual exercise

The main tasks for this exercise are as follows:

1. Replicate Data to Multiple Regions

2. Managing Failover

Task 1: Replicate Data to Multiple Regions

1. In Microsoft Edge, click on the tab that states awcdbstudxx - Data Explorer...

2. If a message appears that states "Connection error", click on the button Refresh.


3. In the awcdbstudxx - Data Explorer window, in the blade, click on Replicate data globally.

4. On the world map, single click a data center location within the continent you reside, and click
on Save.

Note The provisioning of the additional data centers will take approximately 7 minutes

Task 2: Managing Failover.

1. In the awcdbstudxx - Replicate data globally window, click on Manual Failover.

2. Click on the Read Region datacenter location, then click on the check box next to "I understand and
agree to trigger a failover on my current Write Region.", and then click on OK.

Note The Manual Failover will take approximately 3 minutes. The screen will look as follows. Note the icon
colors have changed
1. In the awcdbstudxx - Replicate data globally window, click on Automatic Failover

2. In the "Automatic Failover" screen, click on the ON button, and then click on OK.

Note The provisioning of the Automatic Failover will take approximately 3 minutes.

If time permits

Note: If you have completed the labs so far and there is time, ask the instructor if you can do exercise 4. It is
an example of building an application against Cosmos DB. This is not an exam requirement for DP200, and
this lab show what is possible

Exercise 4: Build a .NET Core app for Azure Cosmos DB in Visual


Studio Code

Estimated Time: 45 minutes

Individual exercise

The main tasks for this exercise are as follows:

1. Enable Azure Cosmos DB resources in Visual Studio Code

2. Setup an application in Visual Studio Code


3. Create, read, update, and delete NoSQL data programmatically

4. Query using the Azure Cosmos DB .NET Core SDK

5. Create and run stored procedures from your application

Task 1: Enable Azure Cosmos DB resources in Visual Studio Code

1. Open up Visual Studio Code.

2. On the left hand menu, click the extensions button.

3. In the Search Extensions in Marketplace text box, type Cosmos DB and click on Azure Cosmos DB. A
document appears in Visual Studio Code and then click on install

Note: A moving bar will appear whilst the extension is being installed. Then a tick will appear next to
Installed once completed.

4. After installation is complete, click Reload.

5. In the Search Extensions in Marketplace text box, type Azure Account and click on Azure Account
extension. A document appears in Visual Studio Code and then click on install

Note: A moving bar will appear whilst the extension is being installed. Then a tick will appear next to
Installed once completed.

6. After installation is complete, click Reload.

7. In Visual Studio Code, sign in to Azure by clicking View, Command Palette and typing Azure: Sign


In.

Note: Follow the prompts in the web browser to pick an account which authenticates your Visual
Studio Code session. A message in the browser will confirm that you are signed in. You can close
down this tab.

8. In Visual Studio Code, click the Azure icon on the left menu, under Cosmos DB, right-click your
Subscription, and click Create Account.

9. In Visual Studio Code, an Open Folder dialog box appears.

10. Create a new folder named learning-module in the location of your choice, and then click Select
Folder.

Note: It is possible at this point that Visual Studio Code restarts as you are setting up your working
folder. As a result you have to re- open you lab documentation.

11. In Visual Studio Code, click the Azure icon on the left menu, under Cosmos DB, right-click
your Subscription, and click Create Account.
12. In the text box at the top of the screen named Create new Cosmos DB Account, enter a unique
name for your Azure Cosmos DB account, named xxcosmos, where xx are your initials and then
press Enter on the keyboard.

13. Next, select SQL (DocumentDB), then select the awrgstudxx resource group, and then select
a location closest to you.

Note: A bar will appear at the bottom of Visual Studio Code stating "Creating Cosmos DB Account..."
and will take approximately 5 minutes. The bar will change to state that the creation has occurred
successfully.

14. After the account is created, expand your Azure subscription in the Azure: Cosmos DB pane and the
extension displays the new Azure Cosmos DB account.

15. Right-click your new account, and then click Create Database.

16. In the input palette at the top of the screen, type Users for the database name and press Enter.

17. Enter WebCustomers for the collection name and press Enter.

18. Enter userId for the partition key and press Enter.

19. Finally, confirm 1000 for the initial throughput capacity and press Enter.

20. Expand the account in the Azure: Cosmos DB pane, and the new Users database and WebCustomers
collection are displayed.

Task 2: Setup an application in Visual Studio Code

1. Ensure that file auto-save is enabled by clicking on the File menu and checking Auto Save if it is
blank. You will be copying in several blocks of code, and this will ensure you are always operating
against the latest edits of your files.

2. Open the integrated terminal from Visual Studio Code by selecting View, Terminal from the main
menu.

3. Click in the terminal window, press Enter on the keyboard and then copy and paste the following
command.

dotnet new console


Note: This command creates a Program.cs file in your learning-module folder with a basic "Hello
World" program already written, along with a C# project file named learning-module.csproj.

4. In the terminal window, copy and paste the following command to run the "Hello World!" program.

dotnet run

5. At the terminal prompt, copy and paste the following command block to install the required NuGet
packages.

6. dotnet add package System.Net.Http


7. dotnet add package System.Configuration
8. dotnet add package System.Configuration.ConfigurationManager
9. dotnet add package Microsoft.Azure.DocumentDB.Core
10. dotnet add package Newtonsoft.Json
11. dotnet add package System.Threading.Tasks
12. dotnet add package System.Linq
dotnet restore

13. The terminal screen will load package and display the command at the end dotnet restore, in the
terminal window press Enter.

14. At the top of the Explorer pane, click Program.cs to open the file. Add the following using
statements after using System.

15. using System.Configuration;


16. using System.Linq;
17. using System.Threading.Tasks;
18. using System.Net;
19. using Microsoft.Azure.Documents;
20. using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
Important: Wait for about 15 seconds until you will get a message about adding required missing assets,
click Yes.

1. In the learning-module folder, create a new file named App.config, and add the following code:

2. <?xml version="1.0" encoding="utf-8"?>


3. <configuration>
4. <appSettings>
5. <add key="accountEndpoint" value="<replace with your Endpoint URL>" />
6. <add key="accountKey" value="<replace with your Primary Key>" />
7. </appSettings>
</configuration>

8. Copy your connection string by clicking the Azure icon on the left, expanding your
Subscription, right-clicking your new Azure Cosmos DB account, and then clicking Copy
Connection String.

9. Paste the connection string into the end of the App.config file, and then copy
the AccountEndpoint portion from the connection string into the accountEndpoint value in
App.config.

10. Now copy the AccountKey value from the connection string into the accountKey value, and
then delete the original connection string you copied in.

11. Your final App.config file looks similar to this.

12. <?xml version="1.0" encoding="utf-8"?>


13. <configuration>
14. <appSettings>
15. <add key="accountEndpoint" value="https://my-
account.documents.azure.com:443/" />
16. <add key="accountKey"
value="6e7sRxunccGEeO7IVlMdeFt5BdsllfSGLYc28KyjzkESiCu7tfWbTaZXAErt2v88gOcMbOYgwp1q4N
YDifD7ew==" />
17. </appSettings>
</configuration>
18. At the terminal prompt, copy and paste the following command to run the program.

dotnet run
Note: The program displays Hello World! in the terminal.

19. In the Explorer pane, click Program.cs to open the file. Add the following to the beginning of the
Program class.

private DocumentClient client;

20. Add a new asynchronous task to create a new client, and check whether the Users database exists by
adding the following method after the Main method.

21. private async Task BasicOperations()


22. {
23. this.client = new DocumentClient(new
Uri(ConfigurationManager.AppSettings["accountEndpoint"]),
ConfigurationManager.AppSettings["accountKey"]);
24.
25. await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "Users" });
26.
27. await
this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Us
ers"), new DocumentCollection { Id = "WebCustomers" });
28.
29. Console.WriteLine("Database and collection validation complete");
}

30. In the integrated terminal, again, copy and paste the following command to run the program to
ensure that the code runs. "Hello World!" is returned in the console.

dotnet run

31. Copy and paste the following code into the Main method, overwriting the
current Console.WriteLine("Hello World!"); code:

32. try
33. {
34. Program p = new Program();
35. p.BasicOperations().Wait();
36. }
37. catch (DocumentClientException de)
38. {
39. Exception baseException = de.GetBaseException();
40. Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode,
de.Message, baseException.Message);
41. }
42. catch (Exception e)
43. {
44. Exception baseException = e.GetBaseException();
45. Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
46. }
47. finally
48. {
49. Console.WriteLine("End of demo, press any key to exit.");
50. Console.ReadKey();
}
51. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

52. The following result should be displayed

53. Database and collection validation complete


End of demo, press any key to exit.
Result In this exercise, you have created a client side application that can connect to Azure Cosmos DB

Task 3: Create, read, update, and delete NoSQL data programmatically

Create Documents

1. Create a User class that represents the objects to store in Azure Cosmos DB. We will also
create OrderHistory and ShippingPreference classes that are used within User. Note that
documents must have an Id property serialized as id in JSON.

2. To create these classes, copy and paste the


following User, OrderHistory, ShippingPreference and CouponsUsed classes underneath
the BasicOperations method.

3. public class User


4. {
5. [JsonProperty("id")]
6. public string Id { get; set; }
7. [JsonProperty("userId")]
8. public string UserId { get; set; }
9. [JsonProperty("lastName")]
10. public string LastName { get; set; }
11. [JsonProperty("firstName")]
12. public string FirstName { get; set; }
13. [JsonProperty("email")]
14. public string Email { get; set; }
15. [JsonProperty("dividend")]
16. public string Dividend { get; set; }
17. [JsonProperty("OrderHistory")]
18. public OrderHistory[] OrderHistory { get; set; }
19. [JsonProperty("ShippingPreference")]
20. public ShippingPreference[] ShippingPreference { get; set; }
21. [JsonProperty("CouponsUsed")]
22. public CouponsUsed[] Coupons { get; set; }
23. public override string ToString()
24. {
25. return JsonConvert.SerializeObject(this);
26. }
27. }
28.
29. public class OrderHistory
30. {
31. public string OrderId { get; set; }
32. public string DateShipped { get; set; }
33. public string Total { get; set; }
34. }
35.
36. public class ShippingPreference
37. {
38. public int Priority { get; set; }
39. public string AddressLine1 { get; set; }
40. public string AddressLine2 { get; set; }
41. public string City { get; set; }
42. public string State { get; set; }
43. public string ZipCode { get; set; }
44. public string Country { get; set; }
45. }
46.
47. public class CouponsUsed
48. {
49. public string CouponCode { get; set; }
50.
51. }
52.
53. private void WriteToConsoleAndPromptToContinue(string format, params object[] args)
54. {
55. Console.WriteLine(format, args);
56. Console.WriteLine("Press any key to continue ...");
57. Console.ReadKey();
}

58. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

59. The following result should be displayed

60. Database and collection validation complete


61. End of demo, press any key to exit.

62. Now copy and paste the CreateUserDocumentIfNotExists task under


the WriteToConsoleAndPromptToContinue method at the end of the Program.cs file.

63. private async Task CreateUserDocumentIfNotExists(string databaseName, string


collectionName, User user)
64. {
65. try
66. {
67. await
this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName,
collectionName, user.Id), new RequestOptions { PartitionKey = new
PartitionKey(user.UserId) });
68. this.WriteToConsoleAndPromptToContinue("User {0} already exists in the
database", user.Id);
69. }
70. catch (DocumentClientException de)
71. {
72. if (de.StatusCode == HttpStatusCode.NotFound)
73. {
74. await
this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName,
collectionName), user);
75. this.WriteToConsoleAndPromptToContinue("Created User {0}", user.Id);
76. }
77. else
78. {
79. throw;
80. }
81. }
}

82. Then, return to the BasicOperations method and add the following to the end of that method.

83. User yanhe = new User


84. {
85. Id = "1",
86. UserId = "yanhe",
87. LastName = "He",
88. FirstName = "Yan",
89. Email = "yanhe@contoso.com",
90. OrderHistory = new OrderHistory[]
91. {
92. new OrderHistory {
93. OrderId = "1000",
94. DateShipped = "08/17/2018",
95. Total = "52.49"
96. }
97. },
98. ShippingPreference = new ShippingPreference[]
99. {
100. new ShippingPreference {
101. Priority = 1,
102. AddressLine1 = "90 W 8th St",
103. City = "New York",
104. State = "NY",
105. ZipCode = "10001",
106. Country = "USA"
107. }
108. },
109. };
110.
111. await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", yanhe);
112.
113. User nelapin = new User
114. {
115. Id = "2",
116. UserId = "nelapin",
117. LastName = "Pindakova",
118. FirstName = "Nela",
119. Email = "nelapin@contoso.com",
120. Dividend = "8.50",
121. OrderHistory = new OrderHistory[]
122. {
123. new OrderHistory {
124. OrderId = "1001",
125. DateShipped = "08/17/2018",
126. Total = "105.89"
127. }
128. },
129. ShippingPreference = new ShippingPreference[]
130. {
131. new ShippingPreference {
132. Priority = 1,
133. AddressLine1 = "505 NW 5th St",
134. City = "New York",
135. State = "NY",
136. ZipCode = "10001",
137. Country = "USA"
138. },
139. new ShippingPreference {
140. Priority = 2,
141. AddressLine1 = "505 NW 5th St",
142. City = "New York",
143. State = "NY",
144. ZipCode = "10001",
145. Country = "USA"
146. }
147. },
148. Coupons = new CouponsUsed[]
149. {
150. new CouponsUsed{
151. CouponCode = "Fall2018"
152. }
153. }
154. };
155.
await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin);

156. In the integrated terminal, again, copy and paste the following command to run the program
to ensure it runs.

dotnet run

157. The following result should be displayed

158. Database and collection validation complete


159. Created User 1
160. Press any key to continue ...
161. Created User 2
162. Press any key to continue ...
163. End of demo, press any key to exit.

Read Documents

1. To read documents from the database, copy in the following code and place after
the WriteToConsoleAndPromptToContinue method in the Program.cs file.

2. private async Task ReadUserDocument(string databaseName, string collectionName, User


user)
3. {
4. try
5. {
6. await
this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName,
collectionName, user.Id), new RequestOptions { PartitionKey = new
PartitionKey(user.UserId) });
7. this.WriteToConsoleAndPromptToContinue("Read user {0}", user.Id);
8. }
9. catch (DocumentClientException de)
10. {
11. if (de.StatusCode == HttpStatusCode.NotFound)
12. {
13. this.WriteToConsoleAndPromptToContinue("User {0} not read", user.Id);
14. }
15. else
16. {
17. throw;
18. }
19. }
}

20. Copy and paste the following code to the end of the BasicOperations method, after the await
this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin); line:

await this.ReadUserDocument("Users", "WebCustomers", yanhe);

21. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

22. The following result should be displayed

23. Database and collection validation complete


24. User 1 already exists in the database
25. Press any key to continue ...
26. User 2 already exists in the database
27. Press any key to continue ...
28. Read user 1
29. Press any key to continue ...
30. End of demo, press any key to exit.

Replace Documents

1. Copy and paste the ReplaceUserDocument method after the ReadUserDocument method in the


Program.cs file.

2. private async Task ReplaceUserDocument(string databaseName, string collectionName,


User updatedUser)
3. {
4. try
5. {
6. await
this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName,
collectionName, updatedUser.Id), updatedUser, new RequestOptions { PartitionKey = new
PartitionKey(updatedUser.UserId) });
7. this.WriteToConsoleAndPromptToContinue("Replaced last name for {0}",
updatedUser.LastName);
8. }
9. catch (DocumentClientException de)
10. {
11. if (de.StatusCode == HttpStatusCode.NotFound)
12. {
13. this.WriteToConsoleAndPromptToContinue("User {0} not found for
replacement", updatedUser.Id);
14. }
15. else
16. {
17. throw;
18. }
19. }
}

20. Copy and paste the following code to the end of the BasicOperations method, after the await
this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin); line.

21. yanhe.LastName = "Suh";


await this.ReplaceUserDocument("Users", "WebCustomers", yanhe);

22. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

23. The following result should be displayed

24. Database and collection validation complete


25. User 1 already exists in the database
26. Press any key to continue ...
27. User 2 already exists in the database
28. Press any key to continue ...
29. Replaced last name for Suh
30. Press any key to continue ...
31. Read user 1
32. Press any key to continue ...
33. End of demo, press any key to exit

Delete Documents

1. Copy and paste the DeleteUserDocument method underneath


your ReplaceUserDocument method.

2. private async Task DeleteUserDocument(string databaseName, string collectionName,


User deletedUser)
3. {
4. try
5. {
6. await
this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName,
collectionName, deletedUser.Id), new RequestOptions { PartitionKey = new
PartitionKey(deletedUser.UserId) });
7. Console.WriteLine("Deleted user {0}", deletedUser.Id);
8. }
9. catch (DocumentClientException de)
10. {
11. if (de.StatusCode == HttpStatusCode.NotFound)
12. {
13. this.WriteToConsoleAndPromptToContinue("User {0} not found for deletion",
deletedUser.Id);
14. }
15. else
16. {
17. throw;
18. }
19. }
}

20. Copy and paste the following code to the end of the BasicOperations method.

await this.DeleteUserDocument("Users", "WebCustomers", yanhe);

21. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

22. The following result should be displayed

23. Database and collection validation complete


24. User 1 already exists in the database
25. Press any key to continue ...
26. User 2 already exists in the database
27. Press any key to continue ...
28. Replaced last name for Suh
29. Press any key to continue ...
30. Read user 1
31. Press any key to continue ...
32. Deleted user 1
33. End of demo, press any key to exit.

Task 4: Query using the Azure Cosmos DB .NET Core SDK

1. The following sample shows how a query could be performed in SQL, LINQ, or LINQ lambda from
your .NET code. Copy the code and add it after private async Task
CreateUserDocumentIfNotExists towards the end of the Program.cs file.

2. private void ExecuteSimpleQuery(string databaseName, string collectionName)


3. {
4. // Set some common query options
5. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1,
EnableCrossPartitionQuery = true };
6.
7. // Here we find nelapin via their LastName
8. IQueryable<User> userQuery = this.client.CreateDocumentQuery<User>(
9. UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
queryOptions)
10. .Where(u => u.LastName == "Pindakova");
11.
12. // The query is executed synchronously here, but can also be executed
asynchronously via the IDocumentQuery<T> interface
13. Console.WriteLine("Running LINQ query...");
14. foreach (User user in userQuery)
15. {
16. Console.WriteLine("\tRead {0}", user);
17. }
18.
19. // Now execute the same query via direct SQL
20. IQueryable<User> userQueryInSql = this.client.CreateDocumentQuery<User>(
21. UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
22. "SELECT * FROM User WHERE User.lastName = 'Pindakova'", queryOptions );
23.
24. Console.WriteLine("Running direct SQL query...");
25. foreach (User user in userQueryInSql)
26. {
27. Console.WriteLine("\tRead {0}", user);
28. }
29.
30. Console.WriteLine("Press any key to continue ...");
31. Console.ReadKey();
}

32. Copy and paste the following code to your BasicOperations method, before the await
this.DeleteUserDocument("Users", "WebCustomers", yanhe); line.

this.ExecuteSimpleQuery("Users", "WebCustomers");

33. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

34. The following result should be displayed

35. Database and collection validation complete


36. Created User 1
37. Press any key to continue ...
38. User 2 already exists in the database
39. Press any key to continue ...
40. Replaced last name for Suh
41. Press any key to continue ...
42. Read user 1
43. Press any key to continue ...
44. Running LINQ query...
45. Read
{"id":"2","userId":"nelapin","lastName":"Pindakova","firstName":"Nela","email":"nelap
in@contoso.com","dividend":"8.50","OrderHistory":
[{"OrderId":"1001","DateShipped":"08/17/2018","Total":"105.89"}],"ShippingPreference"
:[{"Priority":1,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"},
{"Priority":2,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"}],"CouponsUsed":
[{"CouponCode":"Fall2018"}]}
46. Running direct SQL query...
47. Read
{"id":"2","userId":"nelapin","lastName":"Pindakova","firstName":"Nela","email":"nelap
in@contoso.com","dividend":"8.50","OrderHistory":
[{"OrderId":"1001","DateShipped":"08/17/2018","Total":"105.89"}],"ShippingPreference"
:[{"Priority":1,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"},
{"Priority":2,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"}],"CouponsUsed":
[{"CouponCode":"Fall2018"}]}
48. Press any key to continue ...
49. Deleted user 1
50. End of demo, press any key to exit.
Task 5: Create and run stored procedures from your application

1. In Visual Studio Code, in the Azure: Cosmos DB tab, expand your Azure Cosmos DB


account, Users, and then WebCustomers and then right-click Stored Procedures and then
click Create Stored Procedure.

2. In the text box at the top of the screen, type UpdateOrderTotal and press Enter to give the stored
procedure a name.

Note: By default, a stored procedure that retrieves the first item is provided. if not perform the
following steps:

3. In the Azure: Cosmos DB tab, expand Stored Procedures and click UpdateOrderTotal.

4. To run this default stored procedure from your application, add the following code to
the Program.cs file as the first entry after the class Program.

5. public async Task RunStoredProcedure(string databaseName, string collectionName, User


user)
6. {
7. await
client.ExecuteStoredProcedureAsync<string>(UriFactory.CreateStoredProcedureUri(databa
seName, collectionName, "UpdateOrderTotal"), new RequestOptions { PartitionKey = new
PartitionKey(user.UserId) });
8. Console.WriteLine("Stored procedure complete");
}

9. Copy the following code and paste it before the await this.DeleteUserDocument("Users",
"WebCustomers", yanhe); line in the BasicOperations method.

await this.RunStoredProcedure("Users", "WebCustomers", yanhe);

10. In the integrated terminal, again, copy and paste the following command to run the program to
ensure it runs.

dotnet run

11. The following result should be displayed

12. Database and collection validation complete


13. Created User 1
14. Press any key to continue ...
15. User 2 already exists in the database
16. Press any key to continue ...
17. Replaced last name for Suh
18. Press any key to continue ...
19. Read user 1
20. Press any key to continue ...
21. Running LINQ query...
22. Read
{"id":"2","userId":"nelapin","lastName":"Pindakova","firstName":"Nela","email":"nelap
in@contoso.com","dividend":"8.50","OrderHistory":
[{"OrderId":"1001","DateShipped":"08/17/2018","Total":"105.89"}],"ShippingPreference"
:[{"Priority":1,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"},
{"Priority":2,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"}],"CouponsUsed":
[{"CouponCode":"Fall2018"}]}
23. Running direct SQL query...
24. Read
{"id":"2","userId":"nelapin","lastName":"Pindakova","firstName":"Nela","email":"nelap
in@contoso.com","dividend":"8.50","OrderHistory":
[{"OrderId":"1001","DateShipped":"08/17/2018","Total":"105.89"}],"ShippingPreference"
:[{"Priority":1,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"},
{"Priority":2,"AddressLine1":"505 NW 5th St","AddressLine2":null,"City":"New
York","State":"NY","ZipCode":"10001","Country":"USA"}],"CouponsUsed":
[{"CouponCode":"Fall2018"}]}
25. Press any key to continue ...
26. Stored procedure complete
27. Deleted user 1
28. End of demo, press any key to exit.
Result In this exercise, you have built a console application from scratch by setting up Visual Studio code to
connect with Azure Cosmos DB. You have then created .Net code to create, read, update, and delete NoSQL
data programmatically. You then added code to query the Cosmos DB and learned how to create
programming objects such as Stored Procedures to work against Cosmos DB

S-ar putea să vă placă și