forked from hardikchimedia/cosmosdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
307 lines (281 loc) · 12 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
using System;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
namespace learning_module
{
class Program
{
private DocumentClient client;
static void Main(string[] args)
{
try
{
Program p = new Program();
p.BasicOperations().Wait();
}
catch (DocumentClientException de)
{
Exception baseException = de.GetBaseException();
Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message);
}
catch (Exception e)
{
Exception baseException = e.GetBaseException();
Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
}
finally
{
Console.WriteLine("End of demo, press any key to exit.");
Console.ReadKey();
}
}
private async Task BasicOperations()
{
this.client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["accountEndpoint"]), ConfigurationManager.AppSettings["accountKey"]);
await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "Users" });
await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Users"), new DocumentCollection { Id = "WebCustomers" });
Console.WriteLine("Database and collection validation complete");
User yanhe = new User
{
Id = "1",
UserId = "yanhe",
LastName = "He",
FirstName = "Yan",
Email = "yanhe@contoso.com",
OrderHistory = new OrderHistory[]
{
new OrderHistory {
OrderId = "1000",
DateShipped = "08/17/2018",
Total = "52.49"
}
},
ShippingPreference = new ShippingPreference[]
{
new ShippingPreference {
Priority = 1,
AddressLine1 = "90 W 8th St",
City = "New York",
State = "NY",
ZipCode = "10001",
Country = "USA"
}
},
};
await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", yanhe);
User nelapin = new User
{
Id = "2",
UserId = "nelapin",
LastName = "Pindakova",
FirstName = "Nela",
Email = "nelapin@contoso.com",
Dividend = "8.50",
OrderHistory = new OrderHistory[]
{
new OrderHistory {
OrderId = "1001",
DateShipped = "08/17/2018",
Total = "105.89"
}
},
ShippingPreference = new ShippingPreference[]
{
new ShippingPreference {
Priority = 1,
AddressLine1 = "505 NW 5th St",
City = "New York",
State = "NY",
ZipCode = "10001",
Country = "USA"
},
new ShippingPreference {
Priority = 2,
AddressLine1 = "505 NW 5th St",
City = "New York",
State = "NY",
ZipCode = "10001",
Country = "USA"
}
},
Coupons = new CouponsUsed[]
{
new CouponsUsed{
CouponCode = "Fall2018"
}
}
};
// await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin);
// yanhe.LastName = "Suh";
// await this.ReplaceUserDocument("Users", "WebCustomers", yanhe);
// await this.ReadUserDocument("Users", "WebCustomers", yanhe);
// this.ExecuteSimpleQuery("Users", "WebCustomers");
// await this.DeleteUserDocument("Users", "WebCustomers", yanhe);
await this.RunStoredProcedure("Users", "WebCustomers", yanhe);
}
public class User
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("userId")]
public string UserId { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("dividend")]
public string Dividend { get; set; }
[JsonProperty("OrderHistory")]
public OrderHistory[] OrderHistory { get; set; }
[JsonProperty("ShippingPreference")]
public ShippingPreference[] ShippingPreference { get; set; }
[JsonProperty("CouponsUsed")]
public CouponsUsed[] Coupons { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
public class OrderHistory
{
public string OrderId { get; set; }
public string DateShipped { get; set; }
public string Total { get; set; }
}
public class ShippingPreference
{
public int Priority { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
public class CouponsUsed
{
public string CouponCode { get; set; }
}
private void WriteToConsoleAndPromptToContinue(string format, params object[] args)
{
Console.WriteLine(format, args);
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}
private async Task CreateUserDocumentIfNotExists(string databaseName, string collectionName, User user)
{
try
{
await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, user.Id), new RequestOptions { PartitionKey = new PartitionKey(user.UserId) });
this.WriteToConsoleAndPromptToContinue("User {0} already exists in the database", user.Id);
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), user);
this.WriteToConsoleAndPromptToContinue("Created User {0}", user.Id);
}
else
{
throw;
}
}
}
private async Task ReadUserDocument(string databaseName, string collectionName, User user)
{
try
{
await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, user.Id), new RequestOptions { PartitionKey = new PartitionKey(user.UserId) });
this.WriteToConsoleAndPromptToContinue("Read user {0}", user.Id);
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
this.WriteToConsoleAndPromptToContinue("User {0} not read", user.Id);
}
else
{
throw;
}
}
}
private async Task ReplaceUserDocument(string databaseName, string collectionName, User updatedUser)
{
try
{
await this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, updatedUser.Id), updatedUser, new RequestOptions { PartitionKey = new PartitionKey(updatedUser.UserId) });
this.WriteToConsoleAndPromptToContinue("Replaced last name for {0}", updatedUser.LastName);
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
this.WriteToConsoleAndPromptToContinue("User {0} not found for replacement", updatedUser.Id);
}
else
{
throw;
}
}
}
private async Task DeleteUserDocument(string databaseName, string collectionName, User deletedUser)
{
try
{
await this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, deletedUser.Id), new RequestOptions { PartitionKey = new PartitionKey(deletedUser.UserId) });
Console.WriteLine("Deleted user {0}", deletedUser.Id);
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
this.WriteToConsoleAndPromptToContinue("User {0} not found for deletion", deletedUser.Id);
}
else
{
throw;
}
}
}
private void ExecuteSimpleQuery(string databaseName, string collectionName)
{
// Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true };
// Here we find nelapin via their LastName
IQueryable<User> userQuery = this.client.CreateDocumentQuery<User>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.Where(u => u.LastName == "Pindakova");
// The query is executed synchronously here, but can also be executed asynchronously via the IDocumentQuery<T> interface
Console.WriteLine("Running LINQ query...");
foreach (User user in userQuery)
{
Console.WriteLine("\tRead {0}", user);
}
// Now execute the same query via direct SQL
IQueryable<User> userQueryInSql = this.client.CreateDocumentQuery<User>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
"SELECT * FROM User WHERE User.lastName = 'Pindakova'", queryOptions );
Console.WriteLine("Running direct SQL query...");
foreach (User user in userQueryInSql)
{
Console.WriteLine("\tRead {0}", user);
}
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}
public async Task RunStoredProcedure(string databaseName, string collectionName, User user)
{
await client.ExecuteStoredProcedureAsync<string>(UriFactory.CreateStoredProcedureUri(databaseName, collectionName, "UpdateOrderTotal"), new RequestOptions { PartitionKey = new PartitionKey(user.UserId) });
Console.WriteLine("Stored procedure complete");
}
}
}