Disable use of Win32 specific p/invokes when built for the mobile profile
[mono.git] / mcs / class / referencesource / System.Data / System / Data / Common / AdapterUtil.cs
1 //------------------------------------------------------------------------------
2 // <copyright file="AdapterUtil.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>
5 // <owner current="true" primary="true">Microsoft</owner>
6 // <owner current="true" primary="false">Microsoft</owner>
7 //------------------------------------------------------------------------------
8
9 namespace System.Data.Common {
10
11     using Microsoft.Win32;
12     using System;
13     using System.Collections;
14     using System.Collections.Generic;
15     using System.ComponentModel;
16     using System.Configuration;
17     using System.Data;
18     using System.Data.ProviderBase;
19 #if !MOBILE
20     using System.Data.Odbc;
21     using System.Data.OleDb;
22 #endif
23     using System.Data.Sql;
24     using System.Data.SqlTypes;
25     using System.Diagnostics;
26     using System.Globalization;
27     using System.IO;
28     using System.Reflection;
29     using System.Runtime.ConstrainedExecution;
30     using System.Runtime.InteropServices;
31     using System.Runtime.Serialization;
32     using System.Security;
33     using System.Security.Permissions;
34     using System.Data.SqlClient;
35     using System.Text;
36     using System.Threading;
37     using System.Threading.Tasks;
38     using System.Xml;
39     using SysTx = System.Transactions;
40 #if !MOBILE
41     using SysES = System.EnterpriseServices;
42 #endif
43     using System.Runtime.Versioning;
44
45     using Microsoft.SqlServer.Server;
46
47     internal static class ADP {
48         
49         // The class ADP defines the exceptions that are specific to the Adapters.f
50         // The class contains functions that take the proper informational variables and then construct
51         // the appropriate exception with an error string obtained from the resource Framework.txt.
52         // The exception is then returned to the caller, so that the caller may then throw from its
53         // location so that the catcher of the exception will have the appropriate call stack.
54         // This class is used so that there will be compile time checking of error messages.
55         // The resource Framework.txt will ensure proper string text based on the appropriate
56         // locale.
57
58         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 
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
1856         // security issue, don't rely upon static public readonly values - AS/URT 109635
1857         static internal readonly String StrEmpty = ""; // String.Empty
1858
1859         static internal readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
1860         static internal readonly int PtrSize = IntPtr.Size;
1861         static internal readonly IntPtr InvalidPtr = new IntPtr(-1); // use for INVALID_HANDLE
1862         static internal readonly IntPtr RecordsUnaffected = new IntPtr(-1);
1863
1864         static internal readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
1865
1866         internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
1867
1868         static internal bool CompareInsensitiveInvariant(string strvalue, string strconst) {
1869             return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase));
1870         }
1871
1872         static internal Delegate FindBuilder(MulticastDelegate mcd) { // V1.2.3300
1873             if (null != mcd) {
1874                 Delegate[] d = mcd.GetInvocationList();
1875                 for (int i = 0; i < d.Length; i++) {
1876                     if (d[i].Target is DbCommandBuilder)
1877                         return d[i];
1878                 }
1879             }
1880
1881             return null;
1882         }
1883
1884         static internal readonly bool IsWindowsNT   =  (PlatformID.Win32NT == Environment.OSVersion.Platform);
1885         static internal readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
1886
1887         static internal SysTx.Transaction GetCurrentTransaction() {
1888             SysTx.Transaction transaction = SysTx.Transaction.Current;
1889             return transaction;
1890         }
1891
1892         static internal void SetCurrentTransaction(SysTx.Transaction transaction)
1893         {
1894             SysTx.Transaction.Current = transaction;
1895         }
1896
1897         static internal SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction){
1898             SysTx.IDtcTransaction oleTxTransaction = null;
1899
1900             if (null != transaction) {
1901                 oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction);
1902             }
1903             return oleTxTransaction;
1904         }
1905
1906         [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
1907         static internal bool IsSysTxEqualSysEsTransaction() {
1908 #if MOBILE
1909             return false;
1910 #else
1911             // This Method won't JIT inproc (ES isn't available), so we code it
1912             // separately and call it behind an if statement.
1913             bool result = (!SysES.ContextUtil.IsInTransaction && null == SysTx.Transaction.Current)
1914                        || (SysES.ContextUtil.IsInTransaction  && SysTx.Transaction.Current == (SysTx.Transaction)SysES.ContextUtil.SystemTransaction);
1915             return result;
1916 #endif
1917         }
1918
1919         static internal bool NeedManualEnlistment() {
1920 #if !MOBILE && !MONO_PARTIAL_DATA_IMPORT
1921             // We need to force a manual enlistment of transactions for ODBC and
1922             // OLEDB whenever the current SysTx transaction != the SysTx transaction
1923             // on the EnterpriseServices ContextUtil, or when ES.ContextUtil is
1924             // not available and there is a non-null current SysTx transaction.
1925             if (IsWindowsNT) { // we can reference SysTx just not use it on Win9X, we can't ever reference SysES on Win9X
1926                 bool isEnterpriseServicesOK = !InOutOfProcHelper.InProc;
1927                 if ((isEnterpriseServicesOK && !IsSysTxEqualSysEsTransaction())
1928                  || (!isEnterpriseServicesOK && null != SysTx.Transaction.Current)) {
1929                     return true;
1930                 }
1931             }
1932 #endif
1933             return false;
1934         }
1935
1936         static internal void TimerCurrent(out long ticks) {
1937             ticks = DateTime.UtcNow.ToFileTimeUtc();
1938         }
1939
1940         static internal long TimerCurrent() {
1941             return DateTime.UtcNow.ToFileTimeUtc();
1942         }
1943
1944         static internal long TimerFromSeconds(int seconds) {
1945             long result = checked((long)seconds * TimeSpan.TicksPerSecond);
1946             return result;
1947         }
1948
1949         static internal long TimerFromMilliseconds(long milliseconds) {
1950             long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
1951             return result;
1952         }
1953
1954         static internal bool TimerHasExpired(long timerExpire) {
1955             bool result = TimerCurrent() > timerExpire;
1956             return result;
1957         }
1958
1959         static internal long TimerRemaining(long timerExpire) {
1960             long timerNow       = TimerCurrent();
1961             long result         = checked(timerExpire - timerNow);
1962             return result;
1963         }
1964
1965         static internal long TimerRemainingMilliseconds(long timerExpire) {
1966             long result         = TimerToMilliseconds(TimerRemaining(timerExpire));
1967             return result;
1968         }
1969
1970         static internal long TimerRemainingSeconds(long timerExpire) {
1971             long result         = TimerToSeconds(TimerRemaining(timerExpire));
1972             return result;
1973         }
1974
1975         static internal long TimerToMilliseconds(long timerValue) {
1976             long result = timerValue / TimeSpan.TicksPerMillisecond;
1977             return result;
1978         }
1979
1980         static private long TimerToSeconds(long timerValue) {
1981             long result = timerValue / TimeSpan.TicksPerSecond;
1982             return result;
1983         }
1984
1985         [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")]
1986         static internal string MachineName() 
1987         {
1988             // Note: In Longhorn you'll be able to rename a machine without
1989             // rebooting.  Therefore, don't cache this machine name.
1990             return Environment.MachineName;
1991         }
1992
1993         static internal string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) {
1994             StringBuilder resultString = new StringBuilder();
1995             if (ADP.IsEmpty(quotePrefix) == false) {
1996                 resultString.Append(quotePrefix);
1997             }
1998
1999             // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
2000             if (ADP.IsEmpty(quoteSuffix) == false) {
2001                 resultString.Append(unQuotedString.Replace(quoteSuffix,quoteSuffix+quoteSuffix));
2002                 resultString.Append(quoteSuffix);
2003             }
2004             else {
2005                 resultString.Append(unQuotedString);
2006             }
2007
2008             return resultString.ToString();
2009         }
2010
2011         private static readonly string hexDigits = "0123456789abcdef";
2012
2013         static internal byte[] ByteArrayFromString(string hexString, string dataTypeName) {
2014             if ((hexString.Length & 0x1) != 0) {
2015                 throw ADP.LiteralValueIsInvalid(dataTypeName);
2016             }
2017             char[]  c = hexString.ToCharArray();
2018             byte[]  b = new byte[hexString.Length / 2];
2019
2020             CultureInfo invariant = CultureInfo.InvariantCulture;
2021             for (int i = 0; i < hexString.Length; i += 2) {
2022                 int h = hexDigits.IndexOf(Char.ToLower(c[i], invariant));
2023                 int l = hexDigits.IndexOf(Char.ToLower(c[i+1], invariant));
2024
2025                 if (h < 0 || l < 0) {
2026                     throw ADP.LiteralValueIsInvalid(dataTypeName);
2027                 }
2028                 b[i/2] = (byte)((h << 4) | l);
2029             }
2030             return b;
2031         }
2032
2033         static internal void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString){
2034
2035             // note special characters list is from character escapes
2036             // in the MSDN regular expression language elements documentation
2037             // added ] since escaping it seems necessary
2038             const string specialCharacters = ".$^{[(|)*+?\\]";
2039
2040             foreach (char currentChar in unescapedString){
2041                 if (specialCharacters.IndexOf(currentChar) >= 0) {
2042                     escapedString.Append("\\");
2043                 }
2044                 escapedString.Append(currentChar);
2045             }
2046             return;
2047         }
2048
2049
2050
2051
2052         static internal string FixUpDecimalSeparator(string numericString,
2053                                                      Boolean formatLiteral,
2054                                                      string decimalSeparator,
2055                                                      char[] exponentSymbols) {
2056             String returnString;
2057             // don't replace the decimal separator if the string is in exponent format
2058             if (numericString.IndexOfAny(exponentSymbols) == -1){
2059
2060                 // if the user has set a decimal separator use it, if not use the current culture's value
2061                 if (ADP.IsEmpty(decimalSeparator) == true) {
2062                    decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
2063                 }
2064                 if (formatLiteral == true){
2065                     returnString =  numericString.Replace(".",decimalSeparator);
2066                 }
2067                 else {
2068                     returnString =  numericString.Replace(decimalSeparator,".");
2069                 }
2070             }
2071             else {
2072                 returnString = numericString;
2073             }
2074             return returnString;
2075         }
2076
2077         [FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
2078         [ResourceExposure(ResourceScope.Machine)]
2079         [ResourceConsumption(ResourceScope.Machine)]
2080         static internal string GetFullPath(string filename) { // MDAC 77686
2081             return Path.GetFullPath(filename);
2082         }
2083
2084         // 
2085         static internal string GetComputerNameDnsFullyQualified() {
2086             const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT
2087             const int ERROR_MORE_DATA = 234; // winerror.h
2088
2089             string value;
2090 #if MOBILE
2091             value = ADP.MachineName();
2092 #else
2093             if (IsPlatformNT5) {
2094                 int length = 0; // length parameter must be zero if buffer is null
2095                 // query for the required length
2096                 // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive
2097                 int getComputerNameExError = 0;
2098                 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) {
2099                     getComputerNameExError = Marshal.GetLastWin32Error();
2100                 }
2101                 if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) {
2102                     throw ADP.ComputerNameEx(getComputerNameExError);
2103                 }
2104
2105                 StringBuilder buffer = new StringBuilder(length);
2106                 length = buffer.Capacity;
2107                 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) {
2108                     throw ADP.ComputerNameEx(Marshal.GetLastWin32Error());
2109                 }
2110
2111                 // Note: In Longhorn you'll be able to rename a machine without
2112                 // rebooting.  Therefore, don't cache this machine name.
2113                 value = buffer.ToString();
2114             }
2115             else {
2116                 value = ADP.MachineName();
2117             }
2118 #endif
2119             return value;
2120         }
2121
2122
2123         // SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously
2124         [ResourceExposure(ResourceScope.Machine)]
2125         [ResourceConsumption(ResourceScope.Machine)]
2126         static internal Stream GetFileStream(string filename) {
2127 #if !DISABLE_CAS_USE
2128             (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert();
2129             try {
2130                 return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2131             }
2132             finally {
2133                 FileIOPermission.RevertAssert();
2134             }
2135 #else
2136             return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2137 #endif
2138         }
2139
2140         [ResourceExposure(ResourceScope.Machine)]
2141         [ResourceConsumption(ResourceScope.Machine)]
2142         static internal FileVersionInfo GetVersionInfo(string filename) {
2143 #if !DISABLE_CAS_USE
2144             (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); // MDAC 62038
2145             try {
2146                 return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2147             }
2148             finally {
2149                 FileIOPermission.RevertAssert();
2150             }
2151 #else
2152             return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2153 #endif
2154         }
2155
2156 #if MOBILE
2157         static internal object LocalMachineRegistryValue(string subkey, string queryvalue) {
2158             return null;
2159         }
2160 #else
2161         [ResourceExposure(ResourceScope.Machine)]
2162         [ResourceConsumption(ResourceScope.Machine)]
2163         static internal Stream GetXmlStreamFromValues(String[] values, String errorString) {
2164             if (values.Length != 1){
2165                 throw ADP.ConfigWrongNumberOfValues(errorString);
2166             }
2167             return ADP.GetXmlStream(values[0],errorString);
2168         }
2169
2170         // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
2171         // 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
2172         // under the runtime folder.
2173         // This method returns stream to open file, so its ResourceExposure value is ResourceScope.Machine.
2174         [ResourceExposure(ResourceScope.Machine)]
2175         [ResourceConsumption(ResourceScope.Machine)]
2176         static internal Stream GetXmlStream(String value, String errorString) {
2177             Stream XmlStream;
2178             const string config = "config\\";
2179             // get location of config directory
2180             string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
2181             if (rootPath == null) {
2182                     throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2183             }
2184             StringBuilder tempstring = new StringBuilder(rootPath.Length+config.Length+value.Length);
2185             tempstring.Append(rootPath);
2186             tempstring.Append(config);
2187             tempstring.Append(value);
2188             String fullPath = tempstring.ToString();
2189
2190             // don't allow relative paths
2191             if (ADP.GetFullPath(fullPath) != fullPath) {
2192                 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2193             }
2194
2195             try {
2196                 XmlStream = ADP.GetFileStream(fullPath);
2197             }
2198             catch(Exception e){
2199                 // 
2200                 if (!ADP.IsCatchableExceptionType(e)) {
2201                     throw;
2202                 }
2203                 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2204             }
2205
2206             return XmlStream;
2207
2208         }
2209
2210         [ResourceExposure(ResourceScope.Machine)]
2211         [ResourceConsumption(ResourceScope.Machine)]
2212         static internal object ClassesRootRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2213             (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CLASSES_ROOT\\" + subkey)).Assert(); // MDAC 62028
2214             try {
2215                 using(RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) {
2216                     return ((null != key) ? key.GetValue(queryvalue) : null);
2217                 }
2218             }
2219             catch(SecurityException e) {
2220                 // Even though we assert permission - it's possible there are
2221                 // ACL's on registry that cause SecurityException to be thrown.
2222                 ADP.TraceExceptionWithoutRethrow(e);
2223                 return null;
2224             }
2225             finally {
2226                 RegistryPermission.RevertAssert();
2227             }
2228         }
2229
2230         [ResourceExposure(ResourceScope.Machine)]
2231         [ResourceConsumption(ResourceScope.Machine)]
2232         static internal object LocalMachineRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2233             (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028
2234             try {
2235                 using(RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) {
2236                     return ((null != key) ? key.GetValue(queryvalue) : null);
2237                 }
2238             }
2239             catch(SecurityException e) {
2240                 // Even though we assert permission - it's possible there are
2241                 // ACL's on registry that cause SecurityException to be thrown.
2242                 ADP.TraceExceptionWithoutRethrow(e);
2243                 return null;
2244             }
2245             finally {
2246                 RegistryPermission.RevertAssert();
2247             }
2248         }
2249
2250         // SxS: although this method uses registry, it does not expose anything out
2251         [ResourceExposure(ResourceScope.None)]
2252         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2253         static internal void CheckVersionMDAC(bool ifodbcelseoledb) {
2254                         // we don't have that version info on the registry implementation, so it won't work.
2255                         if (Environment.OSVersion.Platform == PlatformID.Unix)
2256                                 return;
2257             int major, minor, build;
2258             string version;
2259
2260             try {
2261                 version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer");
2262                 if (ADP.IsEmpty(version)) {
2263                     string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, ADP.StrEmpty);
2264                     FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); // MDAC 60411
2265                     major = versionInfo.FileMajorPart;
2266                     minor = versionInfo.FileMinorPart;
2267                     build = versionInfo.FileBuildPart;
2268                     version = versionInfo.FileVersion;
2269                 }
2270                 else {
2271                     string[] parts = version.Split('.');
2272                     major = Int32.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture);
2273                     minor = Int32.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture);
2274                     build = Int32.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture);
2275                     Int32.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture);
2276                 }
2277             }
2278             catch(Exception e) {
2279                 // 
2280                 if (!ADP.IsCatchableExceptionType(e)) {
2281                     throw;
2282                 }
2283
2284                 throw System.Data.OleDb.ODB.MDACNotAvailable(e);
2285             }
2286
2287             // disallow any MDAC version before MDAC 2.6 rtm
2288             // include MDAC 2.51 that ships with Win2k
2289             if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526))))) { // MDAC 66628
2290                 if (ifodbcelseoledb) {
2291                     throw ADP.DataAdapter(Res.GetString(Res.Odbc_MDACWrongVersion, version));
2292                 }
2293                 else {
2294                     throw ADP.DataAdapter(Res.GetString(Res.OleDb_MDACWrongVersion, version));
2295                 }
2296             }
2297         }
2298 #endif
2299         // the return value is true if the string was quoted and false if it was not
2300         // this allows the caller to determine if it is an error or not for the quotedString to not be quoted
2301         static internal Boolean RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) {
2302
2303             int prefixLength;
2304             if (quotePrefix == null){
2305                 prefixLength = 0;
2306             }
2307             else {
2308                 prefixLength = quotePrefix.Length;
2309             }
2310
2311             int suffixLength;
2312             if (quoteSuffix == null){
2313                 suffixLength = 0;
2314             }
2315             else{
2316                 suffixLength = quoteSuffix.Length;
2317             }
2318
2319             if ((suffixLength + prefixLength) == 0) {
2320                 unquotedString = quotedString;
2321                 return true;
2322             }
2323
2324             if (quotedString == null){
2325                 unquotedString = quotedString;
2326                 return false;
2327             }
2328
2329             int quotedStringLength = quotedString.Length;
2330
2331             // is the source string too short to be quoted
2332             if (quotedStringLength < prefixLength + suffixLength){
2333                 unquotedString = quotedString;
2334                 return false;
2335             }
2336
2337             // is the prefix present?
2338             if ( prefixLength > 0) {
2339                 if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false){
2340                     unquotedString = quotedString;
2341                     return false;
2342                 }
2343             }
2344
2345             // is the suffix present?
2346             if ( suffixLength > 0) {
2347                 if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false){
2348                     unquotedString = quotedString;
2349                     return false;
2350                 }
2351                 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix+quoteSuffix,quoteSuffix);
2352             }
2353             else {
2354                 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - prefixLength);
2355             }
2356             return true;
2357         }
2358
2359         static internal DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) {
2360             const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
2361
2362             // equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
2363             int countAdded = 0, countDeleted = 0, countModifed = 0;
2364             DataRowCollection rowCollection = dataTable.Rows;
2365             foreach(DataRow dataRow in rowCollection) {
2366                 switch(dataRow.RowState) {
2367                 case DataRowState.Added:
2368                     countAdded++;
2369                     break;
2370                 case DataRowState.Deleted:
2371                     countDeleted++;
2372                     break;
2373                 case DataRowState.Modified:
2374                     countModifed++;
2375                     break;
2376                 default:
2377                     Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2378                     break;
2379                 }
2380             }
2381             DataRow[] dataRows = new DataRow[countAdded + countDeleted + countModifed];
2382             if(sorted) {
2383                 countModifed = countAdded + countDeleted;
2384                 countDeleted = countAdded;
2385                 countAdded = 0;
2386
2387                 foreach(DataRow dataRow in rowCollection) {
2388                     switch(dataRow.RowState) {
2389                     case DataRowState.Added:
2390                         dataRows[countAdded++] = dataRow;
2391                         break;
2392                     case DataRowState.Deleted:
2393                         dataRows[countDeleted++] = dataRow;
2394                         break;
2395                     case DataRowState.Modified:
2396                         dataRows[countModifed++] = dataRow;
2397                         break;
2398                     default:
2399                         Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2400                         break;
2401                     }
2402                 }
2403             }
2404             else {
2405                 int index = 0;
2406                 foreach(DataRow dataRow in rowCollection) {
2407                     if (0 != (dataRow.RowState & rowStates)) {
2408                         dataRows[index++] = dataRow;
2409                         if (index == dataRows.Length) {
2410                             break;
2411                         }
2412                     }
2413                 }
2414             }
2415             return dataRows;
2416         }
2417
2418         internal static int StringLength(string inputString) {
2419             return ((null != inputString) ? inputString.Length : 0);
2420         }
2421
2422         // { "a", "a", "a" } -> { "a", "a1", "a2" }
2423         // { "a", "a", "a1" } -> { "a", "a2", "a1" }
2424         // { "a", "A", "a" } -> { "a", "A1", "a2" }
2425         // { "a", "A", "a1" } -> { "a", "A2", "a1" } // MDAC 66718
2426         static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray) {
2427             Dictionary<string,int> hash = new Dictionary<string,int>(columnNameArray.Length);
2428
2429             int startIndex = columnNameArray.Length; // lowest non-unique index
2430             for (int i = columnNameArray.Length - 1; 0 <= i; --i) {
2431                 string columnName = columnNameArray[i];
2432                 if ((null != columnName) && (0 < columnName.Length)) {
2433                     columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2434                     int index;
2435                     if (hash.TryGetValue(columnName, out index)) {
2436                         startIndex = Math.Min(startIndex, index);
2437                     }
2438                     hash[columnName] = i;
2439                 }
2440                 else {
2441                     columnNameArray[i] = ADP.StrEmpty; // MDAC 66681
2442                     startIndex = i;
2443                 }
2444             }
2445             int uniqueIndex = 1;
2446             for (int i = startIndex; i < columnNameArray.Length; ++i) {
2447                 string columnName = columnNameArray[i];
2448                 if (0 == columnName.Length) { // generate a unique name
2449                     columnNameArray[i] = "Column";
2450                     uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
2451                 }
2452                 else {
2453                     columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2454                     if (i != hash[columnName]) {
2455                         GenerateUniqueName(hash, ref columnNameArray[i], i, 1); // MDAC 66718
2456                     }
2457                 }
2458             }
2459         }
2460
2461         static private int GenerateUniqueName(Dictionary<string,int> hash, ref string columnName, int index, int uniqueIndex) {
2462             for (;; ++uniqueIndex) {
2463                 string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
2464                 string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); // MDAC 66978
2465                 if (!hash.ContainsKey(lowerName)) {
2466
2467                     columnName = uniqueName;
2468                     hash.Add(lowerName, index);
2469                     break;
2470                 }
2471             }
2472             return uniqueIndex;
2473         }
2474
2475         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2476         static internal IntPtr IntPtrOffset(IntPtr pbase, Int32 offset) {
2477             if (4 == ADP.PtrSize) {
2478                 return (IntPtr) checked(pbase.ToInt32() + offset);
2479             }
2480             Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747
2481             return (IntPtr) checked(pbase.ToInt64() + offset);
2482         }
2483
2484         static internal int IntPtrToInt32(IntPtr value) {
2485             if (4 == ADP.PtrSize) {
2486                 return (int)value;
2487             }
2488             else {
2489                 long lval = (long)value;
2490                 lval = Math.Min((long)Int32.MaxValue, lval);
2491                 lval = Math.Max((long)Int32.MinValue, lval);
2492                 return (int)lval;
2493             }
2494         }
2495
2496 // 
2497         static internal int SrcCompare(string strA, string strB) { // this is null safe
2498             return ((strA == strB) ? 0 : 1);
2499         }
2500
2501         static internal int DstCompare(string strA, string strB) { // this is null safe
2502             return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
2503         }
2504
2505         static internal bool IsDirection(IDataParameter value, ParameterDirection condition) {
2506 #if DEBUG
2507             IsDirectionValid(condition);
2508 #endif
2509             return (condition == (condition & value.Direction));
2510         }
2511 #if DEBUG
2512         static private void IsDirectionValid(ParameterDirection value) {
2513             switch (value) { // @perfnote: Enum.IsDefined
2514             case ParameterDirection.Input:
2515             case ParameterDirection.Output:
2516             case ParameterDirection.InputOutput:
2517             case ParameterDirection.ReturnValue:
2518                 break;
2519             default:
2520                 throw ADP.InvalidParameterDirection(value);
2521             }
2522         }
2523 #endif
2524
2525         static internal bool IsEmpty(string str) {
2526             return ((null == str) || (0 == str.Length));
2527         }
2528
2529         static internal bool IsEmptyArray(string[] array) {
2530             return ((null == array) || (0 == array.Length));
2531         }
2532
2533         static internal bool IsNull(object value) {
2534             if ((null == value) || (DBNull.Value == value)) {
2535                 return true;
2536             }
2537             INullable nullable = (value as INullable);
2538             return ((null != nullable) && nullable.IsNull);
2539         }
2540
2541         static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) {
2542             if ((value == null) || (value == DBNull.Value)) {
2543                 isNull = true;
2544                 isSqlType = false;
2545             }
2546             else {
2547                 INullable nullable = (value as INullable);
2548                 if (nullable != null) {
2549                     isNull = nullable.IsNull;
2550                     isSqlType = DataStorage.IsSqlType(value.GetType());
2551                 }
2552                 else {
2553                     isNull = false;
2554                     isSqlType = false;
2555                 }
2556             }
2557         }
2558
2559         private static Version _systemDataVersion;
2560         static internal Version GetAssemblyVersion() {
2561             // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
2562             if (_systemDataVersion == null) {
2563                 _systemDataVersion = new Version(ThisAssembly.InformationalVersion);
2564             }
2565
2566             return _systemDataVersion;
2567         }
2568     }
2569 }