Bump corefx
[mono.git] / mcs / class / referencesource / System.Data / System / Data / Common / AdapterUtil.cs
1 //------------------------------------------------------------------------------
2 // <copyright file="AdapterUtil.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>
5 // <owner current="true" primary="true">Microsoft</owner>
6 // <owner current="true" primary="false">Microsoft</owner>
7 //------------------------------------------------------------------------------
8
9 namespace System.Data.Common {
10
11     using Microsoft.Win32;
12     using System;
13     using System.Collections;
14     using System.Collections.Generic;
15     using System.ComponentModel;
16     using System.Configuration;
17     using System.Data;
18     using System.Data.ProviderBase;
19 #if !MOBILE
20     using System.Data.Odbc;
21     using System.Data.OleDb;
22 #endif
23     using System.Data.Sql;
24     using System.Data.SqlTypes;
25     using System.Diagnostics;
26     using System.Globalization;
27     using System.IO;
28     using System.Reflection;
29     using System.Runtime.ConstrainedExecution;
30     using System.Runtime.InteropServices;
31     using System.Runtime.Serialization;
32     using System.Security;
33     using System.Security.Permissions;
34     using System.Data.SqlClient;
35     using System.Text;
36     using System.Threading;
37     using System.Threading.Tasks;
38     using System.Xml;
39     using SysTx = System.Transactions;
40 #if !MOBILE
41     using SysES = System.EnterpriseServices;
42 #endif
43     using System.Runtime.Versioning;
44
45     using Microsoft.SqlServer.Server;
46
47     internal static class ADP {
48         
49         // The class ADP defines the exceptions that are specific to the Adapters.f
50         // The class contains functions that take the proper informational variables and then construct
51         // the appropriate exception with an error string obtained from the resource Framework.txt.
52         // The exception is then returned to the caller, so that the caller may then throw from its
53         // location so that the catcher of the exception will have the appropriate call stack.
54         // This class is used so that there will be compile time checking of error messages.
55         // The resource Framework.txt will ensure proper string text based on the appropriate
56         // locale.
57
58         public const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
59
60         static internal Task<T> CreatedTaskWithException<T>(Exception ex) {
61             TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
62             completion.SetException(ex);
63             return completion.Task;
64         }
65
66         static internal Task<T> CreatedTaskWithCancellation<T>() {
67             TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
68             completion.SetCanceled();
69             return completion.Task;
70         }
71
72         static internal Exception ExceptionWithStackTrace(Exception e)
73         {
74             try {
75                 throw e;
76             }
77             catch (Exception caught) {
78                 return caught;
79             }
80         }
81
82         static internal Task<bool> s_trueTask = Task.FromResult<bool>(true);
83
84         static internal Task<bool> s_falseTask = Task.FromResult<bool>(false);
85         
86 #if MONO
87         static internal Task<bool> TrueTask => s_trueTask;
88         static internal Task<bool> FalseTask => s_falseTask;
89 #endif
90
91         [BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
92         static private void TraceException(
93                 string trace,
94                 [BidArgumentType(typeof(String))] Exception e) {
95             Debug.Assert(null != e, "TraceException: null Exception");
96             if (null != e) {
97                 Bid.Trace(trace, e.ToString()); // will include callstack if permission is available
98             }
99         }
100
101         static internal void TraceExceptionAsReturnValue(Exception e) {
102             TraceException("<comm.ADP.TraceException|ERR|THROW> '%ls'\n", e);
103         }
104         static internal void TraceExceptionForCapture(Exception e) {
105             Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
106             TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
107         }
108         static internal void TraceExceptionWithoutRethrow(Exception e) {
109             Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
110             TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
111         }
112
113         //
114         // COM+ exceptions
115         //
116         static internal ArgumentException Argument(string error) {
117             ArgumentException e = new ArgumentException(error);
118             TraceExceptionAsReturnValue(e);
119             return e;
120         }
121         static internal ArgumentException Argument(string error, Exception inner) {
122             ArgumentException e = new ArgumentException(error, inner);
123             TraceExceptionAsReturnValue(e);
124             return e;
125         }
126         static internal ArgumentException Argument(string error, string parameter) {
127             ArgumentException e = new ArgumentException(error, parameter);
128             TraceExceptionAsReturnValue(e);
129             return e;
130         }
131         static internal ArgumentException Argument(string error, string parameter, Exception inner) {
132             ArgumentException e = new ArgumentException(error, parameter, inner);
133             TraceExceptionAsReturnValue(e);
134             return e;
135         }
136         static internal ArgumentNullException ArgumentNull(string parameter) {
137             ArgumentNullException e = new ArgumentNullException(parameter);
138             TraceExceptionAsReturnValue(e);
139             return e;
140         }
141         static internal ArgumentNullException ArgumentNull(string parameter, string error) {
142             ArgumentNullException e = new ArgumentNullException(parameter, error);
143             TraceExceptionAsReturnValue(e);
144             return e;
145         }
146         static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) {
147             ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
148             TraceExceptionAsReturnValue(e);
149             return e;
150         }
151         static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) {
152             ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
153             TraceExceptionAsReturnValue(e);
154             return e;
155         }
156         static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) {
157             ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message);
158             TraceExceptionAsReturnValue(e);
159             return e;
160         }
161 #if !MOBILE
162         static internal ConfigurationException Configuration(string message) {
163             ConfigurationException e = new ConfigurationErrorsException(message);
164             TraceExceptionAsReturnValue(e);
165             return e;
166         }
167         static internal ConfigurationException Configuration(string message, XmlNode node) {
168             ConfigurationException e = new ConfigurationErrorsException(message, node);
169             TraceExceptionAsReturnValue(e);
170             return e;
171         }
172 #endif
173         static internal DataException Data(string message) {
174             DataException e = new DataException(message);
175             TraceExceptionAsReturnValue(e);
176             return e;
177         }
178         static internal IndexOutOfRangeException IndexOutOfRange(int value) {
179             IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
180             TraceExceptionAsReturnValue(e);
181             return e;
182         }
183         static internal IndexOutOfRangeException IndexOutOfRange(string error) {
184             IndexOutOfRangeException e = new IndexOutOfRangeException(error);
185             TraceExceptionAsReturnValue(e);
186             return e;
187         }
188         static internal IndexOutOfRangeException IndexOutOfRange() {
189             IndexOutOfRangeException e = new IndexOutOfRangeException();
190             TraceExceptionAsReturnValue(e);
191             return e;
192         }
193         static internal InvalidCastException InvalidCast(string error) {
194             return InvalidCast(error, null);
195         }
196         static internal InvalidCastException InvalidCast(string error, Exception inner) {
197             InvalidCastException e = new InvalidCastException(error, inner);
198             TraceExceptionAsReturnValue(e);
199             return e;
200         }
201         static internal InvalidOperationException InvalidOperation(string error) {
202             InvalidOperationException e = new InvalidOperationException(error);
203             TraceExceptionAsReturnValue(e);
204             return e;
205         }
206         static internal TimeoutException TimeoutException(string error) {
207             TimeoutException e = new TimeoutException(error);
208             TraceExceptionAsReturnValue(e);
209             return e;
210         }
211         static internal InvalidOperationException InvalidOperation(string error, Exception inner)
212         {
213             InvalidOperationException e = new InvalidOperationException(error, inner);
214             TraceExceptionAsReturnValue(e);
215             return e;
216         }
217         static internal NotImplementedException NotImplemented(string error) {
218             NotImplementedException e = new NotImplementedException(error);
219             TraceExceptionAsReturnValue(e);
220             return e;
221         }
222         static internal NotSupportedException NotSupported() {
223             NotSupportedException e = new NotSupportedException();
224             TraceExceptionAsReturnValue(e);
225             return e;
226         }
227         static internal NotSupportedException NotSupported(string error) {
228             NotSupportedException e = new NotSupportedException(error);
229             TraceExceptionAsReturnValue(e);
230             return e;
231         }
232         static internal OverflowException Overflow(string error) {
233             return Overflow(error, null);
234         }
235         static internal OverflowException Overflow(string error, Exception inner) {
236             OverflowException e = new OverflowException(error, inner);
237             TraceExceptionAsReturnValue(e);
238             return e;
239         }
240         static internal PlatformNotSupportedException PropertyNotSupported(string property) {
241             PlatformNotSupportedException e = new PlatformNotSupportedException(Res.GetString(Res.ADP_PropertyNotSupported, property));
242             TraceExceptionAsReturnValue(e);
243             return e;
244         }
245         static internal TypeLoadException TypeLoad(string error) {
246             TypeLoadException e = new TypeLoadException(error);
247             TraceExceptionAsReturnValue(e);
248             return e;
249         }
250         static internal InvalidCastException InvalidCast() {
251             InvalidCastException e = new InvalidCastException();
252             TraceExceptionAsReturnValue(e);
253             return e;
254         }
255         static internal IOException IO(string error) {
256             IOException e = new IOException(error);
257             TraceExceptionAsReturnValue(e);
258             return e;
259         }
260         static internal IOException IO(string error, Exception inner) {
261             IOException e = new IOException(error, inner);
262             TraceExceptionAsReturnValue(e);
263             return e;
264         }
265         static internal InvalidOperationException DataAdapter(string error) {
266             return InvalidOperation(error);
267         }
268         static internal InvalidOperationException DataAdapter(string error, Exception inner) {
269             return InvalidOperation(error, inner);
270         }
271         static private InvalidOperationException Provider(string error) {
272             return InvalidOperation(error);
273         }
274         static internal ObjectDisposedException ObjectDisposed(object instance) {
275             ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
276             TraceExceptionAsReturnValue(e);
277             return e;
278         }
279
280         static internal InvalidOperationException MethodCalledTwice(string method) {
281             InvalidOperationException e = new InvalidOperationException(Res.GetString(Res.ADP_CalledTwice, method));
282             TraceExceptionAsReturnValue(e);
283             return e;
284         }
285
286         static internal ArgumentException IncorrectAsyncResult() {
287             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_IncorrectAsyncResult), "AsyncResult");
288             TraceExceptionAsReturnValue(e);
289             return e;
290         }
291
292         static internal ArgumentException SingleValuedProperty(string propertyName, string value) {
293             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_SingleValuedProperty, propertyName, value));
294             TraceExceptionAsReturnValue(e);
295             return e;
296         }
297
298         static internal ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) {
299             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_DoubleValuedProperty, propertyName, value1, value2));
300             TraceExceptionAsReturnValue(e);
301             return e;
302         }
303
304         static internal ArgumentException InvalidPrefixSuffix() {
305             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidPrefixSuffix));
306             TraceExceptionAsReturnValue(e);
307             return e;
308         }
309
310         static internal ArgumentException InvalidMultipartName(string property, string value) {
311             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartName, Res.GetString(property), value));
312             TraceExceptionAsReturnValue(e);
313             return e;
314         }
315
316         static internal ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) {
317             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameQuoteUsage, Res.GetString(property), value));
318             TraceExceptionAsReturnValue(e);
319             return e;
320         }
321
322         static internal ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) {
323             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameToManyParts, Res.GetString(property), value, limit));
324             TraceExceptionAsReturnValue(e);
325             return e;
326         }
327
328         static internal ArgumentException BadParameterName(string parameterName) {
329             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_BadParameterName, parameterName));
330             TraceExceptionAsReturnValue(e);
331             return e;
332         }
333
334         static internal ArgumentException MultipleReturnValue() {
335             ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_MultipleReturnValue));
336             TraceExceptionAsReturnValue(e);
337             return e;
338         }
339
340         //
341         // Helper Functions
342         //
343         static internal void CheckArgumentLength(string value, string parameterName) {
344             CheckArgumentNull(value, parameterName);
345             if (0 == value.Length) {
346                 throw Argument(Res.GetString(Res.ADP_EmptyString, parameterName)); // MDAC 94859
347             }
348         }
349         static internal void CheckArgumentLength(Array value, string parameterName) {
350             CheckArgumentNull(value, parameterName);
351             if (0 == value.Length) {
352                 throw Argument(Res.GetString(Res.ADP_EmptyArray, parameterName));
353             }
354         }
355         static internal void CheckArgumentNull(object value, string parameterName) {
356             if (null == value) {
357                 throw ArgumentNull(parameterName);
358             }
359         }
360
361
362         // only StackOverflowException & ThreadAbortException are sealed classes
363         static private readonly Type StackOverflowType   = typeof(StackOverflowException);
364         static private readonly Type OutOfMemoryType     = typeof(OutOfMemoryException);
365         static private readonly Type ThreadAbortType     = typeof(ThreadAbortException);
366         static private readonly Type NullReferenceType   = typeof(NullReferenceException);
367         static private readonly Type AccessViolationType = typeof(AccessViolationException);
368         static private readonly Type SecurityType        = typeof(SecurityException);
369
370         static internal bool IsCatchableExceptionType (Exception e) {
371             // a 'catchable' exception is defined by what it is not.
372             Debug.Assert(e != null, "Unexpected null exception!");
373             Type type = e.GetType();
374
375             return ( (type != StackOverflowType) &&
376                      (type != OutOfMemoryType)   &&
377                      (type != ThreadAbortType)   &&
378                      (type != NullReferenceType) &&
379                      (type != AccessViolationType) &&
380                      !SecurityType.IsAssignableFrom(type));
381         }
382
383         static internal bool IsCatchableOrSecurityExceptionType(Exception e) {
384             // a 'catchable' exception is defined by what it is not.
385             // since IsCatchableExceptionType defined SecurityException as not 'catchable'
386             // this method will return true for SecurityException has being catchable.
387
388             // the other way to write this method is, but then SecurityException is checked twice
389             // return ((e is SecurityException) || IsCatchableExceptionType(e));
390
391             Debug.Assert(e != null, "Unexpected null exception!");
392             Type type = e.GetType();
393
394             return ( (type != StackOverflowType) &&
395                      (type != OutOfMemoryType)   &&
396                      (type != ThreadAbortType)   &&
397                      (type != NullReferenceType) &&
398                      (type != AccessViolationType));
399         }
400
401         // Invalid Enumeration
402
403         static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) {
404             return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
405         }
406
407         static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) {
408             return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
409         }
410
411         static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) {
412 #if DEBUG
413             switch(value) {
414             case AcceptRejectRule.None:
415             case AcceptRejectRule.Cascade:
416                 Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
417                 break;
418             }
419 #endif
420             return InvalidEnumerationValue(typeof(AcceptRejectRule), (int) value);
421         }
422         // DbCommandBuilder.CatalogLocation
423         static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) {
424 #if DEBUG
425             switch(value) {
426             case CatalogLocation.Start:
427             case CatalogLocation.End:
428                 Debug.Assert(false, "valid CatalogLocation " + value.ToString());
429                 break;
430             }
431 #endif
432             return InvalidEnumerationValue(typeof(CatalogLocation), (int) value);
433         }
434
435         static internal ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) {
436 #if DEBUG
437             if ((0 <= (int)value) && ((int)value <= 0x3F)) {
438                 Debug.Assert(false, "valid CommandType " + value.ToString());
439             }
440 #endif
441             return InvalidEnumerationValue(typeof(CommandBehavior), (int) value);
442         }
443         static internal void ValidateCommandBehavior(CommandBehavior value) {
444             if (((int)value < 0) || (0x3F < (int)value)) {
445                 throw InvalidCommandBehavior(value);
446             }
447         }
448         static internal ArgumentException InvalidArgumentLength(string argumentName, int limit) {
449             return Argument(Res.GetString(Res.ADP_InvalidArgumentLength, argumentName, limit));
450         }
451
452         static internal ArgumentException MustBeReadOnly(string argumentName) {
453             return Argument(Res.GetString(Res.ADP_MustBeReadOnly, argumentName));
454         }
455         
456         // IDbCommand.CommandType
457         static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) {
458 #if DEBUG
459             switch(value) {
460             case CommandType.Text:
461             case CommandType.StoredProcedure:
462             case CommandType.TableDirect:
463                 Debug.Assert(false, "valid CommandType " + value.ToString());
464                 break;
465             }
466 #endif
467             return InvalidEnumerationValue(typeof(CommandType), (int) value);
468         }
469
470         static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) {
471 #if DEBUG
472             switch(value) {
473             case ConflictOption.CompareAllSearchableValues:
474             case ConflictOption.CompareRowVersion:
475             case ConflictOption.OverwriteChanges:
476                 Debug.Assert(false, "valid ConflictOption " + value.ToString());
477                 break;
478             }
479 #endif
480             return InvalidEnumerationValue(typeof(ConflictOption), (int) value);
481         }
482
483         // IDataAdapter.Update
484         static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) {
485 #if DEBUG
486             switch(value) {
487             case DataRowState.Detached:
488             case DataRowState.Unchanged:
489             case DataRowState.Added:
490             case DataRowState.Deleted:
491             case DataRowState.Modified:
492                 Debug.Assert(false, "valid DataRowState " + value.ToString());
493                 break;
494             }
495 #endif
496             return InvalidEnumerationValue(typeof(DataRowState), (int) value);
497         }
498
499         // IDataParameter.SourceVersion
500         static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) {
501 #if DEBUG
502             switch(value) {
503             case DataRowVersion.Default:
504             case DataRowVersion.Current:
505             case DataRowVersion.Original:
506             case DataRowVersion.Proposed:
507                 Debug.Assert(false, "valid DataRowVersion " + value.ToString());
508                 break;
509             }
510 #endif
511             return InvalidEnumerationValue(typeof(DataRowVersion), (int) value);
512         }
513
514         // IDbConnection.BeginTransaction, OleDbTransaction.Begin
515         static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) {
516 #if DEBUG
517             switch(value) {
518             case IsolationLevel.Unspecified:
519             case IsolationLevel.Chaos:
520             case IsolationLevel.ReadUncommitted:
521             case IsolationLevel.ReadCommitted:
522             case IsolationLevel.RepeatableRead:
523             case IsolationLevel.Serializable:
524             case IsolationLevel.Snapshot:
525                 Debug.Assert(false, "valid IsolationLevel " + value.ToString());
526                 break;
527             }
528 #endif
529             return InvalidEnumerationValue(typeof(IsolationLevel), (int) value);
530         }
531
532         // DBDataPermissionAttribute.KeyRestrictionBehavior
533         static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) {
534 #if DEBUG
535             switch(value) {
536             case KeyRestrictionBehavior.PreventUsage:
537             case KeyRestrictionBehavior.AllowOnly:
538                 Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
539                 break;
540             }
541 #endif
542             return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int) value);
543         }
544
545         // IDataAdapter.FillLoadOption
546         static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) {
547 #if DEBUG
548             switch(value) {
549             case LoadOption.OverwriteChanges:
550             case LoadOption.PreserveChanges:
551             case LoadOption.Upsert:
552                 Debug.Assert(false, "valid LoadOption " + value.ToString());
553                 break;
554             }
555 #endif
556             return InvalidEnumerationValue(typeof(LoadOption), (int) value);
557         }
558
559         // IDataAdapter.MissingMappingAction
560         static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) {
561 #if DEBUG
562             switch(value) {
563             case MissingMappingAction.Passthrough:
564             case MissingMappingAction.Ignore:
565             case MissingMappingAction.Error:
566                 Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
567                 break;
568             }
569 #endif
570             return InvalidEnumerationValue(typeof(MissingMappingAction), (int) value);
571         }
572
573         // IDataAdapter.MissingSchemaAction
574         static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) {
575 #if DEBUG
576             switch(value) {
577             case MissingSchemaAction.Add:
578             case MissingSchemaAction.Ignore:
579             case MissingSchemaAction.Error:
580             case MissingSchemaAction.AddWithKey:
581                 Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
582                 break;
583             }
584 #endif
585             return InvalidEnumerationValue(typeof(MissingSchemaAction), (int) value);
586         }
587
588         // IDataParameter.Direction
589         static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) {
590 #if DEBUG
591             switch(value) {
592             case ParameterDirection.Input:
593             case ParameterDirection.Output:
594             case ParameterDirection.InputOutput:
595             case ParameterDirection.ReturnValue:
596                 Debug.Assert(false, "valid ParameterDirection " + value.ToString());
597                 break;
598             }
599 #endif
600             return InvalidEnumerationValue(typeof(ParameterDirection), (int) value);
601         }
602
603         static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionState value) {
604 #if DEBUG
605             switch(value) {
606             case PermissionState.Unrestricted:
607             case PermissionState.None:
608                 Debug.Assert(false, "valid PermissionState " + value.ToString());
609                 break;
610             }
611 #endif
612             return InvalidEnumerationValue(typeof(PermissionState), (int) value);
613         }
614
615         static internal ArgumentOutOfRangeException InvalidRule(Rule value) {
616 #if DEBUG
617             switch(value) {
618             case Rule.None:
619             case Rule.Cascade:
620             case Rule.SetNull:
621             case Rule.SetDefault:
622                 Debug.Assert(false, "valid Rule " + value.ToString());
623                 break;
624             }
625 #endif
626             return InvalidEnumerationValue(typeof(Rule), (int) value);
627         }
628
629         // IDataAdapter.FillSchema
630         static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) {
631 #if DEBUG
632             switch(value) {
633             case SchemaType.Source:
634             case SchemaType.Mapped:
635                 Debug.Assert(false, "valid SchemaType " + value.ToString());
636                 break;
637             }
638 #endif
639             return InvalidEnumerationValue(typeof(SchemaType), (int) value);
640         }
641
642         // RowUpdatingEventArgs.StatementType
643         static internal ArgumentOutOfRangeException InvalidStatementType(StatementType value) {
644 #if DEBUG
645             switch(value) {
646             case StatementType.Select:
647             case StatementType.Insert:
648             case StatementType.Update:
649             case StatementType.Delete:
650             case StatementType.Batch:
651                  Debug.Assert(false, "valid StatementType " + value.ToString());
652                 break;
653             }
654 #endif
655             return InvalidEnumerationValue(typeof(StatementType), (int) value);
656         }
657
658         // IDbCommand.UpdateRowSource
659         static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) {
660 #if DEBUG
661             switch(value) {
662             case UpdateRowSource.None:
663             case UpdateRowSource.OutputParameters:
664             case UpdateRowSource.FirstReturnedRecord:
665             case UpdateRowSource.Both:
666                 Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
667                 break;
668             }
669 #endif
670             return InvalidEnumerationValue(typeof(UpdateRowSource), (int) value);
671         }
672
673         // RowUpdatingEventArgs.UpdateStatus
674         static internal ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) {
675 #if DEBUG
676             switch(value) {
677             case UpdateStatus.Continue:
678             case UpdateStatus.ErrorsOccurred:
679             case UpdateStatus.SkipAllRemainingRows:
680             case UpdateStatus.SkipCurrentRow:
681                 Debug.Assert(false, "valid UpdateStatus " + value.ToString());
682                 break;
683             }
684 #endif
685             return InvalidEnumerationValue(typeof(UpdateStatus), (int) value);
686         }
687
688         static internal ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) {
689             return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
690         }
691
692         static internal ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method) {
693             return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method);
694         }
695
696         static internal ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value) {
697 #if DEBUG
698             switch(value) {
699             case Microsoft.SqlServer.Server.Format.Unknown:
700             case Microsoft.SqlServer.Server.Format.Native:
701             case Microsoft.SqlServer.Server.Format.UserDefined:
702                 Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString());
703                 break;
704             }
705 #endif
706             return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int) value);
707         }
708
709         static internal ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method) {
710             return ADP.NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method);
711         }
712
713         //
714         // DbProviderFactories
715         //
716         static internal ArgumentException ConfigProviderNotFound() {
717             return Argument(Res.GetString(Res.ConfigProviderNotFound));
718         }
719         static internal InvalidOperationException ConfigProviderInvalid() {
720             return InvalidOperation(Res.GetString(Res.ConfigProviderInvalid));
721         }
722 #if !MOBILE
723         static internal ConfigurationException ConfigProviderNotInstalled() {
724             return Configuration(Res.GetString(Res.ConfigProviderNotInstalled));
725         }
726         static internal ConfigurationException ConfigProviderMissing() {
727             return Configuration(Res.GetString(Res.ConfigProviderMissing));
728         }
729
730         //
731         // DbProviderConfigurationHandler
732         //
733         static internal ConfigurationException ConfigBaseNoChildNodes(XmlNode node) { // Res.Config_base_no_child_nodes
734             return Configuration(Res.GetString(Res.ConfigBaseNoChildNodes), node);
735         }
736         static internal ConfigurationException ConfigBaseElementsOnly(XmlNode node) { // Res.Config_base_elements_only
737             return Configuration(Res.GetString(Res.ConfigBaseElementsOnly), node);
738         }
739         static internal ConfigurationException ConfigUnrecognizedAttributes(XmlNode node) { // Res.Config_base_unrecognized_attribute
740             return Configuration(Res.GetString(Res.ConfigUnrecognizedAttributes, node.Attributes[0].Name), node);
741         }
742         static internal ConfigurationException ConfigUnrecognizedElement(XmlNode node) { // Res.Config_base_unrecognized_element
743             return Configuration(Res.GetString(Res.ConfigUnrecognizedElement), node);
744         }
745         static internal ConfigurationException ConfigSectionsUnique(string sectionName) { // Res.Res.ConfigSectionsUnique
746             return Configuration(Res.GetString(Res.ConfigSectionsUnique, sectionName));
747         }
748         static internal ConfigurationException ConfigRequiredAttributeMissing(string name, XmlNode node) { // Res.Config_base_required_attribute_missing
749             return Configuration(Res.GetString(Res.ConfigRequiredAttributeMissing, name), node);
750         }
751         static internal ConfigurationException ConfigRequiredAttributeEmpty(string name, XmlNode node) { // Res.Config_base_required_attribute_empty
752             return Configuration(Res.GetString(Res.ConfigRequiredAttributeEmpty, name), node);
753         }
754 #endif
755         //
756         // DbConnectionOptions, DataAccess
757         //
758         static internal ArgumentException ConnectionStringSyntax(int index) {
759             return Argument(Res.GetString(Res.ADP_ConnectionStringSyntax, index));
760         }
761         static internal ArgumentException KeywordNotSupported(string keyword) {
762             return Argument(Res.GetString(Res.ADP_KeywordNotSupported, keyword));
763         }
764         /*
765         static internal ArgumentException EmptyKeyValue(string keyword) { // MDAC 80715
766             return Argument(Res.GetString(Res.ADP_EmptyKeyValue, keyword));
767         }
768         */
769         static internal ArgumentException UdlFileError(Exception inner) {
770             return Argument(Res.GetString(Res.ADP_UdlFileError), inner);
771         }
772         static internal ArgumentException InvalidUDL() {
773             return Argument(Res.GetString(Res.ADP_InvalidUDL));
774         }
775         static internal InvalidOperationException InvalidDataDirectory() {
776             return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidDataDirectory));
777         }
778         static internal ArgumentException InvalidKeyname(string parameterName) {
779             return Argument(Res.GetString(Res.ADP_InvalidKey), parameterName);
780         }
781         static internal ArgumentException InvalidValue(string parameterName) {
782             return Argument(Res.GetString(Res.ADP_InvalidValue), parameterName);
783         }
784         static internal ArgumentException InvalidMinMaxPoolSizeValues() {
785             return ADP.Argument(Res.GetString(Res.ADP_InvalidMinMaxPoolSizeValues));
786         }
787         static internal ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) {
788             return ADP.Argument(Res.GetString(Res.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
789         }
790
791         static internal InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() {
792             return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
793         }
794         
795         static internal ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() {
796             return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
797         }
798
799         static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() {
800             return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
801         }
802
803        static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() {
804            return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
805         }
806
807        static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndContextConnection()
808        {
809            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
810        }
811
812        static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndContextConnection() 
813        {
814            return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
815        }
816
817        static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndContextConnection() {
818            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndContextConnection));
819        }
820
821        static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() {
822            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity));
823        }
824
825        static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() {
826            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword));
827        }
828
829        static internal Exception InvalidMixedUsageOfAccessTokenAndCredential() {
830            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndCredential));
831        }
832
833        static internal Exception InvalidMixedUsageOfAccessTokenAndAuthentication() {
834            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication));
835        }
836
837        static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() {
838            return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
839        }
840
841        //
842         // DbConnection
843         //
844         static internal InvalidOperationException NoConnectionString() {
845             return InvalidOperation(Res.GetString(Res.ADP_NoConnectionString));
846         }
847
848         static internal NotImplementedException MethodNotImplemented(string methodName) {
849             NotImplementedException e = new NotImplementedException(methodName);
850             TraceExceptionAsReturnValue(e);
851             return e;
852         }
853         static private string ConnectionStateMsg(ConnectionState state) { // MDAC 82165, if the ConnectionState enum to msg the localization looks weird
854             switch(state) {
855             case (ConnectionState.Closed):
856             case (ConnectionState.Connecting|ConnectionState.Broken): // treated the same as closed
857                 return Res.GetString(Res.ADP_ConnectionStateMsg_Closed);
858             case (ConnectionState.Connecting):
859                 return Res.GetString(Res.ADP_ConnectionStateMsg_Connecting);
860             case (ConnectionState.Open):
861                 return Res.GetString(Res.ADP_ConnectionStateMsg_Open);
862             case (ConnectionState.Open|ConnectionState.Executing):
863                 return Res.GetString(Res.ADP_ConnectionStateMsg_OpenExecuting);
864             case (ConnectionState.Open|ConnectionState.Fetching):
865                 return Res.GetString(Res.ADP_ConnectionStateMsg_OpenFetching);
866             default:
867                 return Res.GetString(Res.ADP_ConnectionStateMsg, state.ToString());
868             }
869         }
870 #if !MOBILE
871         static internal ConfigurationException ConfigUnableToLoadXmlMetaDataFile(string settingName){
872             return Configuration(Res.GetString(Res.OleDb_ConfigUnableToLoadXmlMetaDataFile, settingName));
873         }
874
875         static internal ConfigurationException ConfigWrongNumberOfValues(string settingName){
876             return Configuration(Res.GetString(Res.OleDb_ConfigWrongNumberOfValues, settingName));
877         }
878 #endif
879         //
880         // : DbConnectionOptions, DataAccess, SqlClient
881         //
882         static internal Exception InvalidConnectionOptionValue(string key) {
883             return InvalidConnectionOptionValue(key, null);
884         }
885         static internal Exception InvalidConnectionOptionValueLength(string key, int limit) {
886             return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValueLength, key, limit));
887         }
888         static internal Exception InvalidConnectionOptionValue(string key, Exception inner) {
889             return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValue, key), inner);
890         }
891         static internal Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) {
892             return Argument(Res.GetString(Res.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
893         }
894
895         //
896         // DBDataPermission, DataAccess, Odbc
897         //
898         static internal Exception InvalidXMLBadVersion() {
899             return Argument(Res.GetString(Res.ADP_InvalidXMLBadVersion));
900         }
901         static internal Exception NotAPermissionElement() {
902             return Argument(Res.GetString(Res.ADP_NotAPermissionElement));
903         }
904         static internal Exception PermissionTypeMismatch() {
905             return Argument(Res.GetString(Res.ADP_PermissionTypeMismatch));
906         }
907
908         static internal Exception WrongType(Type got, Type expected) {
909             return Argument(Res.GetString(Res.SQL_WrongType, got.ToString(), expected.ToString()));
910         }
911
912         static internal Exception OdbcNoTypesFromProvider() {
913             return InvalidOperation(Res.GetString(Res.ADP_OdbcNoTypesFromProvider));
914         }
915
916         //
917         // DbConnectionPool and related
918         //
919         static internal Exception PooledOpenTimeout() {
920             return ADP.InvalidOperation(Res.GetString(Res.ADP_PooledOpenTimeout));
921         }
922
923         static internal Exception NonPooledOpenTimeout() {
924             return ADP.TimeoutException(Res.GetString(Res.ADP_NonPooledOpenTimeout));
925         }
926         
927         //
928         // Generic Data Provider Collection
929         //
930         static internal ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) {
931             return Argument(Res.GetString(Res.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); // MDAC 68201
932         }
933         static internal ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) {
934             return ArgumentNull(parameter, Res.GetString(Res.ADP_CollectionNullValue, collection.Name, itemType.Name));
935         }
936         static internal IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) {
937             return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
938         }
939         static internal IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) {
940             return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
941         }
942         static internal InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) {
943             return InvalidCast(Res.GetString(Res.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
944         }
945         static internal Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue) {
946             return Argument(Res.GetString(Res.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue));
947         }
948         static internal ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) {
949             return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
950         }
951         static internal ArgumentException ParametersIsParent(Type parameterType, ICollection collection) {
952             return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
953         }
954
955         //
956         // DbProviderException
957         //
958         static internal InvalidOperationException TransactionConnectionMismatch() {
959             return Provider(Res.GetString(Res.ADP_TransactionConnectionMismatch));
960         }
961         static internal InvalidOperationException TransactionCompletedButNotDisposed()
962         {
963             return Provider(Res.GetString(Res.ADP_TransactionCompletedButNotDisposed));
964         }
965         static internal InvalidOperationException TransactionRequired(string method) {
966             return Provider(Res.GetString(Res.ADP_TransactionRequired, method));
967         }
968
969         // IDbDataAdapter.Fill(Schema)
970         static internal InvalidOperationException MissingSelectCommand(string method) {
971             return Provider(Res.GetString(Res.ADP_MissingSelectCommand, method));
972         }
973
974         //
975         // AdapterMappingException
976         //
977         static private InvalidOperationException DataMapping(string error) {
978             return InvalidOperation(error);
979         }
980
981         // DataColumnMapping.GetDataColumnBySchemaAction
982         static internal InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn) {
983             return DataMapping(Res.GetString(Res.ADP_ColumnSchemaExpression, srcColumn, cacheColumn));
984         }
985
986         // DataColumnMapping.GetDataColumnBySchemaAction
987         static internal InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column) {
988             return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name));
989         }
990
991         // DataColumnMapping.GetDataColumnBySchemaAction
992         static internal InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn) {
993             if (ADP.IsEmpty(tableName)) {
994                 return InvalidOperation(Res.GetString(Res.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn));
995             }
996             return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn));
997         }
998
999         // DataColumnMappingCollection.GetColumnMappingBySchemaAction
1000         static internal InvalidOperationException MissingColumnMapping(string srcColumn) {
1001             return DataMapping(Res.GetString(Res.ADP_MissingColumnMapping, srcColumn));
1002         }
1003
1004         // DataTableMapping.GetDataTableBySchemaAction
1005         static internal InvalidOperationException MissingTableSchema(string cacheTable, string srcTable) {
1006             return DataMapping(Res.GetString(Res.ADP_MissingTableSchema, cacheTable, srcTable));
1007         }
1008
1009         // DataTableMappingCollection.GetTableMappingBySchemaAction
1010         static internal InvalidOperationException MissingTableMapping(string srcTable) {
1011             return DataMapping(Res.GetString(Res.ADP_MissingTableMapping, srcTable));
1012         }
1013
1014         // DbDataAdapter.Update
1015         static internal InvalidOperationException MissingTableMappingDestination(string dstTable) {
1016             return DataMapping(Res.GetString(Res.ADP_MissingTableMappingDestination, dstTable));
1017         }
1018
1019         //
1020         // DataColumnMappingCollection, DataAccess
1021         //
1022         static internal Exception InvalidSourceColumn(string parameter) {
1023             return Argument(Res.GetString(Res.ADP_InvalidSourceColumn), parameter);
1024         }
1025         static internal Exception ColumnsAddNullAttempt(string parameter) {
1026             return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping));
1027         }
1028         static internal Exception ColumnsDataSetColumn(string cacheColumn) {
1029             return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection));
1030         }
1031         static internal Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection) {
1032             return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1033         }
1034         static internal Exception ColumnsIndexSource(string srcColumn) {
1035             return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection));
1036         }
1037         static internal Exception ColumnsIsNotParent(ICollection collection) {
1038             return ParametersIsNotParent(typeof(DataColumnMapping), collection);
1039         }
1040         static internal Exception ColumnsIsParent(ICollection collection) {
1041             return ParametersIsParent(typeof(DataColumnMapping), collection);
1042         }
1043         static internal Exception ColumnsUniqueSourceColumn(string srcColumn) {
1044             return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn);
1045         }
1046         static internal Exception NotADataColumnMapping(object value) {
1047             return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value);
1048         }
1049
1050         //
1051         // DataTableMappingCollection, DataAccess
1052         //
1053         static internal Exception InvalidSourceTable(string parameter) {
1054             return Argument(Res.GetString(Res.ADP_InvalidSourceTable), parameter);
1055         }
1056         static internal Exception TablesAddNullAttempt(string parameter) {
1057             return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping));
1058         }
1059         static internal Exception TablesDataSetTable(string cacheTable) {
1060             return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection));
1061         }
1062         static internal Exception TablesIndexInt32(int index, ITableMappingCollection collection) {
1063             return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1064         }
1065         static internal Exception TablesIsNotParent(ICollection collection) {
1066             return ParametersIsNotParent(typeof(DataTableMapping), collection);
1067         }
1068         static internal Exception TablesIsParent(ICollection collection) {
1069             return ParametersIsParent(typeof(DataTableMapping), collection);
1070         }
1071         static internal Exception TablesSourceIndex(string srcTable) {
1072             return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection));
1073         }
1074         static internal Exception TablesUniqueSourceTable(string srcTable) {
1075             return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable);
1076         }
1077         static internal Exception NotADataTableMapping(object value) {
1078             return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value);
1079         }
1080
1081         //
1082         // IDbCommand
1083         //
1084
1085         static internal InvalidOperationException CommandAsyncOperationCompleted() {
1086             return InvalidOperation(Res.GetString(Res.SQL_AsyncOperationCompleted));
1087         }
1088
1089         static internal Exception CommandTextRequired(string method) {
1090             return InvalidOperation(Res.GetString(Res.ADP_CommandTextRequired, method));
1091         }
1092
1093         static internal InvalidOperationException ConnectionRequired(string method) {
1094             return InvalidOperation(Res.GetString(Res.ADP_ConnectionRequired, method));
1095         }
1096         static internal InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) {
1097             return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
1098         }
1099
1100
1101         static internal InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand) {
1102             string resource;
1103             if (isRowUpdatingCommand) {
1104                 resource = Res.ADP_ConnectionRequired_Clone;
1105             }
1106             else {
1107                 switch(statementType) {
1108                 case StatementType.Insert:
1109                     resource = Res.ADP_ConnectionRequired_Insert;
1110                     break;
1111                 case StatementType.Update:
1112                     resource = Res.ADP_ConnectionRequired_Update;
1113                     break;
1114                 case StatementType.Delete:
1115                     resource = Res.ADP_ConnectionRequired_Delete;
1116                     break;
1117                 case StatementType.Batch:
1118                     resource = Res.ADP_ConnectionRequired_Batch;
1119                     goto default;
1120 #if DEBUG
1121                 case StatementType.Select:
1122                     Debug.Assert(false, "shouldn't be here");
1123                     goto default;
1124 #endif
1125                 default:
1126                     throw ADP.InvalidStatementType(statementType);
1127                 }
1128             }
1129             return InvalidOperation(Res.GetString(resource));
1130         }
1131
1132         static internal InvalidOperationException ConnectionRequired_Res(string method) {
1133             string resource = "ADP_ConnectionRequired_" + method;
1134 #if DEBUG
1135             switch(resource) {
1136             case Res.ADP_ConnectionRequired_Fill:
1137             case Res.ADP_ConnectionRequired_FillPage:
1138             case Res.ADP_ConnectionRequired_FillSchema:
1139             case Res.ADP_ConnectionRequired_Update:
1140             case Res.ADP_ConnecitonRequired_UpdateRows:
1141                 break;
1142             default:
1143                 Debug.Assert(false, "missing resource string: " + resource);
1144                 break;
1145             }
1146 #endif
1147             return InvalidOperation(Res.GetString(resource));
1148         }
1149         static internal InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state) {
1150             string resource;
1151             if (isRowUpdatingCommand) {
1152                 resource = Res.ADP_OpenConnectionRequired_Clone;
1153             }
1154             else {
1155                 switch(statementType) {
1156                 case StatementType.Insert:
1157                     resource = Res.ADP_OpenConnectionRequired_Insert;
1158                     break;
1159                 case StatementType.Update:
1160                     resource = Res.ADP_OpenConnectionRequired_Update;
1161                     break;
1162                 case StatementType.Delete:
1163                     resource = Res.ADP_OpenConnectionRequired_Delete;
1164                     break;
1165 #if DEBUG
1166                 case StatementType.Select:
1167                     Debug.Assert(false, "shouldn't be here");
1168                     goto default;
1169                 case StatementType.Batch:
1170                     Debug.Assert(false, "isRowUpdatingCommand should have been true");
1171                     goto default;
1172 #endif
1173                 default:
1174                     throw ADP.InvalidStatementType(statementType);
1175                 }
1176             }
1177             return InvalidOperation(Res.GetString(resource, ADP.ConnectionStateMsg(state)));
1178         }
1179
1180         static internal Exception NoStoredProcedureExists(string sproc) {
1181             return InvalidOperation(Res.GetString(Res.ADP_NoStoredProcedureExists, sproc));
1182         }
1183         static internal Exception OpenReaderExists() {
1184             return OpenReaderExists(null);
1185         }
1186
1187         static internal Exception OpenReaderExists(Exception e) {
1188             return InvalidOperation(Res.GetString(Res.ADP_OpenReaderExists), e);
1189         }
1190
1191         static internal Exception TransactionCompleted() {
1192             return DataAdapter(Res.GetString(Res.ADP_TransactionCompleted));
1193         }
1194
1195         //
1196         // DbDataReader
1197         //
1198         static internal Exception NonSeqByteAccess(long badIndex, long currIndex, string method) {
1199             return InvalidOperation(Res.GetString(Res.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
1200         }
1201
1202         static internal Exception NegativeParameter(string parameterName) {
1203             return InvalidOperation(Res.GetString(Res.ADP_NegativeParameter, parameterName));
1204         }
1205
1206         static internal Exception NumericToDecimalOverflow() {
1207             return InvalidCast(Res.GetString(Res.ADP_NumericToDecimalOverflow));
1208         }
1209
1210         //
1211         // Stream, SqlTypes, SqlClient
1212         //
1213
1214         static internal Exception ExceedsMaxDataLength(long specifiedLength, long maxLength) {
1215             return IndexOutOfRange(Res.GetString(Res.SQL_ExceedsMaxDataLength, specifiedLength.ToString(CultureInfo.InvariantCulture), maxLength.ToString(CultureInfo.InvariantCulture)));
1216         }
1217
1218         static internal Exception InvalidSeekOrigin(string parameterName) {
1219             return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSeekOrigin), parameterName);
1220         }
1221
1222         //
1223         // SqlMetaData, SqlTypes, SqlClient
1224         //
1225         static internal Exception InvalidImplicitConversion(Type fromtype, string totype) {
1226             return InvalidCast(Res.GetString(Res.ADP_InvalidImplicitConversion, fromtype.Name, totype));
1227         }
1228         static internal Exception InvalidMetaDataValue() {
1229             return ADP.Argument(Res.GetString(Res.ADP_InvalidMetaDataValue));
1230         }
1231
1232         static internal Exception NotRowType() {
1233             return InvalidOperation(Res.GetString(Res.ADP_NotRowType));
1234         }
1235
1236         //
1237         // DbDataAdapter
1238         //
1239         static internal ArgumentException UnwantedStatementType(StatementType statementType) {
1240             return Argument(Res.GetString(Res.ADP_UnwantedStatementType, statementType.ToString()));
1241         }
1242         static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) {
1243             return InvalidOperation(Res.GetString(Res.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
1244         }
1245
1246         //
1247         // DbDataAdapter.FillSchema
1248         //
1249         static internal Exception FillSchemaRequiresSourceTableName(string parameter) {
1250             return Argument(Res.GetString(Res.ADP_FillSchemaRequiresSourceTableName), parameter);
1251         }
1252
1253         //
1254         // DbDataAdapter.Fill
1255         //
1256         static internal Exception InvalidMaxRecords(string parameter, int max) {
1257             return Argument(Res.GetString(Res.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter);
1258         }
1259         static internal Exception InvalidStartRecord(string parameter, int start) {
1260             return Argument(Res.GetString(Res.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter);
1261         }
1262         static internal Exception FillRequires(string parameter) {
1263             return ArgumentNull(parameter);
1264         }
1265         static internal Exception FillRequiresSourceTableName(string parameter) {
1266             return Argument(Res.GetString(Res.ADP_FillRequiresSourceTableName), parameter);
1267         }
1268         static internal Exception FillChapterAutoIncrement() {
1269             return InvalidOperation(Res.GetString(Res.ADP_FillChapterAutoIncrement));
1270         }
1271         static internal InvalidOperationException MissingDataReaderFieldType(int index) {
1272             return DataAdapter(Res.GetString(Res.ADP_MissingDataReaderFieldType, index));
1273         }
1274         static internal InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords() {
1275             return DataAdapter(Res.GetString(Res.ADP_OnlyOneTableForStartRecordOrMaxRecords));
1276         }
1277         //
1278         // DbDataAdapter.Update
1279         //
1280         static internal ArgumentNullException UpdateRequiresNonNullDataSet(string parameter) {
1281             return ArgumentNull(parameter);
1282         }
1283         static internal InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName) {
1284             return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTable, defaultSrcTableName));
1285         }
1286         static internal InvalidOperationException UpdateRequiresSourceTableName(string srcTable) {
1287             return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTableName, srcTable)); // MDAC 70448
1288         }
1289         static internal ArgumentNullException UpdateRequiresDataTable(string parameter) {
1290             return ArgumentNull(parameter);
1291         }
1292
1293         static internal Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows) {
1294             string resource;
1295             switch(statementType) {
1296             case StatementType.Update:
1297                 resource = Res.ADP_UpdateConcurrencyViolation_Update;
1298                 break;
1299             case StatementType.Delete:
1300                 resource = Res.ADP_UpdateConcurrencyViolation_Delete;
1301                 break;
1302             case StatementType.Batch:
1303                 resource = Res.ADP_UpdateConcurrencyViolation_Batch;
1304                 break;
1305 #if DEBUG
1306             case StatementType.Select:
1307             case StatementType.Insert:
1308                 Debug.Assert(false, "should be here");
1309                 goto default;
1310 #endif
1311             default:
1312                 throw ADP.InvalidStatementType(statementType);
1313             }
1314             DBConcurrencyException exception = new DBConcurrencyException(Res.GetString(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows);
1315             TraceExceptionAsReturnValue(exception);
1316             return exception;
1317         }
1318
1319         static internal InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand) {
1320             string resource;
1321             if (isRowUpdatingCommand) {
1322                 resource = Res.ADP_UpdateRequiresCommandClone;
1323             }
1324             else {
1325                 switch(statementType) {
1326                 case StatementType.Select:
1327                     resource = Res.ADP_UpdateRequiresCommandSelect;
1328                     break;
1329                 case StatementType.Insert:
1330                     resource = Res.ADP_UpdateRequiresCommandInsert;
1331                     break;
1332                 case StatementType.Update:
1333                     resource = Res.ADP_UpdateRequiresCommandUpdate;
1334                     break;
1335                 case StatementType.Delete:
1336                     resource = Res.ADP_UpdateRequiresCommandDelete;
1337                     break;
1338 #if DEBUG
1339                 case StatementType.Batch:
1340                     Debug.Assert(false, "isRowUpdatingCommand should have been true");
1341                     goto default;
1342 #endif
1343                 default:
1344                     throw ADP.InvalidStatementType(statementType);
1345                 }
1346             }
1347             return InvalidOperation(Res.GetString(resource));
1348         }
1349         static internal ArgumentException UpdateMismatchRowTable(int i) {
1350             return Argument(Res.GetString(Res.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture)));
1351         }
1352         static internal DataException RowUpdatedErrors() {
1353             return Data(Res.GetString(Res.ADP_RowUpdatedErrors));
1354         }
1355         static internal DataException RowUpdatingErrors() {
1356             return Data(Res.GetString(Res.ADP_RowUpdatingErrors));
1357         }
1358         static internal InvalidOperationException ResultsNotAllowedDuringBatch() {
1359             return DataAdapter(Res.GetString(Res.ADP_ResultsNotAllowedDuringBatch));
1360         }
1361
1362         //
1363         // : IDbCommand
1364         //
1365         static internal Exception InvalidCommandTimeout(int value) {
1366             return Argument(Res.GetString(Res.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout);
1367         }
1368         static internal Exception DeriveParametersNotSupported(IDbCommand value) {
1369             return DataAdapter(Res.GetString(Res.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
1370         }
1371         static internal Exception UninitializedParameterSize(int index, Type dataType) {
1372             return InvalidOperation(Res.GetString(Res.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
1373         }
1374         static internal Exception PrepareParameterType(IDbCommand cmd) {
1375             return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterType, cmd.GetType().Name));
1376         }
1377         static internal Exception PrepareParameterSize(IDbCommand cmd) {
1378             return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name));
1379         }
1380         static internal Exception PrepareParameterScale(IDbCommand cmd, string type) {
1381             return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterScale, cmd.GetType().Name, type));
1382         }
1383         static internal Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) {
1384             return InvalidOperation(Res.GetString(Res.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
1385         }
1386
1387         //
1388         // : ConnectionUtil
1389         //
1390         static internal Exception ConnectionIsDisabled (Exception InnerException) {
1391             return InvalidOperation(Res.GetString(Res.ADP_ConnectionIsDisabled), InnerException);
1392         }
1393         static internal Exception ClosedConnectionError() {
1394             return InvalidOperation(Res.GetString(Res.ADP_ClosedConnectionError));
1395         }
1396         static internal Exception ConnectionAlreadyOpen(ConnectionState state) {
1397             return InvalidOperation(Res.GetString(Res.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
1398         }
1399         static internal Exception DelegatedTransactionPresent() {
1400             return InvalidOperation(Res.GetString(Res.ADP_DelegatedTransactionPresent));
1401         }
1402         static internal Exception TransactionPresent() {
1403             return InvalidOperation(Res.GetString(Res.ADP_TransactionPresent));
1404         }
1405         static internal Exception LocalTransactionPresent() {
1406             return InvalidOperation(Res.GetString(Res.ADP_LocalTransactionPresent));
1407         }
1408         static internal Exception OpenConnectionPropertySet(string property, ConnectionState state) {
1409             return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
1410         }
1411         static internal Exception EmptyDatabaseName() {
1412             return Argument(Res.GetString(Res.ADP_EmptyDatabaseName));
1413         }
1414         static internal Exception DatabaseNameTooLong() {
1415             return Argument(Res.GetString(Res.ADP_DatabaseNameTooLong));
1416         }
1417
1418         internal enum ConnectionError {
1419             BeginGetConnectionReturnsNull,
1420             GetConnectionReturnsNull,
1421             ConnectionOptionsMissing,
1422             CouldNotSwitchToClosedPreviouslyOpenedState,
1423         }
1424         static internal Exception InternalConnectionError(ConnectionError internalError) {
1425             return InvalidOperation(Res.GetString(Res.ADP_InternalConnectionError, (int)internalError));
1426         }
1427
1428         internal enum InternalErrorCode {
1429             UnpooledObjectHasOwner                                  =  0,
1430             UnpooledObjectHasWrongOwner                             =  1,
1431             PushingObjectSecondTime                                 =  2,
1432             PooledObjectHasOwner                                    =  3,
1433             PooledObjectInPoolMoreThanOnce                          =  4,
1434             CreateObjectReturnedNull                                =  5,
1435             NewObjectCannotBePooled                                 =  6,
1436             NonPooledObjectUsedMoreThanOnce                         =  7,
1437             AttemptingToPoolOnRestrictedToken                       =  8,
1438 //          ConnectionOptionsInUse                                  =  9,
1439             ConvertSidToStringSidWReturnedNull                      = 10,
1440 //          UnexpectedTransactedObject                              = 11,
1441             AttemptingToConstructReferenceCollectionOnStaticObject  = 12,
1442             AttemptingToEnlistTwice                                 = 13,
1443             CreateReferenceCollectionReturnedNull                   = 14,
1444             PooledObjectWithoutPool                                 = 15,
1445             UnexpectedWaitAnyResult                                 = 16,
1446             SynchronousConnectReturnedPending                       = 17,
1447             CompletedConnectReturnedPending                         = 18,
1448
1449             NameValuePairNext                                       = 20,
1450             InvalidParserState1                                     = 21,
1451             InvalidParserState2                                     = 22,
1452             InvalidParserState3                                     = 23,
1453
1454             InvalidBuffer                                           = 30,
1455
1456             UnimplementedSMIMethod                                  = 40,
1457             InvalidSmiCall                                          = 41,
1458
1459             SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
1460             SqlDependencyProcessDispatcherFailureCreateInstance     = 51,
1461             SqlDependencyProcessDispatcherFailureAppDomain          = 52,
1462             SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
1463
1464             UnknownTransactionFailure                               = 60,
1465         }
1466         static internal Exception InternalError(InternalErrorCode internalError) {
1467             return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError));
1468         }
1469         static internal Exception InternalError(InternalErrorCode internalError, Exception innerException) {
1470             return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError), innerException);
1471         }
1472         static internal Exception InvalidConnectTimeoutValue() {
1473             return Argument(Res.GetString(Res.ADP_InvalidConnectTimeoutValue));
1474         }
1475
1476         static internal Exception InvalidConnectRetryCountValue() {
1477             return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryCountValue));
1478         }
1479
1480         static internal Exception InvalidConnectRetryIntervalValue() {
1481             return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryIntervalValue));
1482         }
1483
1484         //
1485         // : DbDataReader
1486         //
1487         static internal Exception DataReaderNoData() {
1488             return InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData));
1489         }
1490         static internal Exception DataReaderClosed(string method) {
1491             return InvalidOperation(Res.GetString(Res.ADP_DataReaderClosed, method));
1492         }
1493         static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) {
1494             return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
1495         }
1496         static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) {
1497             return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
1498         }
1499         static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) {
1500             return IndexOutOfRange(Res.GetString(Res.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
1501         }
1502         static internal Exception InvalidDataLength(long length) {
1503             return IndexOutOfRange(Res.GetString(Res.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
1504         }
1505         static internal InvalidOperationException AsyncOperationPending() {
1506             return InvalidOperation(Res.GetString(Res.ADP_PendingAsyncOperation));
1507         }
1508
1509         //
1510         // : Stream
1511         //
1512         static internal Exception StreamClosed(string method) {
1513             return InvalidOperation(Res.GetString(Res.ADP_StreamClosed, method));
1514         }
1515         static internal IOException ErrorReadingFromStream(Exception internalException) {
1516             return IO(Res.GetString(Res.SqlMisc_StreamErrorMessage), internalException);
1517         }
1518
1519         //
1520         // : DbDataAdapter
1521         //
1522         static internal InvalidOperationException DynamicSQLJoinUnsupported() {
1523             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLJoinUnsupported));
1524         }
1525         static internal InvalidOperationException DynamicSQLNoTableInfo() {
1526             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoTableInfo));
1527         }
1528         static internal InvalidOperationException DynamicSQLNoKeyInfoDelete() {
1529             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoDelete));
1530         }
1531         static internal InvalidOperationException DynamicSQLNoKeyInfoUpdate() {
1532             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoUpdate));
1533         }
1534         static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete() {
1535             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionDelete));
1536         }
1537         static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate() {
1538             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionUpdate));
1539         }
1540         static internal InvalidOperationException DynamicSQLNestedQuote(string name, string quote) {
1541             return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNestedQuote, name, quote));
1542         }
1543         static internal InvalidOperationException NoQuoteChange() {
1544             return InvalidOperation(Res.GetString(Res.ADP_NoQuoteChange));
1545         }
1546         static internal InvalidOperationException ComputerNameEx(int lastError) {
1547             return InvalidOperation(Res.GetString(Res.ADP_ComputerNameEx, lastError));
1548         }
1549         static internal InvalidOperationException MissingSourceCommand() {
1550             return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommand));
1551         }
1552         static internal InvalidOperationException MissingSourceCommandConnection() {
1553             return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommandConnection));
1554         }
1555
1556         //
1557         // : IDataParameter
1558         //
1559         static internal ArgumentException InvalidDataType(TypeCode typecode) {
1560             return Argument(Res.GetString(Res.ADP_InvalidDataType, typecode.ToString()));
1561         }
1562         static internal ArgumentException UnknownDataType(Type dataType) {
1563             return Argument(Res.GetString(Res.ADP_UnknownDataType, dataType.FullName));
1564         }
1565         static internal ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype) {
1566             return Argument(Res.GetString(Res.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
1567         }
1568         static internal ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) {
1569             return Argument(Res.GetString(Res.ADP_UnknownDataTypeCode, ((int) typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
1570         }
1571         static internal ArgumentException InvalidOffsetValue(int value) {
1572             return Argument(Res.GetString(Res.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
1573         }
1574         static internal ArgumentException InvalidSizeValue(int value) {
1575             return Argument(Res.GetString(Res.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
1576         }
1577         static internal ArgumentException ParameterValueOutOfRange(Decimal value) {
1578             return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
1579         }
1580         static internal ArgumentException ParameterValueOutOfRange(SqlDecimal value) {
1581             return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString()));
1582         }
1583
1584         static internal ArgumentException ParameterValueOutOfRange(String value) {
1585             return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value));
1586         }
1587
1588         static internal ArgumentException VersionDoesNotSupportDataType(string typeName) {
1589             return Argument(Res.GetString(Res.ADP_VersionDoesNotSupportDataType, typeName));
1590         }
1591         static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) { // WebData 75433
1592             Debug.Assert(null != value, "null value on conversion failure");
1593             Debug.Assert(null != inner, "null inner on conversion failure");
1594
1595             Exception e;
1596             string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
1597             if (inner is ArgumentException) {
1598                 e = new ArgumentException(message, inner);
1599             }
1600             else if (inner is FormatException) {
1601                 e = new FormatException(message, inner);
1602             }
1603             else if (inner is InvalidCastException) {
1604                 e = new InvalidCastException(message, inner);
1605             }
1606             else if (inner is OverflowException) {
1607                 e = new OverflowException(message, inner);
1608             }
1609             else {
1610                 e = inner;
1611             }
1612             TraceExceptionAsReturnValue(e);
1613             return e;
1614         }
1615
1616         //
1617         // : IDataParameterCollection
1618         //
1619         static internal Exception ParametersMappingIndex(int index, IDataParameterCollection collection) {
1620             return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1621         }
1622         static internal Exception ParametersSourceIndex(string parameterName, IDataParameterCollection collection, Type parameterType) {
1623             return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
1624         }
1625         static internal Exception ParameterNull(string parameter, IDataParameterCollection collection, Type parameterType) {
1626             return CollectionNullValue(parameter, collection.GetType(), parameterType);
1627         }
1628         static internal Exception InvalidParameterType(IDataParameterCollection collection, Type parameterType, object invalidValue) {
1629             return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
1630         }
1631
1632         //
1633         // : IDbTransaction
1634         //
1635         static internal Exception ParallelTransactionsNotSupported(IDbConnection obj) {
1636             return InvalidOperation(Res.GetString(Res.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
1637         }
1638         static internal Exception TransactionZombied(IDbTransaction obj) {
1639             return InvalidOperation(Res.GetString(Res.ADP_TransactionZombied, obj.GetType().Name));
1640         }
1641
1642         static internal Exception DbRecordReadOnly(string methodname) {
1643             return InvalidOperation(Res.GetString(Res.ADP_DbRecordReadOnly, methodname));
1644         }
1645
1646         static internal Exception OffsetOutOfRangeException() {
1647             return InvalidOperation(Res.GetString(Res.ADP_OffsetOutOfRangeException));
1648         }
1649
1650          //
1651         // : DbMetaDataFactory
1652         //
1653
1654         static internal Exception AmbigousCollectionName(string collectionName) {
1655             return Argument(Res.GetString(Res.MDF_AmbigousCollectionName,collectionName));
1656         }
1657
1658         static internal Exception CollectionNameIsNotUnique(string collectionName) {
1659             return Argument(Res.GetString(Res.MDF_CollectionNameISNotUnique,collectionName));
1660         }
1661
1662         static internal Exception DataTableDoesNotExist(string collectionName) {
1663             return Argument(Res.GetString(Res.MDF_DataTableDoesNotExist,collectionName));
1664         }
1665
1666         static internal Exception IncorrectNumberOfDataSourceInformationRows() {
1667             return Argument(Res.GetString(Res.MDF_IncorrectNumberOfDataSourceInformationRows));
1668         }
1669
1670         static internal ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue) {
1671             return ADP.Argument(Res.GetString(Res.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue));
1672         }
1673
1674         static internal Exception InvalidXml() {
1675             return Argument(Res.GetString(Res.MDF_InvalidXml));
1676         }
1677
1678         static internal Exception InvalidXmlMissingColumn(string collectionName, string columnName) {
1679             return Argument(Res.GetString(Res.MDF_InvalidXmlMissingColumn, collectionName, columnName));
1680         }
1681
1682         static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName) {
1683             return Argument(Res.GetString(Res.MDF_InvalidXmlInvalidValue, collectionName, columnName));
1684         }
1685
1686         static internal Exception MissingDataSourceInformationColumn() {
1687             return Argument(Res.GetString(Res.MDF_MissingDataSourceInformationColumn));
1688         }
1689
1690         static internal Exception MissingRestrictionColumn() {
1691             return Argument(Res.GetString(Res.MDF_MissingRestrictionColumn));
1692         }
1693
1694         static internal Exception MissingRestrictionRow() {
1695             return Argument(Res.GetString(Res.MDF_MissingRestrictionRow));
1696         }
1697
1698         static internal Exception NoColumns() {
1699             return Argument(Res.GetString(Res.MDF_NoColumns));
1700         }
1701
1702         static internal Exception QueryFailed(string collectionName, Exception e) {
1703             return InvalidOperation(Res.GetString(Res.MDF_QueryFailed,collectionName), e);
1704         }
1705
1706         static internal Exception TooManyRestrictions(string collectionName) {
1707             return Argument(Res.GetString(Res.MDF_TooManyRestrictions,collectionName));
1708         }
1709
1710         static internal Exception UnableToBuildCollection(string collectionName) {
1711             return Argument(Res.GetString(Res.MDF_UnableToBuildCollection,collectionName));
1712         }
1713
1714         static internal Exception UndefinedCollection(string collectionName) {
1715             return Argument(Res.GetString(Res.MDF_UndefinedCollection,collectionName));
1716         }
1717
1718         static internal Exception UndefinedPopulationMechanism(string populationMechanism) {
1719             return Argument(Res.GetString(Res.MDF_UndefinedPopulationMechanism,populationMechanism));
1720         }
1721
1722         static internal Exception UnsupportedVersion(string collectionName) {
1723             return Argument(Res.GetString(Res.MDF_UnsupportedVersion,collectionName));
1724         }
1725
1726
1727         //
1728         // : CommandBuilder
1729         //
1730
1731         static internal InvalidOperationException InvalidDateTimeDigits(string dataTypeName) {
1732             return InvalidOperation(Res.GetString(Res.ADP_InvalidDateTimeDigits, dataTypeName));
1733         }
1734
1735         static internal Exception InvalidFormatValue() {
1736             return Argument(Res.GetString(Res.ADP_InvalidFormatValue));
1737         }
1738
1739         static internal InvalidOperationException InvalidMaximumScale(string dataTypeName) {
1740             return InvalidOperation(Res.GetString(Res.ADP_InvalidMaximumScale, dataTypeName));
1741         }
1742
1743         static internal Exception LiteralValueIsInvalid(string dataTypeName){
1744             return Argument(Res.GetString(Res.ADP_LiteralValueIsInvalid,dataTypeName));
1745         }
1746
1747         static internal Exception EvenLengthLiteralValue(string argumentName) {
1748             return Argument(Res.GetString(Res.ADP_EvenLengthLiteralValue), argumentName );
1749         }
1750
1751         static internal Exception HexDigitLiteralValue(string argumentName) {
1752             return Argument(Res.GetString(Res.ADP_HexDigitLiteralValue), argumentName );
1753         }
1754
1755         static internal InvalidOperationException QuotePrefixNotSet(string method) {
1756             return InvalidOperation(Res.GetString(Res.ADP_QuotePrefixNotSet, method));
1757         }
1758
1759         static internal InvalidOperationException UnableToCreateBooleanLiteral() {
1760             return ADP.InvalidOperation(Res.GetString(Res.ADP_UnableToCreateBooleanLiteral));
1761         }
1762
1763         static internal Exception UnsupportedNativeDataTypeOleDb(string dataTypeName) {
1764             return Argument(Res.GetString(Res.ADP_UnsupportedNativeDataTypeOleDb, dataTypeName));
1765         }
1766
1767         // Sql Result Set and other generic message
1768         static internal Exception InvalidArgumentValue(string methodName) {
1769             return Argument(Res.GetString(Res.ADP_InvalidArgumentValue, methodName));
1770         }
1771
1772         // global constant strings
1773         internal const string Append = "Append";
1774         internal const string BeginExecuteNonQuery = "BeginExecuteNonQuery";
1775         internal const string BeginExecuteReader = "BeginExecuteReader";
1776         internal const string BeginTransaction = "BeginTransaction";
1777         internal const string BeginExecuteXmlReader = "BeginExecuteXmlReader";
1778         internal const string ChangeDatabase = "ChangeDatabase";
1779         internal const string Cancel = "Cancel";
1780         internal const string Clone = "Clone";
1781         internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_";
1782         internal const string CommitTransaction = "CommitTransaction";
1783         internal const string CommandTimeout = "CommandTimeout";
1784         internal const string ConnectionString = "ConnectionString";
1785         internal const string DataSetColumn = "DataSetColumn";
1786         internal const string DataSetTable = "DataSetTable";
1787         internal const string Delete = "Delete";
1788         internal const string DeleteCommand = "DeleteCommand";
1789         internal const string DeriveParameters = "DeriveParameters";
1790         internal const string EndExecuteNonQuery = "EndExecuteNonQuery";
1791         internal const string EndExecuteReader = "EndExecuteReader";
1792         internal const string EndExecuteXmlReader = "EndExecuteXmlReader";
1793         internal const string ExecuteReader = "ExecuteReader";
1794         internal const string ExecuteRow = "ExecuteRow";
1795         internal const string ExecuteNonQuery = "ExecuteNonQuery";
1796         internal const string ExecuteScalar = "ExecuteScalar";
1797         internal const string ExecuteSqlScalar = "ExecuteSqlScalar";
1798         internal const string ExecuteXmlReader = "ExecuteXmlReader";
1799         internal const string Fill = "Fill";
1800         internal const string FillPage = "FillPage";
1801         internal const string FillSchema = "FillSchema";
1802         internal const string GetBytes = "GetBytes";
1803         internal const string GetChars = "GetChars";
1804         internal const string GetOleDbSchemaTable = "GetOleDbSchemaTable";
1805         internal const string GetProperties = "GetProperties";
1806         internal const string GetSchema = "GetSchema";
1807         internal const string GetSchemaTable = "GetSchemaTable";
1808         internal const string GetServerTransactionLevel = "GetServerTransactionLevel";
1809         internal const string Insert = "Insert";
1810         internal const string Open = "Open";
1811         internal const string Parameter = "Parameter";
1812         internal const string ParameterBuffer = "buffer";
1813         internal const string ParameterCount = "count";
1814         internal const string ParameterDestinationType = "destinationType";
1815         internal const string ParameterIndex = "index";
1816         internal const string ParameterName = "ParameterName";
1817         internal const string ParameterOffset = "offset";
1818         internal const string ParameterSetPosition = "set_Position";
1819         internal const string ParameterService = "Service";
1820         internal const string ParameterTimeout = "Timeout";
1821         internal const string ParameterUserData = "UserData";
1822         internal const string Prepare = "Prepare";
1823         internal const string QuoteIdentifier = "QuoteIdentifier";
1824         internal const string Read = "Read";
1825         internal const string ReadAsync = "ReadAsync";
1826         internal const string Remove = "Remove";
1827         internal const string RollbackTransaction = "RollbackTransaction";
1828         internal const string SaveTransaction = "SaveTransaction";
1829         internal const string SetProperties = "SetProperties";
1830         internal const string SourceColumn = "SourceColumn";
1831         internal const string SourceVersion = "SourceVersion";
1832         internal const string SourceTable = "SourceTable";
1833         internal const string UnquoteIdentifier = "UnquoteIdentifier";
1834         internal const string Update = "Update";
1835         internal const string UpdateCommand = "UpdateCommand";
1836         internal const string UpdateRows = "UpdateRows";
1837
1838         internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
1839         internal const int DecimalMaxPrecision = 29;
1840         internal const int DecimalMaxPrecision28 = 28;  // there are some cases in Odbc where we need that ...
1841         internal const int DefaultCommandTimeout = 30;
1842         internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
1843         internal const float FailoverTimeoutStep = 0.08F;    // fraction of timeout to use for fast failover connections
1844         internal const float FailoverTimeoutStepForTnir = 0.125F; // Fraction of timeout to use in case of Transparent Network IP resolution.
1845         internal const int MinimumTimeoutForTnirMs = 500; // The first login attempt in  Transparent network IP Resolution 
1846
1847         // security issue, don't rely upon static public readonly values - AS/URT 109635
1848         static internal readonly String StrEmpty = ""; // String.Empty
1849
1850         static internal readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
1851         static internal readonly int PtrSize = IntPtr.Size;
1852         static internal readonly IntPtr InvalidPtr = new IntPtr(-1); // use for INVALID_HANDLE
1853         static internal readonly IntPtr RecordsUnaffected = new IntPtr(-1);
1854
1855         static internal readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
1856
1857         internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
1858
1859         static internal bool CompareInsensitiveInvariant(string strvalue, string strconst) {
1860             return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase));
1861         }
1862
1863         static internal Delegate FindBuilder(MulticastDelegate mcd) { // V1.2.3300
1864             if (null != mcd) {
1865                 Delegate[] d = mcd.GetInvocationList();
1866                 for (int i = 0; i < d.Length; i++) {
1867                     if (d[i].Target is DbCommandBuilder)
1868                         return d[i];
1869                 }
1870             }
1871
1872             return null;
1873         }
1874
1875         static internal readonly bool IsWindowsNT   =  (PlatformID.Win32NT == Environment.OSVersion.Platform);
1876         static internal readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
1877
1878         static internal SysTx.Transaction GetCurrentTransaction() {
1879             SysTx.Transaction transaction = SysTx.Transaction.Current;
1880             return transaction;
1881         }
1882
1883         static internal void SetCurrentTransaction(SysTx.Transaction transaction)
1884         {
1885             SysTx.Transaction.Current = transaction;
1886         }
1887
1888         static internal SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction){
1889             SysTx.IDtcTransaction oleTxTransaction = null;
1890
1891             if (null != transaction) {
1892                 oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction);
1893             }
1894             return oleTxTransaction;
1895         }
1896
1897         [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
1898         static internal bool IsSysTxEqualSysEsTransaction() {
1899 #if MOBILE
1900             return false;
1901 #else
1902             // This Method won't JIT inproc (ES isn't available), so we code it
1903             // separately and call it behind an if statement.
1904             bool result = (!SysES.ContextUtil.IsInTransaction && null == SysTx.Transaction.Current)
1905                        || (SysES.ContextUtil.IsInTransaction  && SysTx.Transaction.Current == (SysTx.Transaction)SysES.ContextUtil.SystemTransaction);
1906             return result;
1907 #endif
1908         }
1909
1910         static internal bool NeedManualEnlistment() {
1911 #if !MOBILE && !MONO_PARTIAL_DATA_IMPORT
1912             // We need to force a manual enlistment of transactions for ODBC and
1913             // OLEDB whenever the current SysTx transaction != the SysTx transaction
1914             // on the EnterpriseServices ContextUtil, or when ES.ContextUtil is
1915             // not available and there is a non-null current SysTx transaction.
1916             if (IsWindowsNT) { // we can reference SysTx just not use it on Win9X, we can't ever reference SysES on Win9X
1917                 bool isEnterpriseServicesOK = !InOutOfProcHelper.InProc;
1918                 if ((isEnterpriseServicesOK && !IsSysTxEqualSysEsTransaction())
1919                  || (!isEnterpriseServicesOK && null != SysTx.Transaction.Current)) {
1920                     return true;
1921                 }
1922             }
1923 #endif
1924             return false;
1925         }
1926
1927         static internal void TimerCurrent(out long ticks) {
1928             ticks = DateTime.UtcNow.ToFileTimeUtc();
1929         }
1930
1931         static internal long TimerCurrent() {
1932             return DateTime.UtcNow.ToFileTimeUtc();
1933         }
1934
1935         static internal long TimerFromSeconds(int seconds) {
1936             long result = checked((long)seconds * TimeSpan.TicksPerSecond);
1937             return result;
1938         }
1939
1940         static internal long TimerFromMilliseconds(long milliseconds) {
1941             long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
1942             return result;
1943         }
1944
1945         static internal bool TimerHasExpired(long timerExpire) {
1946             bool result = TimerCurrent() > timerExpire;
1947             return result;
1948         }
1949
1950         static internal long TimerRemaining(long timerExpire) {
1951             long timerNow       = TimerCurrent();
1952             long result         = checked(timerExpire - timerNow);
1953             return result;
1954         }
1955
1956         static internal long TimerRemainingMilliseconds(long timerExpire) {
1957             long result         = TimerToMilliseconds(TimerRemaining(timerExpire));
1958             return result;
1959         }
1960
1961         static internal long TimerRemainingSeconds(long timerExpire) {
1962             long result         = TimerToSeconds(TimerRemaining(timerExpire));
1963             return result;
1964         }
1965
1966         static internal long TimerToMilliseconds(long timerValue) {
1967             long result = timerValue / TimeSpan.TicksPerMillisecond;
1968             return result;
1969         }
1970
1971         static private long TimerToSeconds(long timerValue) {
1972             long result = timerValue / TimeSpan.TicksPerSecond;
1973             return result;
1974         }
1975
1976         [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")]
1977         static internal string MachineName() 
1978         {
1979             // Note: In Longhorn you'll be able to rename a machine without
1980             // rebooting.  Therefore, don't cache this machine name.
1981             return Environment.MachineName;
1982         }
1983
1984         static internal string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) {
1985             StringBuilder resultString = new StringBuilder();
1986             if (ADP.IsEmpty(quotePrefix) == false) {
1987                 resultString.Append(quotePrefix);
1988             }
1989
1990             // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
1991             if (ADP.IsEmpty(quoteSuffix) == false) {
1992                 resultString.Append(unQuotedString.Replace(quoteSuffix,quoteSuffix+quoteSuffix));
1993                 resultString.Append(quoteSuffix);
1994             }
1995             else {
1996                 resultString.Append(unQuotedString);
1997             }
1998
1999             return resultString.ToString();
2000         }
2001
2002         private const string hexDigits = "0123456789abcdef";
2003
2004         static internal byte[] ByteArrayFromString(string hexString, string dataTypeName) {
2005             if ((hexString.Length & 0x1) != 0) {
2006                 throw ADP.LiteralValueIsInvalid(dataTypeName);
2007             }
2008             char[]  c = hexString.ToCharArray();
2009             byte[]  b = new byte[hexString.Length / 2];
2010
2011             CultureInfo invariant = CultureInfo.InvariantCulture;
2012             for (int i = 0; i < hexString.Length; i += 2) {
2013                 int h = hexDigits.IndexOf(Char.ToLower(c[i], invariant));
2014                 int l = hexDigits.IndexOf(Char.ToLower(c[i+1], invariant));
2015
2016                 if (h < 0 || l < 0) {
2017                     throw ADP.LiteralValueIsInvalid(dataTypeName);
2018                 }
2019                 b[i/2] = (byte)((h << 4) | l);
2020             }
2021             return b;
2022         }
2023
2024         static internal void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString){
2025
2026             // note special characters list is from character escapes
2027             // in the MSDN regular expression language elements documentation
2028             // added ] since escaping it seems necessary
2029             const string specialCharacters = ".$^{[(|)*+?\\]";
2030
2031             foreach (char currentChar in unescapedString){
2032                 if (specialCharacters.IndexOf(currentChar) >= 0) {
2033                     escapedString.Append("\\");
2034                 }
2035                 escapedString.Append(currentChar);
2036             }
2037             return;
2038         }
2039
2040
2041
2042
2043         static internal string FixUpDecimalSeparator(string numericString,
2044                                                      Boolean formatLiteral,
2045                                                      string decimalSeparator,
2046                                                      char[] exponentSymbols) {
2047             String returnString;
2048             // don't replace the decimal separator if the string is in exponent format
2049             if (numericString.IndexOfAny(exponentSymbols) == -1){
2050
2051                 // if the user has set a decimal separator use it, if not use the current culture's value
2052                 if (ADP.IsEmpty(decimalSeparator) == true) {
2053                    decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
2054                 }
2055                 if (formatLiteral == true){
2056                     returnString =  numericString.Replace(".",decimalSeparator);
2057                 }
2058                 else {
2059                     returnString =  numericString.Replace(decimalSeparator,".");
2060                 }
2061             }
2062             else {
2063                 returnString = numericString;
2064             }
2065             return returnString;
2066         }
2067
2068         [FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
2069         [ResourceExposure(ResourceScope.Machine)]
2070         [ResourceConsumption(ResourceScope.Machine)]
2071         static internal string GetFullPath(string filename) { // MDAC 77686
2072             return Path.GetFullPath(filename);
2073         }
2074
2075         // 
2076         static internal string GetComputerNameDnsFullyQualified() {
2077             const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT
2078             const int ERROR_MORE_DATA = 234; // winerror.h
2079
2080             string value;
2081 #if MOBILE
2082             value = ADP.MachineName();
2083 #else
2084             if (IsPlatformNT5) {
2085                 int length = 0; // length parameter must be zero if buffer is null
2086                 // query for the required length
2087                 // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive
2088                 int getComputerNameExError = 0;
2089                 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) {
2090                     getComputerNameExError = Marshal.GetLastWin32Error();
2091                 }
2092                 if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) {
2093                     throw ADP.ComputerNameEx(getComputerNameExError);
2094                 }
2095
2096                 StringBuilder buffer = new StringBuilder(length);
2097                 length = buffer.Capacity;
2098                 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) {
2099                     throw ADP.ComputerNameEx(Marshal.GetLastWin32Error());
2100                 }
2101
2102                 // Note: In Longhorn you'll be able to rename a machine without
2103                 // rebooting.  Therefore, don't cache this machine name.
2104                 value = buffer.ToString();
2105             }
2106             else {
2107                 value = ADP.MachineName();
2108             }
2109 #endif
2110             return value;
2111         }
2112
2113
2114         // SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously
2115         [ResourceExposure(ResourceScope.Machine)]
2116         [ResourceConsumption(ResourceScope.Machine)]
2117         static internal Stream GetFileStream(string filename) {
2118 #if MONO_FEATURE_CAS
2119             (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert();
2120             try {
2121                 return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2122             }
2123             finally {
2124                 FileIOPermission.RevertAssert();
2125             }
2126 #else
2127             return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2128 #endif
2129         }
2130
2131         [ResourceExposure(ResourceScope.Machine)]
2132         [ResourceConsumption(ResourceScope.Machine)]
2133         static internal FileVersionInfo GetVersionInfo(string filename) {
2134 #if MONO_FEATURE_CAS
2135             (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); // MDAC 62038
2136             try {
2137                 return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2138             }
2139             finally {
2140                 FileIOPermission.RevertAssert();
2141             }
2142 #else
2143             return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2144 #endif
2145         }
2146
2147 #if MOBILE
2148         static internal object LocalMachineRegistryValue(string subkey, string queryvalue) {
2149             return null;
2150         }
2151 #else
2152         [ResourceExposure(ResourceScope.Machine)]
2153         [ResourceConsumption(ResourceScope.Machine)]
2154         static internal Stream GetXmlStreamFromValues(String[] values, String errorString) {
2155             if (values.Length != 1){
2156                 throw ADP.ConfigWrongNumberOfValues(errorString);
2157             }
2158             return ADP.GetXmlStream(values[0],errorString);
2159         }
2160
2161         // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
2162         // this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata
2163         // under the runtime folder.
2164         // This method returns stream to open file, so its ResourceExposure value is ResourceScope.Machine.
2165         [ResourceExposure(ResourceScope.Machine)]
2166         [ResourceConsumption(ResourceScope.Machine)]
2167         static internal Stream GetXmlStream(String value, String errorString) {
2168             Stream XmlStream;
2169             const string config = "config\\";
2170             // get location of config directory
2171             string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
2172             if (rootPath == null) {
2173                     throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2174             }
2175             StringBuilder tempstring = new StringBuilder(rootPath.Length+config.Length+value.Length);
2176             tempstring.Append(rootPath);
2177             tempstring.Append(config);
2178             tempstring.Append(value);
2179             String fullPath = tempstring.ToString();
2180
2181             // don't allow relative paths
2182             if (ADP.GetFullPath(fullPath) != fullPath) {
2183                 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2184             }
2185
2186             try {
2187                 XmlStream = ADP.GetFileStream(fullPath);
2188             }
2189             catch(Exception e){
2190                 // 
2191                 if (!ADP.IsCatchableExceptionType(e)) {
2192                     throw;
2193                 }
2194                 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2195             }
2196
2197             return XmlStream;
2198
2199         }
2200
2201         [ResourceExposure(ResourceScope.Machine)]
2202         [ResourceConsumption(ResourceScope.Machine)]
2203         static internal object ClassesRootRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2204             (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CLASSES_ROOT\\" + subkey)).Assert(); // MDAC 62028
2205             try {
2206                 using(RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) {
2207                     return ((null != key) ? key.GetValue(queryvalue) : null);
2208                 }
2209             }
2210             catch(SecurityException e) {
2211                 // Even though we assert permission - it's possible there are
2212                 // ACL's on registry that cause SecurityException to be thrown.
2213                 ADP.TraceExceptionWithoutRethrow(e);
2214                 return null;
2215             }
2216             finally {
2217                 RegistryPermission.RevertAssert();
2218             }
2219         }
2220
2221         [ResourceExposure(ResourceScope.Machine)]
2222         [ResourceConsumption(ResourceScope.Machine)]
2223         static internal object LocalMachineRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2224             (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028
2225             try {
2226                 using(RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) {
2227                     return ((null != key) ? key.GetValue(queryvalue) : null);
2228                 }
2229             }
2230             catch(SecurityException e) {
2231                 // Even though we assert permission - it's possible there are
2232                 // ACL's on registry that cause SecurityException to be thrown.
2233                 ADP.TraceExceptionWithoutRethrow(e);
2234                 return null;
2235             }
2236             finally {
2237                 RegistryPermission.RevertAssert();
2238             }
2239         }
2240
2241         // SxS: although this method uses registry, it does not expose anything out
2242         [ResourceExposure(ResourceScope.None)]
2243         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2244         static internal void CheckVersionMDAC(bool ifodbcelseoledb) {
2245                         // we don't have that version info on the registry implementation, so it won't work.
2246                         if (Environment.OSVersion.Platform == PlatformID.Unix)
2247                                 return;
2248             int major, minor, build;
2249             string version;
2250
2251             try {
2252                 version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer");
2253                 if (ADP.IsEmpty(version)) {
2254                     string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, ADP.StrEmpty);
2255                     FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); // MDAC 60411
2256                     major = versionInfo.FileMajorPart;
2257                     minor = versionInfo.FileMinorPart;
2258                     build = versionInfo.FileBuildPart;
2259                     version = versionInfo.FileVersion;
2260                 }
2261                 else {
2262                     string[] parts = version.Split('.');
2263                     major = Int32.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture);
2264                     minor = Int32.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture);
2265                     build = Int32.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture);
2266                     Int32.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture);
2267                 }
2268             }
2269             catch(Exception e) {
2270                 // 
2271                 if (!ADP.IsCatchableExceptionType(e)) {
2272                     throw;
2273                 }
2274
2275                 throw System.Data.OleDb.ODB.MDACNotAvailable(e);
2276             }
2277
2278             // disallow any MDAC version before MDAC 2.6 rtm
2279             // include MDAC 2.51 that ships with Win2k
2280             if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526))))) { // MDAC 66628
2281                 if (ifodbcelseoledb) {
2282                     throw ADP.DataAdapter(Res.GetString(Res.Odbc_MDACWrongVersion, version));
2283                 }
2284                 else {
2285                     throw ADP.DataAdapter(Res.GetString(Res.OleDb_MDACWrongVersion, version));
2286                 }
2287             }
2288         }
2289 #endif
2290         // the return value is true if the string was quoted and false if it was not
2291         // this allows the caller to determine if it is an error or not for the quotedString to not be quoted
2292         static internal Boolean RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) {
2293
2294             int prefixLength;
2295             if (quotePrefix == null){
2296                 prefixLength = 0;
2297             }
2298             else {
2299                 prefixLength = quotePrefix.Length;
2300             }
2301
2302             int suffixLength;
2303             if (quoteSuffix == null){
2304                 suffixLength = 0;
2305             }
2306             else{
2307                 suffixLength = quoteSuffix.Length;
2308             }
2309
2310             if ((suffixLength + prefixLength) == 0) {
2311                 unquotedString = quotedString;
2312                 return true;
2313             }
2314
2315             if (quotedString == null){
2316                 unquotedString = quotedString;
2317                 return false;
2318             }
2319
2320             int quotedStringLength = quotedString.Length;
2321
2322             // is the source string too short to be quoted
2323             if (quotedStringLength < prefixLength + suffixLength){
2324                 unquotedString = quotedString;
2325                 return false;
2326             }
2327
2328             // is the prefix present?
2329             if ( prefixLength > 0) {
2330                 if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false){
2331                     unquotedString = quotedString;
2332                     return false;
2333                 }
2334             }
2335
2336             // is the suffix present?
2337             if ( suffixLength > 0) {
2338                 if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false){
2339                     unquotedString = quotedString;
2340                     return false;
2341                 }
2342                 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix+quoteSuffix,quoteSuffix);
2343             }
2344             else {
2345                 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - prefixLength);
2346             }
2347             return true;
2348         }
2349
2350         static internal DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) {
2351             const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
2352
2353             // equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
2354             int countAdded = 0, countDeleted = 0, countModifed = 0;
2355             DataRowCollection rowCollection = dataTable.Rows;
2356             foreach(DataRow dataRow in rowCollection) {
2357                 switch(dataRow.RowState) {
2358                 case DataRowState.Added:
2359                     countAdded++;
2360                     break;
2361                 case DataRowState.Deleted:
2362                     countDeleted++;
2363                     break;
2364                 case DataRowState.Modified:
2365                     countModifed++;
2366                     break;
2367                 default:
2368                     Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2369                     break;
2370                 }
2371             }
2372             DataRow[] dataRows = new DataRow[countAdded + countDeleted + countModifed];
2373             if(sorted) {
2374                 countModifed = countAdded + countDeleted;
2375                 countDeleted = countAdded;
2376                 countAdded = 0;
2377
2378                 foreach(DataRow dataRow in rowCollection) {
2379                     switch(dataRow.RowState) {
2380                     case DataRowState.Added:
2381                         dataRows[countAdded++] = dataRow;
2382                         break;
2383                     case DataRowState.Deleted:
2384                         dataRows[countDeleted++] = dataRow;
2385                         break;
2386                     case DataRowState.Modified:
2387                         dataRows[countModifed++] = dataRow;
2388                         break;
2389                     default:
2390                         Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2391                         break;
2392                     }
2393                 }
2394             }
2395             else {
2396                 int index = 0;
2397                 foreach(DataRow dataRow in rowCollection) {
2398                     if (0 != (dataRow.RowState & rowStates)) {
2399                         dataRows[index++] = dataRow;
2400                         if (index == dataRows.Length) {
2401                             break;
2402                         }
2403                     }
2404                 }
2405             }
2406             return dataRows;
2407         }
2408
2409         internal static int StringLength(string inputString) {
2410             return ((null != inputString) ? inputString.Length : 0);
2411         }
2412
2413         // { "a", "a", "a" } -> { "a", "a1", "a2" }
2414         // { "a", "a", "a1" } -> { "a", "a2", "a1" }
2415         // { "a", "A", "a" } -> { "a", "A1", "a2" }
2416         // { "a", "A", "a1" } -> { "a", "A2", "a1" } // MDAC 66718
2417         static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray) {
2418             Dictionary<string,int> hash = new Dictionary<string,int>(columnNameArray.Length);
2419
2420             int startIndex = columnNameArray.Length; // lowest non-unique index
2421             for (int i = columnNameArray.Length - 1; 0 <= i; --i) {
2422                 string columnName = columnNameArray[i];
2423                 if ((null != columnName) && (0 < columnName.Length)) {
2424                     columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2425                     int index;
2426                     if (hash.TryGetValue(columnName, out index)) {
2427                         startIndex = Math.Min(startIndex, index);
2428                     }
2429                     hash[columnName] = i;
2430                 }
2431                 else {
2432                     columnNameArray[i] = ADP.StrEmpty; // MDAC 66681
2433                     startIndex = i;
2434                 }
2435             }
2436             int uniqueIndex = 1;
2437             for (int i = startIndex; i < columnNameArray.Length; ++i) {
2438                 string columnName = columnNameArray[i];
2439                 if (0 == columnName.Length) { // generate a unique name
2440                     columnNameArray[i] = "Column";
2441                     uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
2442                 }
2443                 else {
2444                     columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2445                     if (i != hash[columnName]) {
2446                         GenerateUniqueName(hash, ref columnNameArray[i], i, 1); // MDAC 66718
2447                     }
2448                 }
2449             }
2450         }
2451
2452         static private int GenerateUniqueName(Dictionary<string,int> hash, ref string columnName, int index, int uniqueIndex) {
2453             for (;; ++uniqueIndex) {
2454                 string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
2455                 string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); // MDAC 66978
2456                 if (!hash.ContainsKey(lowerName)) {
2457
2458                     columnName = uniqueName;
2459                     hash.Add(lowerName, index);
2460                     break;
2461                 }
2462             }
2463             return uniqueIndex;
2464         }
2465
2466         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2467         static internal IntPtr IntPtrOffset(IntPtr pbase, Int32 offset) {
2468             if (4 == ADP.PtrSize) {
2469                 return (IntPtr) checked(pbase.ToInt32() + offset);
2470             }
2471             Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747
2472             return (IntPtr) checked(pbase.ToInt64() + offset);
2473         }
2474
2475         static internal int IntPtrToInt32(IntPtr value) {
2476             if (4 == ADP.PtrSize) {
2477                 return (int)value;
2478             }
2479             else {
2480                 long lval = (long)value;
2481                 lval = Math.Min((long)Int32.MaxValue, lval);
2482                 lval = Math.Max((long)Int32.MinValue, lval);
2483                 return (int)lval;
2484             }
2485         }
2486
2487 // 
2488         static internal int SrcCompare(string strA, string strB) { // this is null safe
2489             return ((strA == strB) ? 0 : 1);
2490         }
2491
2492         static internal int DstCompare(string strA, string strB) { // this is null safe
2493             return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
2494         }
2495
2496         static internal bool IsDirection(IDataParameter value, ParameterDirection condition) {
2497 #if DEBUG
2498             IsDirectionValid(condition);
2499 #endif
2500             return (condition == (condition & value.Direction));
2501         }
2502 #if DEBUG
2503         static private void IsDirectionValid(ParameterDirection value) {
2504             switch (value) { // @perfnote: Enum.IsDefined
2505             case ParameterDirection.Input:
2506             case ParameterDirection.Output:
2507             case ParameterDirection.InputOutput:
2508             case ParameterDirection.ReturnValue:
2509                 break;
2510             default:
2511                 throw ADP.InvalidParameterDirection(value);
2512             }
2513         }
2514 #endif
2515
2516         static internal bool IsEmpty(string str) {
2517             return ((null == str) || (0 == str.Length));
2518         }
2519
2520         static internal bool IsEmptyArray(string[] array) {
2521             return ((null == array) || (0 == array.Length));
2522         }
2523
2524         static internal bool IsNull(object value) {
2525             if ((null == value) || (DBNull.Value == value)) {
2526                 return true;
2527             }
2528             INullable nullable = (value as INullable);
2529             return ((null != nullable) && nullable.IsNull);
2530         }
2531
2532         static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) {
2533             if ((value == null) || (value == DBNull.Value)) {
2534                 isNull = true;
2535                 isSqlType = false;
2536             }
2537             else {
2538                 INullable nullable = (value as INullable);
2539                 if (nullable != null) {
2540                     isNull = nullable.IsNull;
2541                     isSqlType = DataStorage.IsSqlType(value.GetType());
2542                 }
2543                 else {
2544                     isNull = false;
2545                     isSqlType = false;
2546                 }
2547             }
2548         }
2549
2550         private static Version _systemDataVersion;
2551         static internal Version GetAssemblyVersion() {
2552             // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
2553             if (_systemDataVersion == null) {
2554                 _systemDataVersion = new Version(ThisAssembly.InformationalVersion);
2555             }
2556
2557             return _systemDataVersion;
2558         }
2559
2560         static internal readonly string[] AzureSqlServerEndpoints = {Res.GetString(Res.AZURESQL_GenericEndpoint),
2561                                                                      Res.GetString(Res.AZURESQL_GermanEndpoint),
2562                                                                      Res.GetString(Res.AZURESQL_UsGovEndpoint),
2563                                                                      Res.GetString(Res.AZURESQL_ChinaEndpoint)};
2564
2565         // This method assumes dataSource parameter is in TCP connection string format.
2566         static internal bool IsAzureSqlServerEndpoint(string dataSource)
2567         {
2568             // remove server port
2569             int i = dataSource.LastIndexOf(',');
2570             if (i >= 0)
2571             {
2572                 dataSource = dataSource.Substring(0, i);
2573             }
2574
2575             // check for the instance name
2576             i = dataSource.LastIndexOf('\\');
2577             if (i >= 0)
2578             {
2579                 dataSource = dataSource.Substring(0, i);
2580             }
2581
2582             // trim redundant whitespaces
2583             dataSource = dataSource.Trim();
2584
2585             // check if servername end with any azure endpoints
2586             for (i = 0; i < AzureSqlServerEndpoints.Length; i++)
2587             {
2588                 if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))
2589                 {
2590                     return true;
2591                 }
2592             }
2593
2594             return false;
2595         }
2596     }
2597 }