-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathServiceBusConnectionStringProperties.cs
413 lines (349 loc) · 17.3 KB
/
ServiceBusConnectionStringProperties.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
using System.Text;
using Azure.Core;
namespace Azure.Messaging.ServiceBus
{
/// <summary>
/// The set of properties that comprise a Service Bus connection string.
/// </summary>
///
public class ServiceBusConnectionStringProperties
{
/// <summary>The character used to separate a token and its value in the connection string.</summary>
private const char TokenValueSeparator = '=';
/// <summary>The character used to mark the beginning of a new token/value pair in the connection string.</summary>
private const char TokenValuePairDelimiter = ';';
/// <summary>The name of the protocol used by an Service Bus endpoint. </summary>
private const string ServiceBusEndpointSchemeName = "sb";
/// <summary>The token that identifies the endpoint address for the Service Bus namespace.</summary>
private const string EndpointToken = "Endpoint";
/// <summary>The token that identifies the name of a specific Service Bus entity under the namespace.</summary>
private const string EntityPathToken = "EntityPath";
/// <summary>The token that identifies the name of a shared access key.</summary>
private const string SharedAccessKeyNameToken = "SharedAccessKeyName";
/// <summary>The token that identifies the value of a shared access key.</summary>
private const string SharedAccessKeyValueToken = "SharedAccessKey";
/// <summary>The token that identifies the value of a shared access signature.</summary>
private const string SharedAccessSignatureToken = "SharedAccessSignature";
/// <summary>The token that identifies the intent to use a local emulator for development.</summary>
private const string DevelopmentEmulatorToken = "UseDevelopmentEmulator";
/// <summary>The formatted protocol used by an Service Bus endpoint. </summary>
private static readonly string ServiceBusEndpointScheme = $"{ ServiceBusEndpointSchemeName }{ Uri.SchemeDelimiter }";
/// <summary>
/// The fully qualified Service Bus namespace that the consumer is associated with. This is likely
/// to be similar to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
/// <value>The namespace of the Service Bus, as derived from the endpoint address of the connection string.</value>
///
public string FullyQualifiedNamespace => Endpoint?.Host;
/// <summary>
/// The endpoint to be used for connecting to the Service Bus namespace.
/// </summary>
///
/// <value>The endpoint address, including protocol, from the connection string.</value>
///
public Uri Endpoint { get; internal set; }
/// <summary>
/// The name of the specific Service Bus entity instance under the associated Service Bus namespace.
/// </summary>
///
public string EntityPath { get; internal set; }
/// <summary>
/// The name of the shared access key, either for the Service Bus namespace
/// or the Service Bus entity.
/// </summary>
///
public string SharedAccessKeyName { get; internal set; }
/// <summary>
/// The value of the shared access key, either for the Service Bus namespace
/// or the Service Bus entity.
/// </summary>
///
public string SharedAccessKey { get; internal set; }
/// <summary>
/// The value of the fully-formed shared access signature, either for the Service Bus
/// namespace or the Service Bus entity.
/// </summary>
///
public string SharedAccessSignature { get; internal set; }
/// <summary>
/// Indicates whether or not the connection string indicates that the
/// local development emulator is being used.
/// </summary>
///
/// <value><c>true</c> if the emulator is being used; otherwise, <c>false</c>.</value>
///
internal bool UseDevelopmentEmulator { get; set; }
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
///
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
///
/// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
///
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
/// <summary>
/// Converts the instance to string representation.
/// </summary>
///
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
/// <summary>
/// Creates an Service Bus connection string based on this set of <see cref="ServiceBusConnectionStringProperties" />.
/// </summary>
///
/// <returns>
/// A valid Service Bus connection string; depending on the specified property information, this may
/// represent the namespace-level or Event Hub-level.
/// </returns>
///
///
internal string ToConnectionString()
{
// Ensure that there was an endpoint specified and, if so, that it
// either is in the correct format or can be safely coerced.
if (Endpoint == null)
{
throw new ArgumentException(Resources.MissingConnectionInformation);
}
var endpointBuilder = new UriBuilder(Endpoint)
{
Scheme = ServiceBusEndpointScheme,
Port = -1
};
if ((string.Compare(endpointBuilder.Scheme, ServiceBusEndpointSchemeName, StringComparison.OrdinalIgnoreCase) != 0)
|| (Uri.CheckHostName(endpointBuilder.Host) == UriHostNameType.Unknown))
{
throw new ArgumentException(Resources.InvalidEndpointAddress);
}
// The connection string may contain a precomputed shared access signature OR a shared key name and value,
// but not both.
if ((!string.IsNullOrEmpty(SharedAccessSignature))
&& ((!string.IsNullOrEmpty(SharedAccessKeyName)) || (!string.IsNullOrEmpty(SharedAccessKey))))
{
throw new ArgumentException(Resources.OnlyOneSharedAccessAuthorizationMayBeSpecified);
}
// Ensure that each of the needed components are present for connecting.
var hasSharedKey = ((!string.IsNullOrEmpty(SharedAccessKeyName)) && (!string.IsNullOrEmpty(SharedAccessKey)));
var hasSharedSignature = (!string.IsNullOrEmpty(SharedAccessSignature));
if (string.IsNullOrEmpty(Endpoint?.Host)
|| ((!hasSharedKey) && (!hasSharedSignature)))
{
throw new ArgumentException(Resources.MissingConnectionInformation);
}
var builder = new StringBuilder()
.Append(EndpointToken)
.Append(TokenValueSeparator)
.Append(endpointBuilder.Uri.AbsoluteUri)
.Append(TokenValuePairDelimiter);
if (!string.IsNullOrEmpty(EntityPath))
{
builder
.Append(EntityPathToken)
.Append(TokenValueSeparator)
.Append(EntityPath)
.Append(TokenValuePairDelimiter);
}
if (!string.IsNullOrEmpty(SharedAccessSignature))
{
builder
.Append(SharedAccessSignatureToken)
.Append(TokenValueSeparator)
.Append(SharedAccessSignature)
.Append(TokenValuePairDelimiter);
}
else
{
builder
.Append(SharedAccessKeyNameToken)
.Append(TokenValueSeparator)
.Append(SharedAccessKeyName)
.Append(TokenValuePairDelimiter)
.Append(SharedAccessKeyValueToken)
.Append(TokenValueSeparator)
.Append(SharedAccessKey)
.Append(TokenValuePairDelimiter);
}
if (UseDevelopmentEmulator)
{
builder
.Append(DevelopmentEmulatorToken)
.Append(TokenValueSeparator)
.Append("true")
.Append(TokenValuePairDelimiter);
}
return builder.ToString();
}
/// <summary>
/// Parses the specified Service Bus connection string into its component properties.
/// </summary>
///
/// <param name="connectionString">The connection string to parse.</param>
///
/// <returns>The component properties parsed from the connection string.</returns>
///
/// <exception cref="FormatException">The specified connection string was malformed and could not be parsed.</exception>
///
public static ServiceBusConnectionStringProperties Parse(string connectionString)
{
Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
var parsedValues = new ServiceBusConnectionStringProperties();
var tokenPositionModifier = (connectionString[0] == TokenValuePairDelimiter) ? 0 : 1;
var lastPosition = 0;
var currentPosition = 0;
int valueStart;
string slice;
string token;
string value;
while (currentPosition != -1)
{
// Slice the string into the next token/value pair.
currentPosition = connectionString.IndexOf(TokenValuePairDelimiter, lastPosition + 1);
if (currentPosition >= 0)
{
slice = connectionString.Substring(lastPosition, (currentPosition - lastPosition));
}
else
{
slice = connectionString.Substring(lastPosition);
}
// Break the token and value apart, if this is a legal pair.
valueStart = slice.IndexOf(TokenValueSeparator);
if (valueStart >= 0)
{
token = slice.Substring((1 - tokenPositionModifier), (valueStart - 1 + tokenPositionModifier));
value = slice.Substring(valueStart + 1);
// Guard against leading and trailing spaces, only trimming if there is a need.
if ((!string.IsNullOrEmpty(token)) && (char.IsWhiteSpace(token[0])) || char.IsWhiteSpace(token[token.Length - 1]))
{
token = token.Trim();
}
if ((!string.IsNullOrEmpty(value)) && (char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[value.Length - 1])))
{
value = value.Trim();
}
// If there was no value for a key, then consider the connection string to
// be malformed.
if (string.IsNullOrEmpty(value))
{
throw new FormatException(Resources.InvalidConnectionString);
}
// Compare the token against the known connection string properties and capture the
// pair if they are a known attribute.
if (string.Compare(EndpointToken, token, StringComparison.OrdinalIgnoreCase) == 0)
{
// If this is an absolute URI, then it may have a custom port specified, which we
// want to preserve. If no scheme was specified, the URI is considered relative and
// the default port should be used.
if (!Uri.TryCreate(value, UriKind.Absolute, out var endpointUri))
{
endpointUri = null;
}
else if (string.IsNullOrEmpty(endpointUri.Host) && (CountChar(':', value.AsSpan()) == 1))
{
// If the host was empty after parsing and the value has a single port/scheme separator,
// then the parsing likely failed to recognize the host due to the lack of a scheme. Add
// an artificial scheme and try to parse again.
if (!Uri.TryCreate($"{ServiceBusEndpointSchemeName}://{value}", UriKind.Absolute, out endpointUri))
{
endpointUri = null;
}
}
var endpointBuilder = endpointUri switch
{
null => new UriBuilder(value)
{
Scheme = ServiceBusEndpointSchemeName,
Port = -1
},
_ => new UriBuilder()
{
Scheme = ServiceBusEndpointSchemeName,
Host = endpointUri.Host,
Port = endpointUri.IsDefaultPort ? -1 : endpointUri.Port,
}
};
if ((string.Compare(endpointBuilder.Scheme, ServiceBusEndpointSchemeName, StringComparison.OrdinalIgnoreCase) != 0)
|| (Uri.CheckHostName(endpointBuilder.Host) == UriHostNameType.Unknown))
{
throw new FormatException(Resources.InvalidConnectionString);
}
parsedValues.Endpoint = endpointBuilder.Uri;
}
else if (string.Compare(EntityPathToken, token, StringComparison.OrdinalIgnoreCase) == 0)
{
parsedValues.EntityPath = value;
}
else if (string.Compare(SharedAccessKeyNameToken, token, StringComparison.OrdinalIgnoreCase) == 0)
{
parsedValues.SharedAccessKeyName = value;
}
else if (string.Compare(SharedAccessKeyValueToken, token, StringComparison.OrdinalIgnoreCase) == 0)
{
parsedValues.SharedAccessKey = value;
}
else if (string.Compare(SharedAccessSignatureToken, token, StringComparison.OrdinalIgnoreCase) == 0)
{
parsedValues.SharedAccessSignature = value;
}
else if (string.Compare(DevelopmentEmulatorToken, token, StringComparison.OrdinalIgnoreCase) == 0)
{
// Do not enforce a value for the development emulator token. If a valid boolean, use it.
// Otherwise, leave the default value of false.
if (bool.TryParse(value, out var useEmulator))
{
parsedValues.UseDevelopmentEmulator = useEmulator;
}
}
}
else if ((slice.Length != 1) || (slice[0] != TokenValuePairDelimiter))
{
// This wasn't a legal pair and it is not simply a trailing delimiter; consider
// the connection string to be malformed.
throw new FormatException(Resources.InvalidConnectionString);
}
tokenPositionModifier = 0;
lastPosition = currentPosition;
}
return parsedValues;
}
/// <summary>
/// Counts the number of times a character occurs in a given span.
/// </summary>
///
/// <param name="span">The span to evaluate.</param>
/// <param name="value">The character to count.</param>
///
/// <returns>The number of times the <paramref name="value"/> occurs in <paramref name="span"/>.</returns>
///
private static int CountChar(char value,
ReadOnlySpan<char> span)
{
var count = 0;
foreach (var character in span)
{
if (character == value)
{
++count;
}
}
return count;
}
}
}