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