-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathLocalAppContextSwitchesHelper.cs
More file actions
474 lines (431 loc) · 16.8 KB
/
LocalAppContextSwitchesHelper.cs
File metadata and controls
474 lines (431 loc) · 16.8 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
namespace Microsoft.Data.SqlClient.Tests.Common;
/// <summary>
/// This class provides read/write access to LocalAppContextSwitches values for
/// the duration of a test. It is intended to be constructed at the start of a
/// test and disposed of at the end. It captures the original values of the
/// switches and restores them when disposed.
///
/// This follows the RAII pattern to ensure that the switches are always
/// restored, which is important for global state like LocalAppContextSwitches.
///
/// https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization
///
/// As with all global state, care must be taken when using this class in tests
/// that may run in parallel. This class enforces a single instance policy
/// using a semaphore. Overlapping constructor calls will wait up to 5 seconds
/// for the previous instance to be disposed. Any tests that use this class
/// should not keep an instance alive for longer than 5 seconds, or they risk
/// causing failures in other tests.
/// </summary>
public sealed class LocalAppContextSwitchesHelper : IDisposable
{
#region Private Fields
/// <summary>
/// This semaphore ensures that only one instance of this class may exist at
/// a time.
/// </summary>
private static readonly SemaphoreSlim s_instanceLock = new(1, 1);
/// <summary>
/// These fields are used to capture the original switch values.
/// </summary>
#if NETFRAMEWORK
private readonly bool? _disableTnirByDefaultOriginal;
#endif
private readonly bool? _enableMultiSubnetFailoverByDefaultOriginal;
#if NET
private readonly bool? _globalizationInvariantModeOriginal;
#endif
private readonly bool? _ignoreServerProvidedFailoverPartnerOriginal;
private readonly bool? _useLegacyFailoverAlternationOnLoginSqlErrorsOriginal;
private readonly bool? _useLegacyIsolationLevelBehaviorOriginal;
private readonly bool? _legacyRowVersionNullBehaviorOriginal;
private readonly bool? _legacyVarTimeZeroScaleBehaviourOriginal;
private readonly bool? _makeReadAsyncBlockingOriginal;
private readonly bool? _suppressInsecureTlsWarningOriginal;
private readonly bool? _truncateScaledDecimalOriginal;
private readonly bool? _useCompatibilityAsyncBehaviourOriginal;
private readonly bool? _useCompatibilityProcessSniOriginal;
private readonly bool? _useConnectionPoolV2Original;
private readonly bool? _useOverallConnectTimeoutForPoolWaitOriginal;
#if NET && _WINDOWS
private readonly bool? _useManagedNetworkingOriginal;
#endif
private readonly bool? _useMinimumLoginTimeoutOriginal;
#endregion
#region Construction
/// <summary>
/// Construct to capture all existing switch values.
///
/// This call will block for at most 5 seconds, waiting for any previous
/// instance to be disposed before completing construction. Failure to
/// acquire the lock in that time will result in an exception being thrown.
/// </summary>
public LocalAppContextSwitchesHelper()
{
// Wait for any previous instance to be disposed.
//
// We are only willing to wait a short time to avoid deadlocks.
//
if (! s_instanceLock.Wait(TimeSpan.FromSeconds(5)))
{
throw new InvalidOperationException(
"Timeout waiting for previous LocalAppContextSwitchesHelper " +
"instance to be disposed.");
}
try
{
#if NETFRAMEWORK
_disableTnirByDefaultOriginal =
GetSwitchValue("s_disableTnirByDefault");
#endif
_enableMultiSubnetFailoverByDefaultOriginal =
GetSwitchValue("s_enableMultiSubnetFailoverByDefault");
#if NET
_globalizationInvariantModeOriginal =
GetSwitchValue("s_globalizationInvariantMode");
#endif
_ignoreServerProvidedFailoverPartnerOriginal =
GetSwitchValue("s_ignoreServerProvidedFailoverPartner");
_useLegacyFailoverAlternationOnLoginSqlErrorsOriginal =
GetSwitchValue("s_useLegacyFailoverAlternationOnLoginSqlErrors");
_useLegacyIsolationLevelBehaviorOriginal =
GetSwitchValue("s_useLegacyIsolationLevelBehavior");
_legacyRowVersionNullBehaviorOriginal =
GetSwitchValue("s_legacyRowVersionNullBehavior");
_legacyVarTimeZeroScaleBehaviourOriginal =
GetSwitchValue("s_legacyVarTimeZeroScaleBehaviour");
_makeReadAsyncBlockingOriginal =
GetSwitchValue("s_makeReadAsyncBlocking");
_suppressInsecureTlsWarningOriginal =
GetSwitchValue("s_suppressInsecureTlsWarning");
_truncateScaledDecimalOriginal =
GetSwitchValue("s_truncateScaledDecimal");
_useCompatibilityAsyncBehaviourOriginal =
GetSwitchValue("s_useCompatibilityAsyncBehaviour");
_useCompatibilityProcessSniOriginal =
GetSwitchValue("s_useCompatibilityProcessSni");
_useConnectionPoolV2Original =
GetSwitchValue("s_useConnectionPoolV2");
_useOverallConnectTimeoutForPoolWaitOriginal =
GetSwitchValue("s_useOverallConnectTimeoutForPoolWait");
#if NET && _WINDOWS
_useManagedNetworkingOriginal =
GetSwitchValue("s_useManagedNetworking");
#endif
_useMinimumLoginTimeoutOriginal =
GetSwitchValue("s_useMinimumLoginTimeout");
}
catch
{
// If we fail to capture the original values, release the lock
// immediately to avoid deadlocks.
s_instanceLock.Release();
throw;
}
}
/// <summary>
/// Disposal restores all original switch values and releases the instance
/// lock.
/// </summary>
public void Dispose()
{
try
{
#if NETFRAMEWORK
SetSwitchValue(
"s_disableTnirByDefault",
_disableTnirByDefaultOriginal);
#endif
SetSwitchValue(
"s_enableMultiSubnetFailoverByDefault",
_enableMultiSubnetFailoverByDefaultOriginal);
#if NET
SetSwitchValue(
"s_globalizationInvariantMode",
_globalizationInvariantModeOriginal);
#endif
SetSwitchValue(
"s_ignoreServerProvidedFailoverPartner",
_ignoreServerProvidedFailoverPartnerOriginal);
SetSwitchValue(
"s_useLegacyFailoverAlternationOnLoginSqlErrors",
_useLegacyFailoverAlternationOnLoginSqlErrorsOriginal);
SetSwitchValue(
"s_useLegacyIsolationLevelBehavior",
_useLegacyIsolationLevelBehaviorOriginal);
SetSwitchValue(
"s_legacyRowVersionNullBehavior",
_legacyRowVersionNullBehaviorOriginal);
SetSwitchValue(
"s_legacyVarTimeZeroScaleBehaviour",
_legacyVarTimeZeroScaleBehaviourOriginal);
SetSwitchValue(
"s_makeReadAsyncBlocking",
_makeReadAsyncBlockingOriginal);
SetSwitchValue(
"s_suppressInsecureTlsWarning",
_suppressInsecureTlsWarningOriginal);
SetSwitchValue(
"s_truncateScaledDecimal",
_truncateScaledDecimalOriginal);
SetSwitchValue(
"s_useCompatibilityAsyncBehaviour",
_useCompatibilityAsyncBehaviourOriginal);
SetSwitchValue(
"s_useCompatibilityProcessSni",
_useCompatibilityProcessSniOriginal);
SetSwitchValue(
"s_useConnectionPoolV2",
_useConnectionPoolV2Original);
SetSwitchValue(
"s_useOverallConnectTimeoutForPoolWait",
_useOverallConnectTimeoutForPoolWaitOriginal);
#if NET && _WINDOWS
SetSwitchValue(
"s_useManagedNetworking",
_useManagedNetworkingOriginal);
#endif
SetSwitchValue(
"s_useMinimumLoginTimeout",
_useMinimumLoginTimeoutOriginal);
}
finally
{
// Release the lock to allow another instance to be created.
s_instanceLock.Release();
}
}
#endregion
#region Switch Value Getters and Setters
// These properties get or set the like-named underlying switch field value.
//
// They all throw if the value cannot be retrieved or set.
#if NETFRAMEWORK
/// <summary>
/// Get or set the DisableTnirByDefault switch value.
/// </summary>
public bool? DisableTnirByDefault
{
get => GetSwitchValue("s_disableTnirByDefault");
set => SetSwitchValue("s_disableTnirByDefault", value);
}
#endif
/// <summary>
/// Get or set the EnableMultiSubnetFailoverByDefault switch value.
/// </summary>
public bool? EnableMultiSubnetFailoverByDefault
{
get => GetSwitchValue("s_enableMultiSubnetFailoverByDefault");
set => SetSwitchValue("s_enableMultiSubnetFailoverByDefault", value);
}
#if NET
/// <summary>
/// Get or set the GlobalizationInvariantMode switch value.
/// </summary>
public bool? GlobalizationInvariantMode
{
get => GetSwitchValue("s_globalizationInvariantMode");
set => SetSwitchValue("s_globalizationInvariantMode", value);
}
#endif
/// <summary>
/// Get or set the IgnoreServerProvidedFailoverPartner switch value.
/// </summary>
public bool? IgnoreServerProvidedFailoverPartner
{
get => GetSwitchValue("s_ignoreServerProvidedFailoverPartner");
set => SetSwitchValue("s_ignoreServerProvidedFailoverPartner", value);
}
/// <summary>
/// Get or set the UseLegacyFailoverAlternationOnLoginSqlErrors switch value.
/// </summary>
public bool? UseLegacyFailoverAlternationOnLoginSqlErrors
{
get => GetSwitchValue("s_useLegacyFailoverAlternationOnLoginSqlErrors");
set => SetSwitchValue("s_useLegacyFailoverAlternationOnLoginSqlErrors", value);
}
/// <summary>
/// Get or set the UseLegacyIsolationLevelBehavior switch value.
/// </summary>
public bool? UseLegacyIsolationLevelBehavior
{
get => GetSwitchValue("s_useLegacyIsolationLevelBehavior");
set => SetSwitchValue("s_useLegacyIsolationLevelBehavior", value);
}
/// <summary>
/// Get or set the LegacyRowVersionNullBehavior switch value.
/// </summary>
public bool? LegacyRowVersionNullBehavior
{
get => GetSwitchValue("s_legacyRowVersionNullBehavior");
set => SetSwitchValue("s_legacyRowVersionNullBehavior", value);
}
/// <summary>
/// Get or set the LegacyVarTimeZeroScaleBehaviour switch value.
/// </summary>
public bool? LegacyVarTimeZeroScaleBehaviour
{
get => GetSwitchValue("s_legacyVarTimeZeroScaleBehaviour");
set => SetSwitchValue("s_legacyVarTimeZeroScaleBehaviour", value);
}
/// <summary>
/// Get or set the MakeReadAsyncBlocking switch value.
/// </summary>
public bool? MakeReadAsyncBlocking
{
get => GetSwitchValue("s_makeReadAsyncBlocking");
set => SetSwitchValue("s_makeReadAsyncBlocking", value);
}
/// <summary>
/// Get or set the SuppressInsecureTlsWarning switch value.
/// </summary>
public bool? SuppressInsecureTlsWarning
{
get => GetSwitchValue("s_suppressInsecureTlsWarning");
set => SetSwitchValue("s_suppressInsecureTlsWarning", value);
}
/// <summary>
/// Get or set the TruncateScaledDecimal switch value.
/// </summary>
public bool? TruncateScaledDecimal
{
get => GetSwitchValue("s_truncateScaledDecimal");
set => SetSwitchValue("s_truncateScaledDecimal", value);
}
/// <summary>
/// Get or set the UseCompatibilityAsyncBehaviour switch value.
/// </summary>
public bool? UseCompatibilityAsyncBehaviour
{
get => GetSwitchValue("s_useCompatibilityAsyncBehaviour");
set => SetSwitchValue("s_useCompatibilityAsyncBehaviour", value);
}
/// <summary>
/// Get or set the UseCompatibilityProcessSni switch value.
/// </summary>
public bool? UseCompatibilityProcessSni
{
get => GetSwitchValue("s_useCompatibilityProcessSni");
set => SetSwitchValue("s_useCompatibilityProcessSni", value);
}
/// <summary>
/// Get or set the UseConnectionPoolV2 switch value.
/// </summary>
public bool? UseConnectionPoolV2
{
get => GetSwitchValue("s_useConnectionPoolV2");
set => SetSwitchValue("s_useConnectionPoolV2", value);
}
/// <summary>
/// Get or set the UseOverallConnectTimeoutForPoolWait switch value.
/// </summary>
public bool? UseOverallConnectTimeoutForPoolWait
{
get => GetSwitchValue("s_useOverallConnectTimeoutForPoolWait");
set => SetSwitchValue("s_useOverallConnectTimeoutForPoolWait", value);
}
#if NET && _WINDOWS
/// <summary>
/// Get or set the UseManagedNetworking switch value.
/// </summary>
public bool? UseManagedNetworking
{
get => GetSwitchValue("s_useManagedNetworking");
set => SetSwitchValue("s_useManagedNetworking", value);
}
#endif
/// <summary>
/// Get or set the UseMinimumLoginTimeout switch value.
/// </summary>
public bool? UseMinimumLoginTimeout
{
get => GetSwitchValue("s_useMinimumLoginTimeout");
set => SetSwitchValue("s_useMinimumLoginTimeout", value);
}
#endregion
#region Helpers
/// <summary>
/// Use reflection to get a switch field value from LocalAppContextSwitches.
/// </summary>
private static bool? GetSwitchValue(string fieldName)
{
var assembly = Assembly.GetAssembly(typeof(SqlConnection));
if (assembly is null)
{
throw new InvalidOperationException(
"Could not get assembly for Microsoft.Data.SqlClient");
}
var type = assembly.GetType("Microsoft.Data.SqlClient.LocalAppContextSwitches");
if (type is null)
{
throw new InvalidOperationException(
"Could not get type LocalAppContextSwitches");
}
var field = type.GetField(
fieldName,
BindingFlags.Static | BindingFlags.NonPublic);
if (field == null)
{
throw new InvalidOperationException(
$"Field '{fieldName}' not found in LocalAppContextSwitches");
}
var value = field.GetValue(null);
if (value is not null)
{
// GOTCHA: This assumes that switch values map to bytes as:
//
// None = 0
// True = 1
// False = 2
//
// See the LocalAppContextSwitches.SwitchValue enum definition.
//
byte underlyingValue = (byte)value;
return underlyingValue == 0 ? null : underlyingValue == 1;
}
throw new InvalidOperationException(
$"Field '{fieldName}' is not of type byte");
}
/// <summary>
/// Use reflection to set a switch field value in LocalAppContextSwitches.
/// </summary>
private static void SetSwitchValue(string fieldName, bool? value)
{
var assembly = Assembly.GetAssembly(typeof(SqlConnection));
if (assembly is null)
{
throw new InvalidOperationException(
"Could not get assembly for Microsoft.Data.SqlClient");
}
var type = assembly.GetType("Microsoft.Data.SqlClient.LocalAppContextSwitches");
if (type is null)
{
throw new InvalidOperationException(
"Could not get type LocalAppContextSwitches");
}
var field = type.GetField(
fieldName,
BindingFlags.Static | BindingFlags.NonPublic);
if (field == null)
{
throw new InvalidOperationException(
$"Field '{fieldName}' not found in LocalAppContextSwitches");
}
// GOTCHA: This assumes that switch values map to bytes as:
//
// None = 0
// True = 1
// False = 2
//
// See the LocalAppContextSwitches.SwitchValue enum definition.
//
byte byteValue =
(byte)(!value.HasValue ? 0 : value.Value ? 1 : 2);
field.SetValue(null, Enum.ToObject(field.FieldType, byteValue));
}
#endregion
}