forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AdapterUtil.cs
531 lines (463 loc) · 22.3 KB
/
AdapterUtil.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// 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;
using System.Collections;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Data.SqlClient;
namespace Microsoft.Data.Common
{
internal static partial class ADP
{
// NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx)
// Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features
private static Task<bool> _trueTask;
internal static Task<bool> TrueTask => _trueTask ?? (_trueTask = Task.FromResult(true));
private static Task<bool> _falseTask;
internal static Task<bool> FalseTask => _falseTask ?? (_falseTask = Task.FromResult(false));
internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
internal const int InfiniteConnectionTimeout = 0; // infinite connection timeout identifier in seconds
internal const int MaxBufferAccessTokenExpiry = 600; // max duration for buffer in seconds
static private void TraceException(string trace, Exception e)
{
Debug.Assert(null != e, "TraceException: null Exception");
if (null != e)
{
SqlClientEventSource.Log.TryTraceEvent(trace, e);
}
}
internal static void TraceExceptionAsReturnValue(Exception e)
{
TraceException("<comm.ADP.TraceException|ERR|THROW> '{0}'", e);
}
internal static void TraceExceptionWithoutRethrow(Exception e)
{
Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e);
}
internal static ArgumentException Argument(string error)
{
ArgumentException e = new ArgumentException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, Exception inner)
{
ArgumentException e = new ArgumentException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, string parameter)
{
ArgumentException e = new ArgumentException(error, parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter)
{
ArgumentNullException e = new ArgumentNullException(parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter, string error)
{
ArgumentNullException e = new ArgumentNullException(parameter, error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange(string error)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidCastException InvalidCast(string error)
{
return InvalidCast(error, null);
}
internal static InvalidCastException InvalidCast(string error, Exception inner)
{
InvalidCastException e = new InvalidCastException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException InvalidOperation(string error)
{
InvalidOperationException e = new InvalidOperationException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported()
{
NotSupportedException e = new NotSupportedException();
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported(string error)
{
NotSupportedException e = new NotSupportedException(error);
TraceExceptionAsReturnValue(e);
return e;
}
// the return value is true if the string was quoted and false if it was not
// this allows the caller to determine if it is an error or not for the quotedString to not be quoted
internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString)
{
int prefixLength = quotePrefix != null ? quotePrefix.Length : 0;
int suffixLength = quoteSuffix != null ? quoteSuffix.Length : 0;
if ((suffixLength + prefixLength) == 0)
{
unquotedString = quotedString;
return true;
}
if (quotedString == null)
{
unquotedString = quotedString;
return false;
}
int quotedStringLength = quotedString.Length;
// is the source string too short to be quoted
if (quotedStringLength < prefixLength + suffixLength)
{
unquotedString = quotedString;
return false;
}
// is the prefix present?
if (prefixLength > 0)
{
if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
}
// is the suffix present?
if (suffixLength > 0)
{
if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix);
}
else
{
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength);
}
return true;
}
internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method)
{
return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
}
internal static InvalidOperationException DataAdapter(string error)
{
return InvalidOperation(error);
}
private static InvalidOperationException Provider(string error)
{
return InvalidOperation(error);
}
internal static ArgumentException InvalidMultipartName(string property, string value)
{
ArgumentException e = new ArgumentException(System.StringsHelper.Format(Strings.ADP_InvalidMultipartName, property, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value)
{
ArgumentException e = new ArgumentException(System.StringsHelper.Format(Strings.ADP_InvalidMultipartNameQuoteUsage, property, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit)
{
ArgumentException e = new ArgumentException(System.StringsHelper.Format(Strings.ADP_InvalidMultipartNameToManyParts, property, value, limit));
TraceExceptionAsReturnValue(e);
return e;
}
internal static void CheckArgumentNull(object value, string parameterName)
{
if (null == value)
{
throw ArgumentNull(parameterName);
}
}
// only StackOverflowException & ThreadAbortException are sealed classes
private static readonly Type s_stackOverflowType = typeof(StackOverflowException);
private static readonly Type s_outOfMemoryType = typeof(OutOfMemoryException);
private static readonly Type s_threadAbortType = typeof(ThreadAbortException);
private static readonly Type s_nullReferenceType = typeof(NullReferenceException);
private static readonly Type s_accessViolationType = typeof(AccessViolationException);
private static readonly Type s_securityType = typeof(SecurityException);
internal static bool IsCatchableExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != s_stackOverflowType) &&
(type != s_outOfMemoryType) &&
(type != s_threadAbortType) &&
(type != s_nullReferenceType) &&
(type != s_accessViolationType) &&
!s_securityType.IsAssignableFrom(type));
}
internal static bool IsCatchableOrSecurityExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
// since IsCatchableExceptionType defined SecurityException as not 'catchable'
// this method will return true for SecurityException has being catchable.
// the other way to write this method is, but then SecurityException is checked twice
// return ((e is SecurityException) || IsCatchableExceptionType(e));
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != s_stackOverflowType) &&
(type != s_outOfMemoryType) &&
(type != s_threadAbortType) &&
(type != s_nullReferenceType) &&
(type != s_accessViolationType));
}
// Invalid Enumeration
internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
{
return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException ConnectionStringSyntax(int index)
{
return Argument(System.StringsHelper.Format(Strings.ADP_ConnectionStringSyntax, index));
}
internal static ArgumentException KeywordNotSupported(string keyword)
{
return Argument(System.StringsHelper.Format(Strings.ADP_KeywordNotSupported, keyword));
}
internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException)
{
return ADP.Argument(System.StringsHelper.Format(Strings.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
}
//
// DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValue(string key)
{
return InvalidConnectionOptionValue(key, null);
}
internal static Exception InvalidConnectionOptionValue(string key, Exception inner)
{
return Argument(System.StringsHelper.Format(Strings.ADP_InvalidConnectionOptionValue, key), inner);
}
static internal InvalidOperationException InvalidDataDirectory()
{
InvalidOperationException e = new InvalidOperationException(Strings.ADP_InvalidDataDirectory);
return e;
}
//
// Generic Data Provider Collection
//
internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection)
{
return Argument(System.StringsHelper.Format(Strings.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name));
}
internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType)
{
return ArgumentNull(parameter, System.StringsHelper.Format(Strings.ADP_CollectionNullValue, collection.Name, itemType.Name));
}
internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count)
{
return IndexOutOfRange(System.StringsHelper.Format(Strings.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
}
internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection)
{
return IndexOutOfRange(System.StringsHelper.Format(Strings.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
}
internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue)
{
return InvalidCast(System.StringsHelper.Format(Strings.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
}
//
// DbConnection
//
private static string ConnectionStateMsg(ConnectionState state)
{
switch (state)
{
case (ConnectionState.Closed):
case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed
return Strings.ADP_ConnectionStateMsg_Closed;
case (ConnectionState.Connecting):
return Strings.ADP_ConnectionStateMsg_Connecting;
case (ConnectionState.Open):
return Strings.ADP_ConnectionStateMsg_Open;
case (ConnectionState.Open | ConnectionState.Executing):
return Strings.ADP_ConnectionStateMsg_OpenExecuting;
case (ConnectionState.Open | ConnectionState.Fetching):
return Strings.ADP_ConnectionStateMsg_OpenFetching;
default:
return System.StringsHelper.Format(Strings.ADP_ConnectionStateMsg, state.ToString());
}
}
//
// : Stream
//
internal static Exception StreamClosed([CallerMemberName] string method = "")
{
return InvalidOperation(System.StringsHelper.Format(Strings.ADP_StreamClosed, method));
}
internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString)
{
var resultString = new StringBuilder();
if (!string.IsNullOrEmpty(quotePrefix))
{
resultString.Append(quotePrefix);
}
// Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
if (!string.IsNullOrEmpty(quoteSuffix))
{
resultString.Append(unQuotedString.Replace(quoteSuffix, quoteSuffix + quoteSuffix));
resultString.Append(quoteSuffix);
}
else
{
resultString.Append(unQuotedString);
}
return resultString.ToString();
}
static internal string BuildMultiPartName(string[] strings)
{
StringBuilder bld = new StringBuilder();
// Assume we want to build a full multi-part name with all parts except trimming separators for
// leading empty names (null or empty strings, but not whitespace). Separators in the middle
// should be added, even if the name part is null/empty, to maintain proper location of the parts.
for (int i = 0; i < strings.Length; i++)
{
if (0 < bld.Length)
{
bld.Append('.');
}
if (null != strings[i] && 0 != strings[i].Length)
{
bld.Append(BuildQuotedString("[", "]", strings[i]));
}
}
return bld.ToString();
}
//
// Generic Data Provider Collection
//
internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection)
{
return Argument(System.StringsHelper.Format(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection)
{
return Argument(System.StringsHelper.Format(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
internal enum InternalErrorCode
{
UnpooledObjectHasOwner = 0,
UnpooledObjectHasWrongOwner = 1,
PushingObjectSecondTime = 2,
PooledObjectHasOwner = 3,
PooledObjectInPoolMoreThanOnce = 4,
CreateObjectReturnedNull = 5,
NewObjectCannotBePooled = 6,
NonPooledObjectUsedMoreThanOnce = 7,
AttemptingToPoolOnRestrictedToken = 8,
// ConnectionOptionsInUse = 9,
ConvertSidToStringSidWReturnedNull = 10,
// UnexpectedTransactedObject = 11,
AttemptingToConstructReferenceCollectionOnStaticObject = 12,
AttemptingToEnlistTwice = 13,
CreateReferenceCollectionReturnedNull = 14,
PooledObjectWithoutPool = 15,
UnexpectedWaitAnyResult = 16,
SynchronousConnectReturnedPending = 17,
CompletedConnectReturnedPending = 18,
NameValuePairNext = 20,
InvalidParserState1 = 21,
InvalidParserState2 = 22,
InvalidParserState3 = 23,
InvalidBuffer = 30,
UnimplementedSMIMethod = 40,
InvalidSmiCall = 41,
SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
SqlDependencyProcessDispatcherFailureCreateInstance = 51,
SqlDependencyProcessDispatcherFailureAppDomain = 52,
SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
UnknownTransactionFailure = 60,
}
internal static Exception InternalError(InternalErrorCode internalError)
{
return InvalidOperation(System.StringsHelper.Format(Strings.ADP_InternalProviderError, (int)internalError));
}
//
// : DbDataReader
//
internal static Exception DataReaderClosed([CallerMemberName] string method = "")
{
return InvalidOperation(System.StringsHelper.Format(Strings.ADP_DataReaderClosed, method));
}
internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName)
{
return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName)
{
return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex)
{
return IndexOutOfRange(System.StringsHelper.Format(Strings.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception InvalidDataLength(long length)
{
return IndexOutOfRange(System.StringsHelper.Format(Strings.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
}
internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) =>
0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase);
internal static int DstCompare(string strA, string strB) => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions);
internal static bool IsEmptyArray(string[] array) => (null == array) || (0 == array.Length);
internal static bool IsNull(object value)
{
if ((null == value) || (DBNull.Value == value))
{
return true;
}
INullable nullable = (value as INullable);
return ((null != nullable) && nullable.IsNull);
}
internal static Exception InvalidSeekOrigin(string parameterName)
{
return ArgumentOutOfRange(Strings.ADP_InvalidSeekOrigin, parameterName);
}
internal static void SetCurrentTransaction(Transaction transaction)
{
Transaction.Current = transaction;
}
}
}