-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
208 lines (186 loc) · 9.63 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Resources.Models;
using Azure.ResourceManager.Samples.Common;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager;
using Azure.ResourceManager.CosmosDB;
using Azure.ResourceManager.CosmosDB.Models;
using System.Reflection;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents;
namespace HACosmosDB
{
public class Program
{
private static ResourceIdentifier? _resourceGroupId = null;
private const int _maxStalenessPrefix = 100000;
private const int _maxIntervalInSeconds = 300;
const String DATABASE_ID = "TestDB";
const String COLLECTION_ID = "TestCollection";
/**
* Azure CosmosDB sample -
* - Create a CosmosDB configured with a single read location
* - Get the credentials for the CosmosDB
* - Update the CosmosDB with additional read locations
* - Delete the CosmosDB
*/
public static async Task RunSample(ArmClient client)
{
try
{
// Get default subscription
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
// Create a resource group in the EastUS region
string rgName = Utilities.CreateRandomName("CosmosDBTemplateRG");
Utilities.Log($"creating resource group with name:{rgName}");
ArmOperation<ResourceGroupResource> rgLro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, new ResourceGroupData(AzureLocation.EastUS));
ResourceGroupResource resourceGroup = rgLro.Value;
_resourceGroupId = resourceGroup.Id;
Utilities.Log("Created a resource group with name: " + resourceGroup.Data.Name);
//============================================================
// Create a CosmosDB.
Utilities.Log("Creating a CosmosDB...");
string dbAccountName = Utilities.CreateRandomName("dbaccount");
CosmosDBAccountKind cosmosDBKind = CosmosDBAccountKind.GlobalDocumentDB;
var locations = new List<CosmosDBAccountLocation>()
{
new CosmosDBAccountLocation(){ LocationName = AzureLocation.EastUS, FailoverPriority = 0 },
};
var dbAccountInput = new CosmosDBAccountCreateOrUpdateContent(AzureLocation.WestUS2, locations)
{
Kind = cosmosDBKind,
ConsistencyPolicy = new Azure.ResourceManager.CosmosDB.Models.ConsistencyPolicy(DefaultConsistencyLevel.BoundedStaleness)
{
MaxStalenessPrefix = _maxStalenessPrefix,
MaxIntervalInSeconds = _maxIntervalInSeconds
},
IPRules =
{
new CosmosDBIPAddressOrRange()
{
IPAddressOrRange = Environment.GetEnvironmentVariable("Current_Machine_PublicIP")
}
},
IsVirtualNetworkFilterEnabled = true,
EnableAutomaticFailover = false,
ConnectorOffer = ConnectorOffer.Small,
DisableKeyBasedMetadataWriteAccess = false,
EnableMultipleWriteLocations = true,
};
dbAccountInput.Tags.Add("key1", "value");
dbAccountInput.Tags.Add("key2", "value");
var accountLro = await resourceGroup.GetCosmosDBAccounts().CreateOrUpdateAsync(WaitUntil.Completed, dbAccountName, dbAccountInput);
CosmosDBAccountResource dbAccount = accountLro.Value;
Utilities.Log($"Created CosmosDB {dbAccount.Id.Name}");
//============================================================
// Get credentials for the CosmosDB.
Utilities.Log("Get credentials for the CosmosDB");
var getKeysLro = await dbAccount.GetKeysAsync();
CosmosDBAccountKeyList keyList = getKeysLro.Value;
string masterKey = keyList.PrimaryMasterKey;
string endPoint = dbAccount.Data.DocumentEndpoint;
Utilities.Log($"masterKey: {masterKey}");
Utilities.Log($"endPoint: {endPoint}");
//============================================================
// Update document db with three additional read regions
Utilities.Log("Updating CosmosDB with three additional read replication regions");
var updataInput = new CosmosDBAccountPatch()
{
Locations =
{
new CosmosDBAccountLocation() { LocationName = AzureLocation.EastUS, FailoverPriority = 0 },
new CosmosDBAccountLocation() { LocationName = AzureLocation.EastAsia, FailoverPriority = 1 },
new CosmosDBAccountLocation() { LocationName = AzureLocation.UKSouth, FailoverPriority = 2 },
new CosmosDBAccountLocation() { LocationName = AzureLocation.SouthAfricaNorth, FailoverPriority = 3 }
}
};
var updateResponse = await dbAccount.UpdateAsync(WaitUntil.Completed, updataInput);
CosmosDBAccountResource updatedDBAccount = updateResponse.Value;
Utilities.Log("Updated CosmosDB");
//============================================================
// Connect to CosmosDB and add a collection
Console.WriteLine("Connecting and adding collection");
CreateDBAndAddCollection(masterKey, endPoint);
//============================================================
// Delete CosmosDB
Utilities.Log("Deleting the CosmosDB");
try
{
await dbAccount.DeleteAsync(WaitUntil.Completed);
}
catch (Exception ex)
{
Utilities.Log(ex.ToString());
}
Utilities.Log("Deleted the CosmosDB");
}
finally
{
try
{
if (_resourceGroupId is not null)
{
Utilities.Log($"Deleting Resource Group: {_resourceGroupId}");
await client.GetResourceGroupResource(_resourceGroupId).DeleteAsync(WaitUntil.Completed);
Utilities.Log($"Deleted Resource Group: {_resourceGroupId}");
}
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception e)
{
Utilities.Log(e.StackTrace);
}
}
}
private static void CreateDBAndAddCollection(string masterKey, string endPoint)
{
DocumentClient documentClient = new DocumentClient(new System.Uri(endPoint),
masterKey, ConnectionPolicy.Default,
ConsistencyLevel.Session);
// Define a new database using the id above.
Database myDatabase = new Database();
myDatabase.Id = DATABASE_ID;
myDatabase = documentClient.CreateDatabaseAsync(myDatabase, null)
.GetAwaiter().GetResult();
Console.WriteLine("Created a new database:");
Console.WriteLine(myDatabase.ToString());
// Define a new collection using the id above.
DocumentCollection myCollection = new DocumentCollection();
myCollection.Id = COLLECTION_ID;
// Set the provisioned throughput for this collection to be 1000 RUs.
RequestOptions requestOptions = new RequestOptions();
requestOptions.OfferThroughput = 4000;
// Create a new collection.
myCollection = documentClient.CreateDocumentCollectionAsync(
"dbs/" + DATABASE_ID, myCollection, requestOptions)
.GetAwaiter().GetResult();
}
public static async Task Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
ArmClient client = new ArmClient(credential, subscription);
await RunSample(client);
}
catch (Exception e)
{
Utilities.Log(e.Message);
Utilities.Log(e.StackTrace);
}
}
}
}