-
Notifications
You must be signed in to change notification settings - Fork 48
/
Advanced.cs
365 lines (319 loc) · 14.7 KB
/
Advanced.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
//----------------------------------------------------------------------------------
// Microsoft Azure Storage Team
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//----------------------------------------------------------------------------------
using Microsoft.Azure;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Queue;
using Microsoft.Azure.Storage.Queue.Protocol;
using Microsoft.Azure.Storage.RetryPolicies;
using Microsoft.Azure.Storage.Shared.Protocol;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace QueueStorage
{
public class Advanced
{
/// <summary>
/// Test some of the queue storage operations.
/// </summary>
public async Task RunQueueStorageAdvancedOpsAsync()
{
try
{
//***** Setup *****//
Console.WriteLine("Getting reference to the storage account.");
// Retrieve storage account information from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
CloudStorageAccount storageAccount = Common.CreateStorageAccountFromConnectionString(Common.ConnStr);
Console.WriteLine("Instantiating queue client.");
Console.WriteLine(string.Empty);
// Create a queue client for interacting with the queue service.
CloudQueueClient cloudQueueClient = storageAccount.CreateCloudQueueClient();
// List queues
await ListQueuesSample(cloudQueueClient);
// Service properties
await ServicePropertiesSample(cloudQueueClient);
// CORS Rules
await CorsSample(cloudQueueClient);
// Service Stats
await ServiceStatsSample(cloudQueueClient);
// Queue Metadata
await QueueMetadataSample(cloudQueueClient);
// Queue Acl
await QueueAclSample(cloudQueueClient);
}
catch (Exception ex)
{
Console.WriteLine(" Exception thrown. Message = {0}{1} Strack Trace = {2}", ex.Message, Environment.NewLine, ex.StackTrace);
}
}
/// <summary>
/// Create, list and delete queues
/// </summary>
/// <param name="cloudQueueClient"></param>
/// <returns></returns>
private static async Task ListQueuesSample(CloudQueueClient cloudQueueClient)
{
// Create 3 queues.
// Create the queue name -- use a guid in the name so it's unique.
string baseQueueName = "demotest-" + System.Guid.NewGuid().ToString();
// Keep a list of the queues so you can compare this list
// against the list of queues that we retrieve.
List<string> queueNames = new List<string>();
for (int i = 0; i < 3; i++)
{
// Set the name of the queue, then add it to the generic list.
string queueName = baseQueueName + "-0" + i;
queueNames.Add(queueName);
// Create the queue with this name.
Console.WriteLine("Creating queue with name {0}", queueName);
CloudQueue cloudQueue = cloudQueueClient.GetQueueReference(queueName);
try
{
await cloudQueue.CreateIfNotExistsAsync();
Console.WriteLine(" Queue created successfully.");
}
catch (StorageException exStorage)
{
Common.WriteException(exStorage);
Console.WriteLine(
"Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
throw;
}
catch (Exception ex)
{
Console.WriteLine(" Exception thrown creating queue.");
Common.WriteException(ex);
throw;
}
}
Console.WriteLine(string.Empty);
Console.WriteLine("List of queues in the storage account:");
// List the queues for this storage account
QueueContinuationToken token = null;
List<CloudQueue> cloudQueueList = new List<CloudQueue>();
do
{
QueueResultSegment segment = await cloudQueueClient.ListQueuesSegmentedAsync(baseQueueName, token);
token = segment.ContinuationToken;
cloudQueueList.AddRange(segment.Results);
}
while (token != null);
try
{
foreach (CloudQueue cloudQ in cloudQueueList)
{
Console.WriteLine("Cloud Queue name = {0}", cloudQ.Name);
}
}
catch (Exception ex)
{
Console.WriteLine(" Exception thrown listing queues.");
Common.WriteException(ex);
throw;
}
// Now clean up after yourself, using the list of queues that you created in case there were other queues in the account.
foreach (string oneQueueName in queueNames)
{
CloudQueue cloudQueue = cloudQueueClient.GetQueueReference(oneQueueName);
cloudQueue.DeleteIfExists();
}
}
/// <summary>
/// Manage the properties of the Queue service.
/// </summary>
/// <param name="queueClient"></param>
private static async Task ServicePropertiesSample(CloudQueueClient queueClient)
{
Console.WriteLine();
// Get service properties
Console.WriteLine("Get service properties");
ServiceProperties originalProperties = await queueClient.GetServicePropertiesAsync();
try
{
// Set service properties
Console.WriteLine("Set service properties");
ServiceProperties props = await queueClient.GetServicePropertiesAsync();
props.Logging.LoggingOperations = LoggingOperations.Read | LoggingOperations.Write;
props.Logging.RetentionDays = 5;
props.Logging.Version = Constants.AnalyticsConstants.LoggingVersionV1;
props.HourMetrics.MetricsLevel = MetricsLevel.Service;
props.HourMetrics.RetentionDays = 6;
props.HourMetrics.Version = Constants.AnalyticsConstants.MetricsVersionV1;
props.MinuteMetrics.MetricsLevel = MetricsLevel.Service;
props.MinuteMetrics.RetentionDays = 6;
props.MinuteMetrics.Version = Constants.AnalyticsConstants.MetricsVersionV1;
await queueClient.SetServicePropertiesAsync(props);
}
finally
{
// Revert back to original service properties
Console.WriteLine("Revert back to original service properties");
await queueClient.SetServicePropertiesAsync(originalProperties);
}
Console.WriteLine();
}
/// <summary>
/// Query the Cross-Origin Resource Sharing (CORS) rules for the Queue service
/// </summary>
/// <param name="queueClient"></param>
private static async Task CorsSample(CloudQueueClient queueClient)
{
Console.WriteLine();
// Get service properties
Console.WriteLine("Get service properties");
ServiceProperties originalProperties = await queueClient.GetServicePropertiesAsync();
try
{
// Add CORS rule
Console.WriteLine("Add CORS rule");
CorsRule corsRule = new CorsRule
{
AllowedHeaders = new List<string> {"*"},
AllowedMethods = CorsHttpMethods.Get,
AllowedOrigins = new List<string> {"*"},
ExposedHeaders = new List<string> {"*"},
MaxAgeInSeconds = 3600
};
ServiceProperties serviceProperties = await queueClient.GetServicePropertiesAsync();
serviceProperties.Cors.CorsRules.Add(corsRule);
await queueClient.SetServicePropertiesAsync(serviceProperties);
}
finally
{
// Revert back to original service properties
Console.WriteLine("Revert back to original service properties");
await queueClient.SetServicePropertiesAsync(originalProperties);
}
Console.WriteLine();
}
/// <summary>
/// Retrieve statistics related to replication for the Table service
/// </summary>
/// <param name="queueClient"></param>
private static async Task ServiceStatsSample(CloudQueueClient queueClient)
{
Console.WriteLine();
var originalLocation = queueClient.DefaultRequestOptions.LocationMode;
Console.WriteLine("Service stats:");
try
{
queueClient.DefaultRequestOptions.LocationMode = LocationMode.SecondaryOnly;
ServiceStats stats = await queueClient.GetServiceStatsAsync();
Console.WriteLine(" Last sync time: {0}", stats.GeoReplication.LastSyncTime);
Console.WriteLine(" Status: {0}", stats.GeoReplication.Status);
}
catch (StorageException)
{
// only works on RA-GRS (Read Access – Geo Redundant Storage)
}
finally
{
// Restore original value
queueClient.DefaultRequestOptions.LocationMode = originalLocation;
}
Console.WriteLine();
}
/// <summary>
/// Manage queue metadata
/// </summary>
/// <param name="cloudQueueClient"></param>
/// <returns></returns>
private static async Task QueueMetadataSample(CloudQueueClient cloudQueueClient)
{
// Create the queue name -- use a guid in the name so it's unique.
string queueName = "demotest-" + Guid.NewGuid();
CloudQueue queue = cloudQueueClient.GetQueueReference(queueName);
// Set queue metadata
Console.WriteLine("Set queue metadata");
queue.Metadata.Add("key1", "value1");
queue.Metadata.Add("key2", "value2");
// Create the queue with this name.
Console.WriteLine("Creating queue with name {0}", queueName);
await queue.CreateIfNotExistsAsync();
// Fetch queue attributes
// in this case this call is not need but is included for demo purposes
await queue.FetchAttributesAsync();
Console.WriteLine("Get queue metadata:");
foreach (var keyValue in queue.Metadata)
{
Console.WriteLine(" {0}: {1}", keyValue.Key, keyValue.Value);
}
// Delete queue
Console.WriteLine("Deleting queue with name {0}", queueName);
queue.DeleteIfExists();
}
/// <summary>
/// Manage stored access policies specified on the queue
/// </summary>
/// <param name="cloudQueueClient"></param>
/// <returns></returns>
private static async Task QueueAclSample(CloudQueueClient cloudQueueClient)
{
// Create the queue name -- use a guid in the name so it's unique.
string queueName = "demotest-" + Guid.NewGuid();
// Create the queue with this name.
Console.WriteLine("Creating queue with name {0}", queueName);
CloudQueue queue = cloudQueueClient.GetQueueReference(queueName);
try
{
await queue.CreateIfNotExistsAsync();
Console.WriteLine(" Queue created successfully.");
}
catch (StorageException exStorage)
{
Common.WriteException(exStorage);
Console.WriteLine(
"Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
throw;
}
catch (Exception ex)
{
Console.WriteLine(" Exception thrown creating queue.");
Common.WriteException(ex);
throw;
}
// Set queue permissions
SharedAccessQueuePolicy accessQueuePolicy = new SharedAccessQueuePolicy
{
SharedAccessStartTime = new DateTimeOffset(DateTime.Now),
SharedAccessExpiryTime = new DateTimeOffset(DateTime.Now.AddMinutes(10)),
Permissions = SharedAccessQueuePermissions.Update
};
QueuePermissions permissions = new QueuePermissions();
permissions.SharedAccessPolicies.Add("key1", accessQueuePolicy);
Console.WriteLine("Set queue permissions");
await queue.SetPermissionsAsync(permissions);
// Get queue permissions
Console.WriteLine("Get queue permissions:");
permissions = await queue.GetPermissionsAsync();
foreach (var keyValue in permissions.SharedAccessPolicies)
{
Console.WriteLine(" {0}:", keyValue.Key);
Console.WriteLine(" permissions: {0}:", keyValue.Value.Permissions);
Console.WriteLine(" start time: {0}:", keyValue.Value.SharedAccessStartTime);
Console.WriteLine(" expiry time: {0}:", keyValue.Value.SharedAccessExpiryTime);
}
// Delete queue
Console.WriteLine("Deleting queue with name {0}", queueName);
queue.DeleteIfExists();
}
}
}