1 //------------------------------------------------------------------------------
2 // <copyright file="AdapterUtil.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // <owner current="true" primary="true">Microsoft</owner>
6 // <owner current="true" primary="false">Microsoft</owner>
7 //------------------------------------------------------------------------------
9 namespace System.Data.Common {
11 using Microsoft.Win32;
13 using System.Collections;
14 using System.Collections.Generic;
15 using System.ComponentModel;
16 using System.Configuration;
18 using System.Data.ProviderBase;
20 using System.Data.Odbc;
21 using System.Data.OleDb;
23 using System.Data.Sql;
24 using System.Data.SqlTypes;
25 using System.Diagnostics;
26 using System.Globalization;
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;
36 using System.Threading;
37 using System.Threading.Tasks;
39 using SysTx = System.Transactions;
41 using SysES = System.EnterpriseServices;
43 using System.Runtime.Versioning;
45 using Microsoft.SqlServer.Server;
47 internal static class ADP {
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
58 public const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
60 static internal Task<T> CreatedTaskWithException<T>(Exception ex) {
61 TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
62 completion.SetException(ex);
63 return completion.Task;
66 static internal Task<T> CreatedTaskWithCancellation<T>() {
67 TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
68 completion.SetCanceled();
69 return completion.Task;
72 static internal Exception ExceptionWithStackTrace(Exception e)
77 catch (Exception caught) {
82 static internal Task<bool> s_trueTask = Task.FromResult<bool>(true);
84 static internal Task<bool> s_falseTask = Task.FromResult<bool>(false);
87 static internal Task<bool> TrueTask => s_trueTask;
88 static internal Task<bool> FalseTask => s_falseTask;
91 [BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
92 static private void TraceException(
94 [BidArgumentType(typeof(String))] Exception e) {
95 Debug.Assert(null != e, "TraceException: null Exception");
97 Bid.Trace(trace, e.ToString()); // will include callstack if permission is available
101 static internal void TraceExceptionAsReturnValue(Exception e) {
102 TraceException("<comm.ADP.TraceException|ERR|THROW> '%ls'\n", e);
104 static internal void TraceExceptionForCapture(Exception e) {
105 Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
106 TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
108 static internal void TraceExceptionWithoutRethrow(Exception e) {
109 Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
110 TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
116 static internal ArgumentException Argument(string error) {
117 ArgumentException e = new ArgumentException(error);
118 TraceExceptionAsReturnValue(e);
121 static internal ArgumentException Argument(string error, Exception inner) {
122 ArgumentException e = new ArgumentException(error, inner);
123 TraceExceptionAsReturnValue(e);
126 static internal ArgumentException Argument(string error, string parameter) {
127 ArgumentException e = new ArgumentException(error, parameter);
128 TraceExceptionAsReturnValue(e);
131 static internal ArgumentException Argument(string error, string parameter, Exception inner) {
132 ArgumentException e = new ArgumentException(error, parameter, inner);
133 TraceExceptionAsReturnValue(e);
136 static internal ArgumentNullException ArgumentNull(string parameter) {
137 ArgumentNullException e = new ArgumentNullException(parameter);
138 TraceExceptionAsReturnValue(e);
141 static internal ArgumentNullException ArgumentNull(string parameter, string error) {
142 ArgumentNullException e = new ArgumentNullException(parameter, error);
143 TraceExceptionAsReturnValue(e);
146 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) {
147 ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
148 TraceExceptionAsReturnValue(e);
151 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) {
152 ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
153 TraceExceptionAsReturnValue(e);
156 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) {
157 ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message);
158 TraceExceptionAsReturnValue(e);
162 static internal ConfigurationException Configuration(string message) {
163 ConfigurationException e = new ConfigurationErrorsException(message);
164 TraceExceptionAsReturnValue(e);
167 static internal ConfigurationException Configuration(string message, XmlNode node) {
168 ConfigurationException e = new ConfigurationErrorsException(message, node);
169 TraceExceptionAsReturnValue(e);
173 static internal DataException Data(string message) {
174 DataException e = new DataException(message);
175 TraceExceptionAsReturnValue(e);
178 static internal IndexOutOfRangeException IndexOutOfRange(int value) {
179 IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
180 TraceExceptionAsReturnValue(e);
183 static internal IndexOutOfRangeException IndexOutOfRange(string error) {
184 IndexOutOfRangeException e = new IndexOutOfRangeException(error);
185 TraceExceptionAsReturnValue(e);
188 static internal IndexOutOfRangeException IndexOutOfRange() {
189 IndexOutOfRangeException e = new IndexOutOfRangeException();
190 TraceExceptionAsReturnValue(e);
193 static internal InvalidCastException InvalidCast(string error) {
194 return InvalidCast(error, null);
196 static internal InvalidCastException InvalidCast(string error, Exception inner) {
197 InvalidCastException e = new InvalidCastException(error, inner);
198 TraceExceptionAsReturnValue(e);
201 static internal InvalidOperationException InvalidOperation(string error) {
202 InvalidOperationException e = new InvalidOperationException(error);
203 TraceExceptionAsReturnValue(e);
206 static internal TimeoutException TimeoutException(string error) {
207 TimeoutException e = new TimeoutException(error);
208 TraceExceptionAsReturnValue(e);
211 static internal InvalidOperationException InvalidOperation(string error, Exception inner)
213 InvalidOperationException e = new InvalidOperationException(error, inner);
214 TraceExceptionAsReturnValue(e);
217 static internal NotImplementedException NotImplemented(string error) {
218 NotImplementedException e = new NotImplementedException(error);
219 TraceExceptionAsReturnValue(e);
222 static internal NotSupportedException NotSupported() {
223 NotSupportedException e = new NotSupportedException();
224 TraceExceptionAsReturnValue(e);
227 static internal NotSupportedException NotSupported(string error) {
228 NotSupportedException e = new NotSupportedException(error);
229 TraceExceptionAsReturnValue(e);
232 static internal OverflowException Overflow(string error) {
233 return Overflow(error, null);
235 static internal OverflowException Overflow(string error, Exception inner) {
236 OverflowException e = new OverflowException(error, inner);
237 TraceExceptionAsReturnValue(e);
240 static internal PlatformNotSupportedException PropertyNotSupported(string property) {
241 PlatformNotSupportedException e = new PlatformNotSupportedException(Res.GetString(Res.ADP_PropertyNotSupported, property));
242 TraceExceptionAsReturnValue(e);
245 static internal TypeLoadException TypeLoad(string error) {
246 TypeLoadException e = new TypeLoadException(error);
247 TraceExceptionAsReturnValue(e);
250 static internal InvalidCastException InvalidCast() {
251 InvalidCastException e = new InvalidCastException();
252 TraceExceptionAsReturnValue(e);
255 static internal IOException IO(string error) {
256 IOException e = new IOException(error);
257 TraceExceptionAsReturnValue(e);
260 static internal IOException IO(string error, Exception inner) {
261 IOException e = new IOException(error, inner);
262 TraceExceptionAsReturnValue(e);
265 static internal InvalidOperationException DataAdapter(string error) {
266 return InvalidOperation(error);
268 static internal InvalidOperationException DataAdapter(string error, Exception inner) {
269 return InvalidOperation(error, inner);
271 static private InvalidOperationException Provider(string error) {
272 return InvalidOperation(error);
274 static internal ObjectDisposedException ObjectDisposed(object instance) {
275 ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
276 TraceExceptionAsReturnValue(e);
280 static internal InvalidOperationException MethodCalledTwice(string method) {
281 InvalidOperationException e = new InvalidOperationException(Res.GetString(Res.ADP_CalledTwice, method));
282 TraceExceptionAsReturnValue(e);
286 static internal ArgumentException IncorrectAsyncResult() {
287 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_IncorrectAsyncResult), "AsyncResult");
288 TraceExceptionAsReturnValue(e);
292 static internal ArgumentException SingleValuedProperty(string propertyName, string value) {
293 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_SingleValuedProperty, propertyName, value));
294 TraceExceptionAsReturnValue(e);
298 static internal ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) {
299 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_DoubleValuedProperty, propertyName, value1, value2));
300 TraceExceptionAsReturnValue(e);
304 static internal ArgumentException InvalidPrefixSuffix() {
305 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidPrefixSuffix));
306 TraceExceptionAsReturnValue(e);
310 static internal ArgumentException InvalidMultipartName(string property, string value) {
311 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartName, Res.GetString(property), value));
312 TraceExceptionAsReturnValue(e);
316 static internal ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) {
317 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameQuoteUsage, Res.GetString(property), value));
318 TraceExceptionAsReturnValue(e);
322 static internal ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) {
323 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameToManyParts, Res.GetString(property), value, limit));
324 TraceExceptionAsReturnValue(e);
328 static internal ArgumentException BadParameterName(string parameterName) {
329 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_BadParameterName, parameterName));
330 TraceExceptionAsReturnValue(e);
334 static internal ArgumentException MultipleReturnValue() {
335 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_MultipleReturnValue));
336 TraceExceptionAsReturnValue(e);
343 static internal void CheckArgumentLength(string value, string parameterName) {
344 CheckArgumentNull(value, parameterName);
345 if (0 == value.Length) {
346 throw Argument(Res.GetString(Res.ADP_EmptyString, parameterName)); // MDAC 94859
349 static internal void CheckArgumentLength(Array value, string parameterName) {
350 CheckArgumentNull(value, parameterName);
351 if (0 == value.Length) {
352 throw Argument(Res.GetString(Res.ADP_EmptyArray, parameterName));
355 static internal void CheckArgumentNull(object value, string parameterName) {
357 throw ArgumentNull(parameterName);
362 // only StackOverflowException & ThreadAbortException are sealed classes
363 static private readonly Type StackOverflowType = typeof(StackOverflowException);
364 static private readonly Type OutOfMemoryType = typeof(OutOfMemoryException);
365 static private readonly Type ThreadAbortType = typeof(ThreadAbortException);
366 static private readonly Type NullReferenceType = typeof(NullReferenceException);
367 static private readonly Type AccessViolationType = typeof(AccessViolationException);
368 static private readonly Type SecurityType = typeof(SecurityException);
370 static internal bool IsCatchableExceptionType (Exception e) {
371 // a 'catchable' exception is defined by what it is not.
372 Debug.Assert(e != null, "Unexpected null exception!");
373 Type type = e.GetType();
375 return ( (type != StackOverflowType) &&
376 (type != OutOfMemoryType) &&
377 (type != ThreadAbortType) &&
378 (type != NullReferenceType) &&
379 (type != AccessViolationType) &&
380 !SecurityType.IsAssignableFrom(type));
383 static internal bool IsCatchableOrSecurityExceptionType(Exception e) {
384 // a 'catchable' exception is defined by what it is not.
385 // since IsCatchableExceptionType defined SecurityException as not 'catchable'
386 // this method will return true for SecurityException has being catchable.
388 // the other way to write this method is, but then SecurityException is checked twice
389 // return ((e is SecurityException) || IsCatchableExceptionType(e));
391 Debug.Assert(e != null, "Unexpected null exception!");
392 Type type = e.GetType();
394 return ( (type != StackOverflowType) &&
395 (type != OutOfMemoryType) &&
396 (type != ThreadAbortType) &&
397 (type != NullReferenceType) &&
398 (type != AccessViolationType));
401 // Invalid Enumeration
403 static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) {
404 return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
407 static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) {
408 return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
411 static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) {
414 case AcceptRejectRule.None:
415 case AcceptRejectRule.Cascade:
416 Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
420 return InvalidEnumerationValue(typeof(AcceptRejectRule), (int) value);
422 // DbCommandBuilder.CatalogLocation
423 static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) {
426 case CatalogLocation.Start:
427 case CatalogLocation.End:
428 Debug.Assert(false, "valid CatalogLocation " + value.ToString());
432 return InvalidEnumerationValue(typeof(CatalogLocation), (int) value);
435 static internal ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) {
437 if ((0 <= (int)value) && ((int)value <= 0x3F)) {
438 Debug.Assert(false, "valid CommandType " + value.ToString());
441 return InvalidEnumerationValue(typeof(CommandBehavior), (int) value);
443 static internal void ValidateCommandBehavior(CommandBehavior value) {
444 if (((int)value < 0) || (0x3F < (int)value)) {
445 throw InvalidCommandBehavior(value);
448 static internal ArgumentException InvalidArgumentLength(string argumentName, int limit) {
449 return Argument(Res.GetString(Res.ADP_InvalidArgumentLength, argumentName, limit));
452 static internal ArgumentException MustBeReadOnly(string argumentName) {
453 return Argument(Res.GetString(Res.ADP_MustBeReadOnly, argumentName));
456 // IDbCommand.CommandType
457 static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) {
460 case CommandType.Text:
461 case CommandType.StoredProcedure:
462 case CommandType.TableDirect:
463 Debug.Assert(false, "valid CommandType " + value.ToString());
467 return InvalidEnumerationValue(typeof(CommandType), (int) value);
470 static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) {
473 case ConflictOption.CompareAllSearchableValues:
474 case ConflictOption.CompareRowVersion:
475 case ConflictOption.OverwriteChanges:
476 Debug.Assert(false, "valid ConflictOption " + value.ToString());
480 return InvalidEnumerationValue(typeof(ConflictOption), (int) value);
483 // IDataAdapter.Update
484 static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) {
487 case DataRowState.Detached:
488 case DataRowState.Unchanged:
489 case DataRowState.Added:
490 case DataRowState.Deleted:
491 case DataRowState.Modified:
492 Debug.Assert(false, "valid DataRowState " + value.ToString());
496 return InvalidEnumerationValue(typeof(DataRowState), (int) value);
499 // IDataParameter.SourceVersion
500 static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) {
503 case DataRowVersion.Default:
504 case DataRowVersion.Current:
505 case DataRowVersion.Original:
506 case DataRowVersion.Proposed:
507 Debug.Assert(false, "valid DataRowVersion " + value.ToString());
511 return InvalidEnumerationValue(typeof(DataRowVersion), (int) value);
514 // IDbConnection.BeginTransaction, OleDbTransaction.Begin
515 static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) {
518 case IsolationLevel.Unspecified:
519 case IsolationLevel.Chaos:
520 case IsolationLevel.ReadUncommitted:
521 case IsolationLevel.ReadCommitted:
522 case IsolationLevel.RepeatableRead:
523 case IsolationLevel.Serializable:
524 case IsolationLevel.Snapshot:
525 Debug.Assert(false, "valid IsolationLevel " + value.ToString());
529 return InvalidEnumerationValue(typeof(IsolationLevel), (int) value);
532 // DBDataPermissionAttribute.KeyRestrictionBehavior
533 static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) {
536 case KeyRestrictionBehavior.PreventUsage:
537 case KeyRestrictionBehavior.AllowOnly:
538 Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
542 return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int) value);
545 // IDataAdapter.FillLoadOption
546 static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) {
549 case LoadOption.OverwriteChanges:
550 case LoadOption.PreserveChanges:
551 case LoadOption.Upsert:
552 Debug.Assert(false, "valid LoadOption " + value.ToString());
556 return InvalidEnumerationValue(typeof(LoadOption), (int) value);
559 // IDataAdapter.MissingMappingAction
560 static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) {
563 case MissingMappingAction.Passthrough:
564 case MissingMappingAction.Ignore:
565 case MissingMappingAction.Error:
566 Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
570 return InvalidEnumerationValue(typeof(MissingMappingAction), (int) value);
573 // IDataAdapter.MissingSchemaAction
574 static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) {
577 case MissingSchemaAction.Add:
578 case MissingSchemaAction.Ignore:
579 case MissingSchemaAction.Error:
580 case MissingSchemaAction.AddWithKey:
581 Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
585 return InvalidEnumerationValue(typeof(MissingSchemaAction), (int) value);
588 // IDataParameter.Direction
589 static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) {
592 case ParameterDirection.Input:
593 case ParameterDirection.Output:
594 case ParameterDirection.InputOutput:
595 case ParameterDirection.ReturnValue:
596 Debug.Assert(false, "valid ParameterDirection " + value.ToString());
600 return InvalidEnumerationValue(typeof(ParameterDirection), (int) value);
603 static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionState value) {
606 case PermissionState.Unrestricted:
607 case PermissionState.None:
608 Debug.Assert(false, "valid PermissionState " + value.ToString());
612 return InvalidEnumerationValue(typeof(PermissionState), (int) value);
615 static internal ArgumentOutOfRangeException InvalidRule(Rule value) {
621 case Rule.SetDefault:
622 Debug.Assert(false, "valid Rule " + value.ToString());
626 return InvalidEnumerationValue(typeof(Rule), (int) value);
629 // IDataAdapter.FillSchema
630 static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) {
633 case SchemaType.Source:
634 case SchemaType.Mapped:
635 Debug.Assert(false, "valid SchemaType " + value.ToString());
639 return InvalidEnumerationValue(typeof(SchemaType), (int) value);
642 // RowUpdatingEventArgs.StatementType
643 static internal ArgumentOutOfRangeException InvalidStatementType(StatementType value) {
646 case StatementType.Select:
647 case StatementType.Insert:
648 case StatementType.Update:
649 case StatementType.Delete:
650 case StatementType.Batch:
651 Debug.Assert(false, "valid StatementType " + value.ToString());
655 return InvalidEnumerationValue(typeof(StatementType), (int) value);
658 // IDbCommand.UpdateRowSource
659 static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) {
662 case UpdateRowSource.None:
663 case UpdateRowSource.OutputParameters:
664 case UpdateRowSource.FirstReturnedRecord:
665 case UpdateRowSource.Both:
666 Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
670 return InvalidEnumerationValue(typeof(UpdateRowSource), (int) value);
673 // RowUpdatingEventArgs.UpdateStatus
674 static internal ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) {
677 case UpdateStatus.Continue:
678 case UpdateStatus.ErrorsOccurred:
679 case UpdateStatus.SkipAllRemainingRows:
680 case UpdateStatus.SkipCurrentRow:
681 Debug.Assert(false, "valid UpdateStatus " + value.ToString());
685 return InvalidEnumerationValue(typeof(UpdateStatus), (int) value);
688 static internal ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) {
689 return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
692 static internal ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method) {
693 return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method);
696 static internal ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value) {
699 case Microsoft.SqlServer.Server.Format.Unknown:
700 case Microsoft.SqlServer.Server.Format.Native:
701 case Microsoft.SqlServer.Server.Format.UserDefined:
702 Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString());
706 return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int) value);
709 static internal ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method) {
710 return ADP.NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method);
714 // DbProviderFactories
716 static internal ArgumentException ConfigProviderNotFound() {
717 return Argument(Res.GetString(Res.ConfigProviderNotFound));
719 static internal InvalidOperationException ConfigProviderInvalid() {
720 return InvalidOperation(Res.GetString(Res.ConfigProviderInvalid));
723 static internal ConfigurationException ConfigProviderNotInstalled() {
724 return Configuration(Res.GetString(Res.ConfigProviderNotInstalled));
726 static internal ConfigurationException ConfigProviderMissing() {
727 return Configuration(Res.GetString(Res.ConfigProviderMissing));
731 // DbProviderConfigurationHandler
733 static internal ConfigurationException ConfigBaseNoChildNodes(XmlNode node) { // Res.Config_base_no_child_nodes
734 return Configuration(Res.GetString(Res.ConfigBaseNoChildNodes), node);
736 static internal ConfigurationException ConfigBaseElementsOnly(XmlNode node) { // Res.Config_base_elements_only
737 return Configuration(Res.GetString(Res.ConfigBaseElementsOnly), node);
739 static internal ConfigurationException ConfigUnrecognizedAttributes(XmlNode node) { // Res.Config_base_unrecognized_attribute
740 return Configuration(Res.GetString(Res.ConfigUnrecognizedAttributes, node.Attributes[0].Name), node);
742 static internal ConfigurationException ConfigUnrecognizedElement(XmlNode node) { // Res.Config_base_unrecognized_element
743 return Configuration(Res.GetString(Res.ConfigUnrecognizedElement), node);
745 static internal ConfigurationException ConfigSectionsUnique(string sectionName) { // Res.Res.ConfigSectionsUnique
746 return Configuration(Res.GetString(Res.ConfigSectionsUnique, sectionName));
748 static internal ConfigurationException ConfigRequiredAttributeMissing(string name, XmlNode node) { // Res.Config_base_required_attribute_missing
749 return Configuration(Res.GetString(Res.ConfigRequiredAttributeMissing, name), node);
751 static internal ConfigurationException ConfigRequiredAttributeEmpty(string name, XmlNode node) { // Res.Config_base_required_attribute_empty
752 return Configuration(Res.GetString(Res.ConfigRequiredAttributeEmpty, name), node);
756 // DbConnectionOptions, DataAccess
758 static internal ArgumentException ConnectionStringSyntax(int index) {
759 return Argument(Res.GetString(Res.ADP_ConnectionStringSyntax, index));
761 static internal ArgumentException KeywordNotSupported(string keyword) {
762 return Argument(Res.GetString(Res.ADP_KeywordNotSupported, keyword));
765 static internal ArgumentException EmptyKeyValue(string keyword) { // MDAC 80715
766 return Argument(Res.GetString(Res.ADP_EmptyKeyValue, keyword));
769 static internal ArgumentException UdlFileError(Exception inner) {
770 return Argument(Res.GetString(Res.ADP_UdlFileError), inner);
772 static internal ArgumentException InvalidUDL() {
773 return Argument(Res.GetString(Res.ADP_InvalidUDL));
775 static internal InvalidOperationException InvalidDataDirectory() {
776 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidDataDirectory));
778 static internal ArgumentException InvalidKeyname(string parameterName) {
779 return Argument(Res.GetString(Res.ADP_InvalidKey), parameterName);
781 static internal ArgumentException InvalidValue(string parameterName) {
782 return Argument(Res.GetString(Res.ADP_InvalidValue), parameterName);
784 static internal ArgumentException InvalidMinMaxPoolSizeValues() {
785 return ADP.Argument(Res.GetString(Res.ADP_InvalidMinMaxPoolSizeValues));
787 static internal ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) {
788 return ADP.Argument(Res.GetString(Res.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
791 static internal InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() {
792 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
795 static internal ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() {
796 return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
799 static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() {
800 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
803 static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() {
804 return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
807 static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndContextConnection()
809 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
812 static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndContextConnection()
814 return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
817 static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndContextConnection() {
818 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndContextConnection));
821 static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() {
822 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity));
825 static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() {
826 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword));
829 static internal Exception InvalidMixedUsageOfAccessTokenAndCredential() {
830 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndCredential));
833 static internal Exception InvalidMixedUsageOfAccessTokenAndAuthentication() {
834 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication));
837 static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() {
838 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
844 static internal InvalidOperationException NoConnectionString() {
845 return InvalidOperation(Res.GetString(Res.ADP_NoConnectionString));
848 static internal NotImplementedException MethodNotImplemented(string methodName) {
849 NotImplementedException e = new NotImplementedException(methodName);
850 TraceExceptionAsReturnValue(e);
853 static private string ConnectionStateMsg(ConnectionState state) { // MDAC 82165, if the ConnectionState enum to msg the localization looks weird
855 case (ConnectionState.Closed):
856 case (ConnectionState.Connecting|ConnectionState.Broken): // treated the same as closed
857 return Res.GetString(Res.ADP_ConnectionStateMsg_Closed);
858 case (ConnectionState.Connecting):
859 return Res.GetString(Res.ADP_ConnectionStateMsg_Connecting);
860 case (ConnectionState.Open):
861 return Res.GetString(Res.ADP_ConnectionStateMsg_Open);
862 case (ConnectionState.Open|ConnectionState.Executing):
863 return Res.GetString(Res.ADP_ConnectionStateMsg_OpenExecuting);
864 case (ConnectionState.Open|ConnectionState.Fetching):
865 return Res.GetString(Res.ADP_ConnectionStateMsg_OpenFetching);
867 return Res.GetString(Res.ADP_ConnectionStateMsg, state.ToString());
871 static internal ConfigurationException ConfigUnableToLoadXmlMetaDataFile(string settingName){
872 return Configuration(Res.GetString(Res.OleDb_ConfigUnableToLoadXmlMetaDataFile, settingName));
875 static internal ConfigurationException ConfigWrongNumberOfValues(string settingName){
876 return Configuration(Res.GetString(Res.OleDb_ConfigWrongNumberOfValues, settingName));
880 // : DbConnectionOptions, DataAccess, SqlClient
882 static internal Exception InvalidConnectionOptionValue(string key) {
883 return InvalidConnectionOptionValue(key, null);
885 static internal Exception InvalidConnectionOptionValueLength(string key, int limit) {
886 return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValueLength, key, limit));
888 static internal Exception InvalidConnectionOptionValue(string key, Exception inner) {
889 return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValue, key), inner);
891 static internal Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) {
892 return Argument(Res.GetString(Res.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
896 // DBDataPermission, DataAccess, Odbc
898 static internal Exception InvalidXMLBadVersion() {
899 return Argument(Res.GetString(Res.ADP_InvalidXMLBadVersion));
901 static internal Exception NotAPermissionElement() {
902 return Argument(Res.GetString(Res.ADP_NotAPermissionElement));
904 static internal Exception PermissionTypeMismatch() {
905 return Argument(Res.GetString(Res.ADP_PermissionTypeMismatch));
908 static internal Exception WrongType(Type got, Type expected) {
909 return Argument(Res.GetString(Res.SQL_WrongType, got.ToString(), expected.ToString()));
912 static internal Exception OdbcNoTypesFromProvider() {
913 return InvalidOperation(Res.GetString(Res.ADP_OdbcNoTypesFromProvider));
917 // DbConnectionPool and related
919 static internal Exception PooledOpenTimeout() {
920 return ADP.InvalidOperation(Res.GetString(Res.ADP_PooledOpenTimeout));
923 static internal Exception NonPooledOpenTimeout() {
924 return ADP.TimeoutException(Res.GetString(Res.ADP_NonPooledOpenTimeout));
928 // Generic Data Provider Collection
930 static internal ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) {
931 return Argument(Res.GetString(Res.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); // MDAC 68201
933 static internal ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) {
934 return ArgumentNull(parameter, Res.GetString(Res.ADP_CollectionNullValue, collection.Name, itemType.Name));
936 static internal IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) {
937 return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
939 static internal IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) {
940 return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
942 static internal InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) {
943 return InvalidCast(Res.GetString(Res.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
945 static internal Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue) {
946 return Argument(Res.GetString(Res.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue));
948 static internal ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) {
949 return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
951 static internal ArgumentException ParametersIsParent(Type parameterType, ICollection collection) {
952 return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
956 // DbProviderException
958 static internal InvalidOperationException TransactionConnectionMismatch() {
959 return Provider(Res.GetString(Res.ADP_TransactionConnectionMismatch));
961 static internal InvalidOperationException TransactionCompletedButNotDisposed()
963 return Provider(Res.GetString(Res.ADP_TransactionCompletedButNotDisposed));
965 static internal InvalidOperationException TransactionRequired(string method) {
966 return Provider(Res.GetString(Res.ADP_TransactionRequired, method));
969 // IDbDataAdapter.Fill(Schema)
970 static internal InvalidOperationException MissingSelectCommand(string method) {
971 return Provider(Res.GetString(Res.ADP_MissingSelectCommand, method));
975 // AdapterMappingException
977 static private InvalidOperationException DataMapping(string error) {
978 return InvalidOperation(error);
981 // DataColumnMapping.GetDataColumnBySchemaAction
982 static internal InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn) {
983 return DataMapping(Res.GetString(Res.ADP_ColumnSchemaExpression, srcColumn, cacheColumn));
986 // DataColumnMapping.GetDataColumnBySchemaAction
987 static internal InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column) {
988 return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name));
991 // DataColumnMapping.GetDataColumnBySchemaAction
992 static internal InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn) {
993 if (ADP.IsEmpty(tableName)) {
994 return InvalidOperation(Res.GetString(Res.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn));
996 return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn));
999 // DataColumnMappingCollection.GetColumnMappingBySchemaAction
1000 static internal InvalidOperationException MissingColumnMapping(string srcColumn) {
1001 return DataMapping(Res.GetString(Res.ADP_MissingColumnMapping, srcColumn));
1004 // DataTableMapping.GetDataTableBySchemaAction
1005 static internal InvalidOperationException MissingTableSchema(string cacheTable, string srcTable) {
1006 return DataMapping(Res.GetString(Res.ADP_MissingTableSchema, cacheTable, srcTable));
1009 // DataTableMappingCollection.GetTableMappingBySchemaAction
1010 static internal InvalidOperationException MissingTableMapping(string srcTable) {
1011 return DataMapping(Res.GetString(Res.ADP_MissingTableMapping, srcTable));
1014 // DbDataAdapter.Update
1015 static internal InvalidOperationException MissingTableMappingDestination(string dstTable) {
1016 return DataMapping(Res.GetString(Res.ADP_MissingTableMappingDestination, dstTable));
1020 // DataColumnMappingCollection, DataAccess
1022 static internal Exception InvalidSourceColumn(string parameter) {
1023 return Argument(Res.GetString(Res.ADP_InvalidSourceColumn), parameter);
1025 static internal Exception ColumnsAddNullAttempt(string parameter) {
1026 return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping));
1028 static internal Exception ColumnsDataSetColumn(string cacheColumn) {
1029 return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection));
1031 static internal Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection) {
1032 return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1034 static internal Exception ColumnsIndexSource(string srcColumn) {
1035 return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection));
1037 static internal Exception ColumnsIsNotParent(ICollection collection) {
1038 return ParametersIsNotParent(typeof(DataColumnMapping), collection);
1040 static internal Exception ColumnsIsParent(ICollection collection) {
1041 return ParametersIsParent(typeof(DataColumnMapping), collection);
1043 static internal Exception ColumnsUniqueSourceColumn(string srcColumn) {
1044 return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn);
1046 static internal Exception NotADataColumnMapping(object value) {
1047 return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value);
1051 // DataTableMappingCollection, DataAccess
1053 static internal Exception InvalidSourceTable(string parameter) {
1054 return Argument(Res.GetString(Res.ADP_InvalidSourceTable), parameter);
1056 static internal Exception TablesAddNullAttempt(string parameter) {
1057 return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping));
1059 static internal Exception TablesDataSetTable(string cacheTable) {
1060 return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection));
1062 static internal Exception TablesIndexInt32(int index, ITableMappingCollection collection) {
1063 return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1065 static internal Exception TablesIsNotParent(ICollection collection) {
1066 return ParametersIsNotParent(typeof(DataTableMapping), collection);
1068 static internal Exception TablesIsParent(ICollection collection) {
1069 return ParametersIsParent(typeof(DataTableMapping), collection);
1071 static internal Exception TablesSourceIndex(string srcTable) {
1072 return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection));
1074 static internal Exception TablesUniqueSourceTable(string srcTable) {
1075 return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable);
1077 static internal Exception NotADataTableMapping(object value) {
1078 return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value);
1085 static internal InvalidOperationException CommandAsyncOperationCompleted() {
1086 return InvalidOperation(Res.GetString(Res.SQL_AsyncOperationCompleted));
1089 static internal Exception CommandTextRequired(string method) {
1090 return InvalidOperation(Res.GetString(Res.ADP_CommandTextRequired, method));
1093 static internal InvalidOperationException ConnectionRequired(string method) {
1094 return InvalidOperation(Res.GetString(Res.ADP_ConnectionRequired, method));
1096 static internal InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) {
1097 return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
1101 static internal InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand) {
1103 if (isRowUpdatingCommand) {
1104 resource = Res.ADP_ConnectionRequired_Clone;
1107 switch(statementType) {
1108 case StatementType.Insert:
1109 resource = Res.ADP_ConnectionRequired_Insert;
1111 case StatementType.Update:
1112 resource = Res.ADP_ConnectionRequired_Update;
1114 case StatementType.Delete:
1115 resource = Res.ADP_ConnectionRequired_Delete;
1117 case StatementType.Batch:
1118 resource = Res.ADP_ConnectionRequired_Batch;
1121 case StatementType.Select:
1122 Debug.Assert(false, "shouldn't be here");
1126 throw ADP.InvalidStatementType(statementType);
1129 return InvalidOperation(Res.GetString(resource));
1132 static internal InvalidOperationException ConnectionRequired_Res(string method) {
1133 string resource = "ADP_ConnectionRequired_" + method;
1136 case Res.ADP_ConnectionRequired_Fill:
1137 case Res.ADP_ConnectionRequired_FillPage:
1138 case Res.ADP_ConnectionRequired_FillSchema:
1139 case Res.ADP_ConnectionRequired_Update:
1140 case Res.ADP_ConnecitonRequired_UpdateRows:
1143 Debug.Assert(false, "missing resource string: " + resource);
1147 return InvalidOperation(Res.GetString(resource));
1149 static internal InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state) {
1151 if (isRowUpdatingCommand) {
1152 resource = Res.ADP_OpenConnectionRequired_Clone;
1155 switch(statementType) {
1156 case StatementType.Insert:
1157 resource = Res.ADP_OpenConnectionRequired_Insert;
1159 case StatementType.Update:
1160 resource = Res.ADP_OpenConnectionRequired_Update;
1162 case StatementType.Delete:
1163 resource = Res.ADP_OpenConnectionRequired_Delete;
1166 case StatementType.Select:
1167 Debug.Assert(false, "shouldn't be here");
1169 case StatementType.Batch:
1170 Debug.Assert(false, "isRowUpdatingCommand should have been true");
1174 throw ADP.InvalidStatementType(statementType);
1177 return InvalidOperation(Res.GetString(resource, ADP.ConnectionStateMsg(state)));
1180 static internal Exception NoStoredProcedureExists(string sproc) {
1181 return InvalidOperation(Res.GetString(Res.ADP_NoStoredProcedureExists, sproc));
1183 static internal Exception OpenReaderExists() {
1184 return OpenReaderExists(null);
1187 static internal Exception OpenReaderExists(Exception e) {
1188 return InvalidOperation(Res.GetString(Res.ADP_OpenReaderExists), e);
1191 static internal Exception TransactionCompleted() {
1192 return DataAdapter(Res.GetString(Res.ADP_TransactionCompleted));
1198 static internal Exception NonSeqByteAccess(long badIndex, long currIndex, string method) {
1199 return InvalidOperation(Res.GetString(Res.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
1202 static internal Exception NegativeParameter(string parameterName) {
1203 return InvalidOperation(Res.GetString(Res.ADP_NegativeParameter, parameterName));
1206 static internal Exception NumericToDecimalOverflow() {
1207 return InvalidCast(Res.GetString(Res.ADP_NumericToDecimalOverflow));
1211 // Stream, SqlTypes, SqlClient
1214 static internal Exception ExceedsMaxDataLength(long specifiedLength, long maxLength) {
1215 return IndexOutOfRange(Res.GetString(Res.SQL_ExceedsMaxDataLength, specifiedLength.ToString(CultureInfo.InvariantCulture), maxLength.ToString(CultureInfo.InvariantCulture)));
1218 static internal Exception InvalidSeekOrigin(string parameterName) {
1219 return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSeekOrigin), parameterName);
1223 // SqlMetaData, SqlTypes, SqlClient
1225 static internal Exception InvalidImplicitConversion(Type fromtype, string totype) {
1226 return InvalidCast(Res.GetString(Res.ADP_InvalidImplicitConversion, fromtype.Name, totype));
1228 static internal Exception InvalidMetaDataValue() {
1229 return ADP.Argument(Res.GetString(Res.ADP_InvalidMetaDataValue));
1232 static internal Exception NotRowType() {
1233 return InvalidOperation(Res.GetString(Res.ADP_NotRowType));
1239 static internal ArgumentException UnwantedStatementType(StatementType statementType) {
1240 return Argument(Res.GetString(Res.ADP_UnwantedStatementType, statementType.ToString()));
1242 static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) {
1243 return InvalidOperation(Res.GetString(Res.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
1247 // DbDataAdapter.FillSchema
1249 static internal Exception FillSchemaRequiresSourceTableName(string parameter) {
1250 return Argument(Res.GetString(Res.ADP_FillSchemaRequiresSourceTableName), parameter);
1254 // DbDataAdapter.Fill
1256 static internal Exception InvalidMaxRecords(string parameter, int max) {
1257 return Argument(Res.GetString(Res.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter);
1259 static internal Exception InvalidStartRecord(string parameter, int start) {
1260 return Argument(Res.GetString(Res.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter);
1262 static internal Exception FillRequires(string parameter) {
1263 return ArgumentNull(parameter);
1265 static internal Exception FillRequiresSourceTableName(string parameter) {
1266 return Argument(Res.GetString(Res.ADP_FillRequiresSourceTableName), parameter);
1268 static internal Exception FillChapterAutoIncrement() {
1269 return InvalidOperation(Res.GetString(Res.ADP_FillChapterAutoIncrement));
1271 static internal InvalidOperationException MissingDataReaderFieldType(int index) {
1272 return DataAdapter(Res.GetString(Res.ADP_MissingDataReaderFieldType, index));
1274 static internal InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords() {
1275 return DataAdapter(Res.GetString(Res.ADP_OnlyOneTableForStartRecordOrMaxRecords));
1278 // DbDataAdapter.Update
1280 static internal ArgumentNullException UpdateRequiresNonNullDataSet(string parameter) {
1281 return ArgumentNull(parameter);
1283 static internal InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName) {
1284 return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTable, defaultSrcTableName));
1286 static internal InvalidOperationException UpdateRequiresSourceTableName(string srcTable) {
1287 return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTableName, srcTable)); // MDAC 70448
1289 static internal ArgumentNullException UpdateRequiresDataTable(string parameter) {
1290 return ArgumentNull(parameter);
1293 static internal Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows) {
1295 switch(statementType) {
1296 case StatementType.Update:
1297 resource = Res.ADP_UpdateConcurrencyViolation_Update;
1299 case StatementType.Delete:
1300 resource = Res.ADP_UpdateConcurrencyViolation_Delete;
1302 case StatementType.Batch:
1303 resource = Res.ADP_UpdateConcurrencyViolation_Batch;
1306 case StatementType.Select:
1307 case StatementType.Insert:
1308 Debug.Assert(false, "should be here");
1312 throw ADP.InvalidStatementType(statementType);
1314 DBConcurrencyException exception = new DBConcurrencyException(Res.GetString(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows);
1315 TraceExceptionAsReturnValue(exception);
1319 static internal InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand) {
1321 if (isRowUpdatingCommand) {
1322 resource = Res.ADP_UpdateRequiresCommandClone;
1325 switch(statementType) {
1326 case StatementType.Select:
1327 resource = Res.ADP_UpdateRequiresCommandSelect;
1329 case StatementType.Insert:
1330 resource = Res.ADP_UpdateRequiresCommandInsert;
1332 case StatementType.Update:
1333 resource = Res.ADP_UpdateRequiresCommandUpdate;
1335 case StatementType.Delete:
1336 resource = Res.ADP_UpdateRequiresCommandDelete;
1339 case StatementType.Batch:
1340 Debug.Assert(false, "isRowUpdatingCommand should have been true");
1344 throw ADP.InvalidStatementType(statementType);
1347 return InvalidOperation(Res.GetString(resource));
1349 static internal ArgumentException UpdateMismatchRowTable(int i) {
1350 return Argument(Res.GetString(Res.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture)));
1352 static internal DataException RowUpdatedErrors() {
1353 return Data(Res.GetString(Res.ADP_RowUpdatedErrors));
1355 static internal DataException RowUpdatingErrors() {
1356 return Data(Res.GetString(Res.ADP_RowUpdatingErrors));
1358 static internal InvalidOperationException ResultsNotAllowedDuringBatch() {
1359 return DataAdapter(Res.GetString(Res.ADP_ResultsNotAllowedDuringBatch));
1365 static internal Exception InvalidCommandTimeout(int value) {
1366 return Argument(Res.GetString(Res.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout);
1368 static internal Exception DeriveParametersNotSupported(IDbCommand value) {
1369 return DataAdapter(Res.GetString(Res.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
1371 static internal Exception UninitializedParameterSize(int index, Type dataType) {
1372 return InvalidOperation(Res.GetString(Res.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
1374 static internal Exception PrepareParameterType(IDbCommand cmd) {
1375 return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterType, cmd.GetType().Name));
1377 static internal Exception PrepareParameterSize(IDbCommand cmd) {
1378 return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name));
1380 static internal Exception PrepareParameterScale(IDbCommand cmd, string type) {
1381 return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterScale, cmd.GetType().Name, type));
1383 static internal Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) {
1384 return InvalidOperation(Res.GetString(Res.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
1390 static internal Exception ConnectionIsDisabled (Exception InnerException) {
1391 return InvalidOperation(Res.GetString(Res.ADP_ConnectionIsDisabled), InnerException);
1393 static internal Exception ClosedConnectionError() {
1394 return InvalidOperation(Res.GetString(Res.ADP_ClosedConnectionError));
1396 static internal Exception ConnectionAlreadyOpen(ConnectionState state) {
1397 return InvalidOperation(Res.GetString(Res.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
1399 static internal Exception DelegatedTransactionPresent() {
1400 return InvalidOperation(Res.GetString(Res.ADP_DelegatedTransactionPresent));
1402 static internal Exception TransactionPresent() {
1403 return InvalidOperation(Res.GetString(Res.ADP_TransactionPresent));
1405 static internal Exception LocalTransactionPresent() {
1406 return InvalidOperation(Res.GetString(Res.ADP_LocalTransactionPresent));
1408 static internal Exception OpenConnectionPropertySet(string property, ConnectionState state) {
1409 return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
1411 static internal Exception EmptyDatabaseName() {
1412 return Argument(Res.GetString(Res.ADP_EmptyDatabaseName));
1414 static internal Exception DatabaseNameTooLong() {
1415 return Argument(Res.GetString(Res.ADP_DatabaseNameTooLong));
1418 internal enum ConnectionError {
1419 BeginGetConnectionReturnsNull,
1420 GetConnectionReturnsNull,
1421 ConnectionOptionsMissing,
1422 CouldNotSwitchToClosedPreviouslyOpenedState,
1424 static internal Exception InternalConnectionError(ConnectionError internalError) {
1425 return InvalidOperation(Res.GetString(Res.ADP_InternalConnectionError, (int)internalError));
1428 internal enum InternalErrorCode {
1429 UnpooledObjectHasOwner = 0,
1430 UnpooledObjectHasWrongOwner = 1,
1431 PushingObjectSecondTime = 2,
1432 PooledObjectHasOwner = 3,
1433 PooledObjectInPoolMoreThanOnce = 4,
1434 CreateObjectReturnedNull = 5,
1435 NewObjectCannotBePooled = 6,
1436 NonPooledObjectUsedMoreThanOnce = 7,
1437 AttemptingToPoolOnRestrictedToken = 8,
1438 // ConnectionOptionsInUse = 9,
1439 ConvertSidToStringSidWReturnedNull = 10,
1440 // UnexpectedTransactedObject = 11,
1441 AttemptingToConstructReferenceCollectionOnStaticObject = 12,
1442 AttemptingToEnlistTwice = 13,
1443 CreateReferenceCollectionReturnedNull = 14,
1444 PooledObjectWithoutPool = 15,
1445 UnexpectedWaitAnyResult = 16,
1446 SynchronousConnectReturnedPending = 17,
1447 CompletedConnectReturnedPending = 18,
1449 NameValuePairNext = 20,
1450 InvalidParserState1 = 21,
1451 InvalidParserState2 = 22,
1452 InvalidParserState3 = 23,
1456 UnimplementedSMIMethod = 40,
1457 InvalidSmiCall = 41,
1459 SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
1460 SqlDependencyProcessDispatcherFailureCreateInstance = 51,
1461 SqlDependencyProcessDispatcherFailureAppDomain = 52,
1462 SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
1464 UnknownTransactionFailure = 60,
1466 static internal Exception InternalError(InternalErrorCode internalError) {
1467 return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError));
1469 static internal Exception InternalError(InternalErrorCode internalError, Exception innerException) {
1470 return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError), innerException);
1472 static internal Exception InvalidConnectTimeoutValue() {
1473 return Argument(Res.GetString(Res.ADP_InvalidConnectTimeoutValue));
1476 static internal Exception InvalidConnectRetryCountValue() {
1477 return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryCountValue));
1480 static internal Exception InvalidConnectRetryIntervalValue() {
1481 return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryIntervalValue));
1487 static internal Exception DataReaderNoData() {
1488 return InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData));
1490 static internal Exception DataReaderClosed(string method) {
1491 return InvalidOperation(Res.GetString(Res.ADP_DataReaderClosed, method));
1493 static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) {
1494 return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
1496 static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) {
1497 return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
1499 static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) {
1500 return IndexOutOfRange(Res.GetString(Res.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
1502 static internal Exception InvalidDataLength(long length) {
1503 return IndexOutOfRange(Res.GetString(Res.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
1505 static internal InvalidOperationException AsyncOperationPending() {
1506 return InvalidOperation(Res.GetString(Res.ADP_PendingAsyncOperation));
1512 static internal Exception StreamClosed(string method) {
1513 return InvalidOperation(Res.GetString(Res.ADP_StreamClosed, method));
1515 static internal IOException ErrorReadingFromStream(Exception internalException) {
1516 return IO(Res.GetString(Res.SqlMisc_StreamErrorMessage), internalException);
1522 static internal InvalidOperationException DynamicSQLJoinUnsupported() {
1523 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLJoinUnsupported));
1525 static internal InvalidOperationException DynamicSQLNoTableInfo() {
1526 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoTableInfo));
1528 static internal InvalidOperationException DynamicSQLNoKeyInfoDelete() {
1529 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoDelete));
1531 static internal InvalidOperationException DynamicSQLNoKeyInfoUpdate() {
1532 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoUpdate));
1534 static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete() {
1535 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionDelete));
1537 static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate() {
1538 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionUpdate));
1540 static internal InvalidOperationException DynamicSQLNestedQuote(string name, string quote) {
1541 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNestedQuote, name, quote));
1543 static internal InvalidOperationException NoQuoteChange() {
1544 return InvalidOperation(Res.GetString(Res.ADP_NoQuoteChange));
1546 static internal InvalidOperationException ComputerNameEx(int lastError) {
1547 return InvalidOperation(Res.GetString(Res.ADP_ComputerNameEx, lastError));
1549 static internal InvalidOperationException MissingSourceCommand() {
1550 return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommand));
1552 static internal InvalidOperationException MissingSourceCommandConnection() {
1553 return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommandConnection));
1559 static internal ArgumentException InvalidDataType(TypeCode typecode) {
1560 return Argument(Res.GetString(Res.ADP_InvalidDataType, typecode.ToString()));
1562 static internal ArgumentException UnknownDataType(Type dataType) {
1563 return Argument(Res.GetString(Res.ADP_UnknownDataType, dataType.FullName));
1565 static internal ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype) {
1566 return Argument(Res.GetString(Res.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
1568 static internal ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) {
1569 return Argument(Res.GetString(Res.ADP_UnknownDataTypeCode, ((int) typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
1571 static internal ArgumentException InvalidOffsetValue(int value) {
1572 return Argument(Res.GetString(Res.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
1574 static internal ArgumentException InvalidSizeValue(int value) {
1575 return Argument(Res.GetString(Res.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
1577 static internal ArgumentException ParameterValueOutOfRange(Decimal value) {
1578 return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
1580 static internal ArgumentException ParameterValueOutOfRange(SqlDecimal value) {
1581 return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString()));
1584 static internal ArgumentException ParameterValueOutOfRange(String value) {
1585 return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value));
1588 static internal ArgumentException VersionDoesNotSupportDataType(string typeName) {
1589 return Argument(Res.GetString(Res.ADP_VersionDoesNotSupportDataType, typeName));
1591 static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) { // WebData 75433
1592 Debug.Assert(null != value, "null value on conversion failure");
1593 Debug.Assert(null != inner, "null inner on conversion failure");
1596 string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
1597 if (inner is ArgumentException) {
1598 e = new ArgumentException(message, inner);
1600 else if (inner is FormatException) {
1601 e = new FormatException(message, inner);
1603 else if (inner is InvalidCastException) {
1604 e = new InvalidCastException(message, inner);
1606 else if (inner is OverflowException) {
1607 e = new OverflowException(message, inner);
1612 TraceExceptionAsReturnValue(e);
1617 // : IDataParameterCollection
1619 static internal Exception ParametersMappingIndex(int index, IDataParameterCollection collection) {
1620 return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1622 static internal Exception ParametersSourceIndex(string parameterName, IDataParameterCollection collection, Type parameterType) {
1623 return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
1625 static internal Exception ParameterNull(string parameter, IDataParameterCollection collection, Type parameterType) {
1626 return CollectionNullValue(parameter, collection.GetType(), parameterType);
1628 static internal Exception InvalidParameterType(IDataParameterCollection collection, Type parameterType, object invalidValue) {
1629 return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
1635 static internal Exception ParallelTransactionsNotSupported(IDbConnection obj) {
1636 return InvalidOperation(Res.GetString(Res.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
1638 static internal Exception TransactionZombied(IDbTransaction obj) {
1639 return InvalidOperation(Res.GetString(Res.ADP_TransactionZombied, obj.GetType().Name));
1642 static internal Exception DbRecordReadOnly(string methodname) {
1643 return InvalidOperation(Res.GetString(Res.ADP_DbRecordReadOnly, methodname));
1646 static internal Exception OffsetOutOfRangeException() {
1647 return InvalidOperation(Res.GetString(Res.ADP_OffsetOutOfRangeException));
1651 // : DbMetaDataFactory
1654 static internal Exception AmbigousCollectionName(string collectionName) {
1655 return Argument(Res.GetString(Res.MDF_AmbigousCollectionName,collectionName));
1658 static internal Exception CollectionNameIsNotUnique(string collectionName) {
1659 return Argument(Res.GetString(Res.MDF_CollectionNameISNotUnique,collectionName));
1662 static internal Exception DataTableDoesNotExist(string collectionName) {
1663 return Argument(Res.GetString(Res.MDF_DataTableDoesNotExist,collectionName));
1666 static internal Exception IncorrectNumberOfDataSourceInformationRows() {
1667 return Argument(Res.GetString(Res.MDF_IncorrectNumberOfDataSourceInformationRows));
1670 static internal ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue) {
1671 return ADP.Argument(Res.GetString(Res.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue));
1674 static internal Exception InvalidXml() {
1675 return Argument(Res.GetString(Res.MDF_InvalidXml));
1678 static internal Exception InvalidXmlMissingColumn(string collectionName, string columnName) {
1679 return Argument(Res.GetString(Res.MDF_InvalidXmlMissingColumn, collectionName, columnName));
1682 static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName) {
1683 return Argument(Res.GetString(Res.MDF_InvalidXmlInvalidValue, collectionName, columnName));
1686 static internal Exception MissingDataSourceInformationColumn() {
1687 return Argument(Res.GetString(Res.MDF_MissingDataSourceInformationColumn));
1690 static internal Exception MissingRestrictionColumn() {
1691 return Argument(Res.GetString(Res.MDF_MissingRestrictionColumn));
1694 static internal Exception MissingRestrictionRow() {
1695 return Argument(Res.GetString(Res.MDF_MissingRestrictionRow));
1698 static internal Exception NoColumns() {
1699 return Argument(Res.GetString(Res.MDF_NoColumns));
1702 static internal Exception QueryFailed(string collectionName, Exception e) {
1703 return InvalidOperation(Res.GetString(Res.MDF_QueryFailed,collectionName), e);
1706 static internal Exception TooManyRestrictions(string collectionName) {
1707 return Argument(Res.GetString(Res.MDF_TooManyRestrictions,collectionName));
1710 static internal Exception UnableToBuildCollection(string collectionName) {
1711 return Argument(Res.GetString(Res.MDF_UnableToBuildCollection,collectionName));
1714 static internal Exception UndefinedCollection(string collectionName) {
1715 return Argument(Res.GetString(Res.MDF_UndefinedCollection,collectionName));
1718 static internal Exception UndefinedPopulationMechanism(string populationMechanism) {
1719 return Argument(Res.GetString(Res.MDF_UndefinedPopulationMechanism,populationMechanism));
1722 static internal Exception UnsupportedVersion(string collectionName) {
1723 return Argument(Res.GetString(Res.MDF_UnsupportedVersion,collectionName));
1731 static internal InvalidOperationException InvalidDateTimeDigits(string dataTypeName) {
1732 return InvalidOperation(Res.GetString(Res.ADP_InvalidDateTimeDigits, dataTypeName));
1735 static internal Exception InvalidFormatValue() {
1736 return Argument(Res.GetString(Res.ADP_InvalidFormatValue));
1739 static internal InvalidOperationException InvalidMaximumScale(string dataTypeName) {
1740 return InvalidOperation(Res.GetString(Res.ADP_InvalidMaximumScale, dataTypeName));
1743 static internal Exception LiteralValueIsInvalid(string dataTypeName){
1744 return Argument(Res.GetString(Res.ADP_LiteralValueIsInvalid,dataTypeName));
1747 static internal Exception EvenLengthLiteralValue(string argumentName) {
1748 return Argument(Res.GetString(Res.ADP_EvenLengthLiteralValue), argumentName );
1751 static internal Exception HexDigitLiteralValue(string argumentName) {
1752 return Argument(Res.GetString(Res.ADP_HexDigitLiteralValue), argumentName );
1755 static internal InvalidOperationException QuotePrefixNotSet(string method) {
1756 return InvalidOperation(Res.GetString(Res.ADP_QuotePrefixNotSet, method));
1759 static internal InvalidOperationException UnableToCreateBooleanLiteral() {
1760 return ADP.InvalidOperation(Res.GetString(Res.ADP_UnableToCreateBooleanLiteral));
1763 static internal Exception UnsupportedNativeDataTypeOleDb(string dataTypeName) {
1764 return Argument(Res.GetString(Res.ADP_UnsupportedNativeDataTypeOleDb, dataTypeName));
1767 // Sql Result Set and other generic message
1768 static internal Exception InvalidArgumentValue(string methodName) {
1769 return Argument(Res.GetString(Res.ADP_InvalidArgumentValue, methodName));
1772 // global constant strings
1773 internal const string Append = "Append";
1774 internal const string BeginExecuteNonQuery = "BeginExecuteNonQuery";
1775 internal const string BeginExecuteReader = "BeginExecuteReader";
1776 internal const string BeginTransaction = "BeginTransaction";
1777 internal const string BeginExecuteXmlReader = "BeginExecuteXmlReader";
1778 internal const string ChangeDatabase = "ChangeDatabase";
1779 internal const string Cancel = "Cancel";
1780 internal const string Clone = "Clone";
1781 internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_";
1782 internal const string CommitTransaction = "CommitTransaction";
1783 internal const string CommandTimeout = "CommandTimeout";
1784 internal const string ConnectionString = "ConnectionString";
1785 internal const string DataSetColumn = "DataSetColumn";
1786 internal const string DataSetTable = "DataSetTable";
1787 internal const string Delete = "Delete";
1788 internal const string DeleteCommand = "DeleteCommand";
1789 internal const string DeriveParameters = "DeriveParameters";
1790 internal const string EndExecuteNonQuery = "EndExecuteNonQuery";
1791 internal const string EndExecuteReader = "EndExecuteReader";
1792 internal const string EndExecuteXmlReader = "EndExecuteXmlReader";
1793 internal const string ExecuteReader = "ExecuteReader";
1794 internal const string ExecuteRow = "ExecuteRow";
1795 internal const string ExecuteNonQuery = "ExecuteNonQuery";
1796 internal const string ExecuteScalar = "ExecuteScalar";
1797 internal const string ExecuteSqlScalar = "ExecuteSqlScalar";
1798 internal const string ExecuteXmlReader = "ExecuteXmlReader";
1799 internal const string Fill = "Fill";
1800 internal const string FillPage = "FillPage";
1801 internal const string FillSchema = "FillSchema";
1802 internal const string GetBytes = "GetBytes";
1803 internal const string GetChars = "GetChars";
1804 internal const string GetOleDbSchemaTable = "GetOleDbSchemaTable";
1805 internal const string GetProperties = "GetProperties";
1806 internal const string GetSchema = "GetSchema";
1807 internal const string GetSchemaTable = "GetSchemaTable";
1808 internal const string GetServerTransactionLevel = "GetServerTransactionLevel";
1809 internal const string Insert = "Insert";
1810 internal const string Open = "Open";
1811 internal const string Parameter = "Parameter";
1812 internal const string ParameterBuffer = "buffer";
1813 internal const string ParameterCount = "count";
1814 internal const string ParameterDestinationType = "destinationType";
1815 internal const string ParameterIndex = "index";
1816 internal const string ParameterName = "ParameterName";
1817 internal const string ParameterOffset = "offset";
1818 internal const string ParameterSetPosition = "set_Position";
1819 internal const string ParameterService = "Service";
1820 internal const string ParameterTimeout = "Timeout";
1821 internal const string ParameterUserData = "UserData";
1822 internal const string Prepare = "Prepare";
1823 internal const string QuoteIdentifier = "QuoteIdentifier";
1824 internal const string Read = "Read";
1825 internal const string ReadAsync = "ReadAsync";
1826 internal const string Remove = "Remove";
1827 internal const string RollbackTransaction = "RollbackTransaction";
1828 internal const string SaveTransaction = "SaveTransaction";
1829 internal const string SetProperties = "SetProperties";
1830 internal const string SourceColumn = "SourceColumn";
1831 internal const string SourceVersion = "SourceVersion";
1832 internal const string SourceTable = "SourceTable";
1833 internal const string UnquoteIdentifier = "UnquoteIdentifier";
1834 internal const string Update = "Update";
1835 internal const string UpdateCommand = "UpdateCommand";
1836 internal const string UpdateRows = "UpdateRows";
1838 internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
1839 internal const int DecimalMaxPrecision = 29;
1840 internal const int DecimalMaxPrecision28 = 28; // there are some cases in Odbc where we need that ...
1841 internal const int DefaultCommandTimeout = 30;
1842 internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
1843 internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
1844 internal const float FailoverTimeoutStepForTnir = 0.125F; // Fraction of timeout to use in case of Transparent Network IP resolution.
1845 internal const int MinimumTimeoutForTnirMs = 500; // The first login attempt in Transparent network IP Resolution
1847 // security issue, don't rely upon static public readonly values - AS/URT 109635
1848 static internal readonly String StrEmpty = ""; // String.Empty
1850 static internal readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
1851 static internal readonly int PtrSize = IntPtr.Size;
1852 static internal readonly IntPtr InvalidPtr = new IntPtr(-1); // use for INVALID_HANDLE
1853 static internal readonly IntPtr RecordsUnaffected = new IntPtr(-1);
1855 static internal readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
1857 internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
1859 static internal bool CompareInsensitiveInvariant(string strvalue, string strconst) {
1860 return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase));
1863 static internal Delegate FindBuilder(MulticastDelegate mcd) { // V1.2.3300
1865 Delegate[] d = mcd.GetInvocationList();
1866 for (int i = 0; i < d.Length; i++) {
1867 if (d[i].Target is DbCommandBuilder)
1875 static internal readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform);
1876 static internal readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
1878 static internal SysTx.Transaction GetCurrentTransaction() {
1879 SysTx.Transaction transaction = SysTx.Transaction.Current;
1883 static internal void SetCurrentTransaction(SysTx.Transaction transaction)
1885 SysTx.Transaction.Current = transaction;
1888 static internal SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction){
1889 SysTx.IDtcTransaction oleTxTransaction = null;
1891 if (null != transaction) {
1892 oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction);
1894 return oleTxTransaction;
1897 [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
1898 static internal bool IsSysTxEqualSysEsTransaction() {
1902 // This Method won't JIT inproc (ES isn't available), so we code it
1903 // separately and call it behind an if statement.
1904 bool result = (!SysES.ContextUtil.IsInTransaction && null == SysTx.Transaction.Current)
1905 || (SysES.ContextUtil.IsInTransaction && SysTx.Transaction.Current == (SysTx.Transaction)SysES.ContextUtil.SystemTransaction);
1910 static internal bool NeedManualEnlistment() {
1911 #if !MOBILE && !MONO_PARTIAL_DATA_IMPORT
1912 // We need to force a manual enlistment of transactions for ODBC and
1913 // OLEDB whenever the current SysTx transaction != the SysTx transaction
1914 // on the EnterpriseServices ContextUtil, or when ES.ContextUtil is
1915 // not available and there is a non-null current SysTx transaction.
1916 if (IsWindowsNT) { // we can reference SysTx just not use it on Win9X, we can't ever reference SysES on Win9X
1917 bool isEnterpriseServicesOK = !InOutOfProcHelper.InProc;
1918 if ((isEnterpriseServicesOK && !IsSysTxEqualSysEsTransaction())
1919 || (!isEnterpriseServicesOK && null != SysTx.Transaction.Current)) {
1927 static internal void TimerCurrent(out long ticks) {
1928 ticks = DateTime.UtcNow.ToFileTimeUtc();
1931 static internal long TimerCurrent() {
1932 return DateTime.UtcNow.ToFileTimeUtc();
1935 static internal long TimerFromSeconds(int seconds) {
1936 long result = checked((long)seconds * TimeSpan.TicksPerSecond);
1940 static internal long TimerFromMilliseconds(long milliseconds) {
1941 long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
1945 static internal bool TimerHasExpired(long timerExpire) {
1946 bool result = TimerCurrent() > timerExpire;
1950 static internal long TimerRemaining(long timerExpire) {
1951 long timerNow = TimerCurrent();
1952 long result = checked(timerExpire - timerNow);
1956 static internal long TimerRemainingMilliseconds(long timerExpire) {
1957 long result = TimerToMilliseconds(TimerRemaining(timerExpire));
1961 static internal long TimerRemainingSeconds(long timerExpire) {
1962 long result = TimerToSeconds(TimerRemaining(timerExpire));
1966 static internal long TimerToMilliseconds(long timerValue) {
1967 long result = timerValue / TimeSpan.TicksPerMillisecond;
1971 static private long TimerToSeconds(long timerValue) {
1972 long result = timerValue / TimeSpan.TicksPerSecond;
1976 [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")]
1977 static internal string MachineName()
1979 // Note: In Longhorn you'll be able to rename a machine without
1980 // rebooting. Therefore, don't cache this machine name.
1981 return Environment.MachineName;
1984 static internal string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) {
1985 StringBuilder resultString = new StringBuilder();
1986 if (ADP.IsEmpty(quotePrefix) == false) {
1987 resultString.Append(quotePrefix);
1990 // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
1991 if (ADP.IsEmpty(quoteSuffix) == false) {
1992 resultString.Append(unQuotedString.Replace(quoteSuffix,quoteSuffix+quoteSuffix));
1993 resultString.Append(quoteSuffix);
1996 resultString.Append(unQuotedString);
1999 return resultString.ToString();
2002 private const string hexDigits = "0123456789abcdef";
2004 static internal byte[] ByteArrayFromString(string hexString, string dataTypeName) {
2005 if ((hexString.Length & 0x1) != 0) {
2006 throw ADP.LiteralValueIsInvalid(dataTypeName);
2008 char[] c = hexString.ToCharArray();
2009 byte[] b = new byte[hexString.Length / 2];
2011 CultureInfo invariant = CultureInfo.InvariantCulture;
2012 for (int i = 0; i < hexString.Length; i += 2) {
2013 int h = hexDigits.IndexOf(Char.ToLower(c[i], invariant));
2014 int l = hexDigits.IndexOf(Char.ToLower(c[i+1], invariant));
2016 if (h < 0 || l < 0) {
2017 throw ADP.LiteralValueIsInvalid(dataTypeName);
2019 b[i/2] = (byte)((h << 4) | l);
2024 static internal void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString){
2026 // note special characters list is from character escapes
2027 // in the MSDN regular expression language elements documentation
2028 // added ] since escaping it seems necessary
2029 const string specialCharacters = ".$^{[(|)*+?\\]";
2031 foreach (char currentChar in unescapedString){
2032 if (specialCharacters.IndexOf(currentChar) >= 0) {
2033 escapedString.Append("\\");
2035 escapedString.Append(currentChar);
2043 static internal string FixUpDecimalSeparator(string numericString,
2044 Boolean formatLiteral,
2045 string decimalSeparator,
2046 char[] exponentSymbols) {
2047 String returnString;
2048 // don't replace the decimal separator if the string is in exponent format
2049 if (numericString.IndexOfAny(exponentSymbols) == -1){
2051 // if the user has set a decimal separator use it, if not use the current culture's value
2052 if (ADP.IsEmpty(decimalSeparator) == true) {
2053 decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
2055 if (formatLiteral == true){
2056 returnString = numericString.Replace(".",decimalSeparator);
2059 returnString = numericString.Replace(decimalSeparator,".");
2063 returnString = numericString;
2065 return returnString;
2068 [FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
2069 [ResourceExposure(ResourceScope.Machine)]
2070 [ResourceConsumption(ResourceScope.Machine)]
2071 static internal string GetFullPath(string filename) { // MDAC 77686
2072 return Path.GetFullPath(filename);
2076 static internal string GetComputerNameDnsFullyQualified() {
2077 const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT
2078 const int ERROR_MORE_DATA = 234; // winerror.h
2082 value = ADP.MachineName();
2084 if (IsPlatformNT5) {
2085 int length = 0; // length parameter must be zero if buffer is null
2086 // query for the required length
2087 // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive
2088 int getComputerNameExError = 0;
2089 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) {
2090 getComputerNameExError = Marshal.GetLastWin32Error();
2092 if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) {
2093 throw ADP.ComputerNameEx(getComputerNameExError);
2096 StringBuilder buffer = new StringBuilder(length);
2097 length = buffer.Capacity;
2098 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) {
2099 throw ADP.ComputerNameEx(Marshal.GetLastWin32Error());
2102 // Note: In Longhorn you'll be able to rename a machine without
2103 // rebooting. Therefore, don't cache this machine name.
2104 value = buffer.ToString();
2107 value = ADP.MachineName();
2114 // SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously
2115 [ResourceExposure(ResourceScope.Machine)]
2116 [ResourceConsumption(ResourceScope.Machine)]
2117 static internal Stream GetFileStream(string filename) {
2118 #if MONO_FEATURE_CAS
2119 (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert();
2121 return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2124 FileIOPermission.RevertAssert();
2127 return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2131 [ResourceExposure(ResourceScope.Machine)]
2132 [ResourceConsumption(ResourceScope.Machine)]
2133 static internal FileVersionInfo GetVersionInfo(string filename) {
2134 #if MONO_FEATURE_CAS
2135 (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); // MDAC 62038
2137 return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2140 FileIOPermission.RevertAssert();
2143 return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2148 static internal object LocalMachineRegistryValue(string subkey, string queryvalue) {
2152 [ResourceExposure(ResourceScope.Machine)]
2153 [ResourceConsumption(ResourceScope.Machine)]
2154 static internal Stream GetXmlStreamFromValues(String[] values, String errorString) {
2155 if (values.Length != 1){
2156 throw ADP.ConfigWrongNumberOfValues(errorString);
2158 return ADP.GetXmlStream(values[0],errorString);
2161 // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
2162 // this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata
2163 // under the runtime folder.
2164 // This method returns stream to open file, so its ResourceExposure value is ResourceScope.Machine.
2165 [ResourceExposure(ResourceScope.Machine)]
2166 [ResourceConsumption(ResourceScope.Machine)]
2167 static internal Stream GetXmlStream(String value, String errorString) {
2169 const string config = "config\\";
2170 // get location of config directory
2171 string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
2172 if (rootPath == null) {
2173 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2175 StringBuilder tempstring = new StringBuilder(rootPath.Length+config.Length+value.Length);
2176 tempstring.Append(rootPath);
2177 tempstring.Append(config);
2178 tempstring.Append(value);
2179 String fullPath = tempstring.ToString();
2181 // don't allow relative paths
2182 if (ADP.GetFullPath(fullPath) != fullPath) {
2183 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2187 XmlStream = ADP.GetFileStream(fullPath);
2191 if (!ADP.IsCatchableExceptionType(e)) {
2194 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2201 [ResourceExposure(ResourceScope.Machine)]
2202 [ResourceConsumption(ResourceScope.Machine)]
2203 static internal object ClassesRootRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2204 (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CLASSES_ROOT\\" + subkey)).Assert(); // MDAC 62028
2206 using(RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) {
2207 return ((null != key) ? key.GetValue(queryvalue) : null);
2210 catch(SecurityException e) {
2211 // Even though we assert permission - it's possible there are
2212 // ACL's on registry that cause SecurityException to be thrown.
2213 ADP.TraceExceptionWithoutRethrow(e);
2217 RegistryPermission.RevertAssert();
2221 [ResourceExposure(ResourceScope.Machine)]
2222 [ResourceConsumption(ResourceScope.Machine)]
2223 static internal object LocalMachineRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2224 (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028
2226 using(RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) {
2227 return ((null != key) ? key.GetValue(queryvalue) : null);
2230 catch(SecurityException e) {
2231 // Even though we assert permission - it's possible there are
2232 // ACL's on registry that cause SecurityException to be thrown.
2233 ADP.TraceExceptionWithoutRethrow(e);
2237 RegistryPermission.RevertAssert();
2241 // SxS: although this method uses registry, it does not expose anything out
2242 [ResourceExposure(ResourceScope.None)]
2243 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2244 static internal void CheckVersionMDAC(bool ifodbcelseoledb) {
2245 // we don't have that version info on the registry implementation, so it won't work.
2246 if (Environment.OSVersion.Platform == PlatformID.Unix)
2248 int major, minor, build;
2252 version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer");
2253 if (ADP.IsEmpty(version)) {
2254 string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, ADP.StrEmpty);
2255 FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); // MDAC 60411
2256 major = versionInfo.FileMajorPart;
2257 minor = versionInfo.FileMinorPart;
2258 build = versionInfo.FileBuildPart;
2259 version = versionInfo.FileVersion;
2262 string[] parts = version.Split('.');
2263 major = Int32.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture);
2264 minor = Int32.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture);
2265 build = Int32.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture);
2266 Int32.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture);
2269 catch(Exception e) {
2271 if (!ADP.IsCatchableExceptionType(e)) {
2275 throw System.Data.OleDb.ODB.MDACNotAvailable(e);
2278 // disallow any MDAC version before MDAC 2.6 rtm
2279 // include MDAC 2.51 that ships with Win2k
2280 if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526))))) { // MDAC 66628
2281 if (ifodbcelseoledb) {
2282 throw ADP.DataAdapter(Res.GetString(Res.Odbc_MDACWrongVersion, version));
2285 throw ADP.DataAdapter(Res.GetString(Res.OleDb_MDACWrongVersion, version));
2290 // the return value is true if the string was quoted and false if it was not
2291 // this allows the caller to determine if it is an error or not for the quotedString to not be quoted
2292 static internal Boolean RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) {
2295 if (quotePrefix == null){
2299 prefixLength = quotePrefix.Length;
2303 if (quoteSuffix == null){
2307 suffixLength = quoteSuffix.Length;
2310 if ((suffixLength + prefixLength) == 0) {
2311 unquotedString = quotedString;
2315 if (quotedString == null){
2316 unquotedString = quotedString;
2320 int quotedStringLength = quotedString.Length;
2322 // is the source string too short to be quoted
2323 if (quotedStringLength < prefixLength + suffixLength){
2324 unquotedString = quotedString;
2328 // is the prefix present?
2329 if ( prefixLength > 0) {
2330 if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false){
2331 unquotedString = quotedString;
2336 // is the suffix present?
2337 if ( suffixLength > 0) {
2338 if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false){
2339 unquotedString = quotedString;
2342 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix+quoteSuffix,quoteSuffix);
2345 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - prefixLength);
2350 static internal DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) {
2351 const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
2353 // equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
2354 int countAdded = 0, countDeleted = 0, countModifed = 0;
2355 DataRowCollection rowCollection = dataTable.Rows;
2356 foreach(DataRow dataRow in rowCollection) {
2357 switch(dataRow.RowState) {
2358 case DataRowState.Added:
2361 case DataRowState.Deleted:
2364 case DataRowState.Modified:
2368 Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2372 DataRow[] dataRows = new DataRow[countAdded + countDeleted + countModifed];
2374 countModifed = countAdded + countDeleted;
2375 countDeleted = countAdded;
2378 foreach(DataRow dataRow in rowCollection) {
2379 switch(dataRow.RowState) {
2380 case DataRowState.Added:
2381 dataRows[countAdded++] = dataRow;
2383 case DataRowState.Deleted:
2384 dataRows[countDeleted++] = dataRow;
2386 case DataRowState.Modified:
2387 dataRows[countModifed++] = dataRow;
2390 Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2397 foreach(DataRow dataRow in rowCollection) {
2398 if (0 != (dataRow.RowState & rowStates)) {
2399 dataRows[index++] = dataRow;
2400 if (index == dataRows.Length) {
2409 internal static int StringLength(string inputString) {
2410 return ((null != inputString) ? inputString.Length : 0);
2413 // { "a", "a", "a" } -> { "a", "a1", "a2" }
2414 // { "a", "a", "a1" } -> { "a", "a2", "a1" }
2415 // { "a", "A", "a" } -> { "a", "A1", "a2" }
2416 // { "a", "A", "a1" } -> { "a", "A2", "a1" } // MDAC 66718
2417 static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray) {
2418 Dictionary<string,int> hash = new Dictionary<string,int>(columnNameArray.Length);
2420 int startIndex = columnNameArray.Length; // lowest non-unique index
2421 for (int i = columnNameArray.Length - 1; 0 <= i; --i) {
2422 string columnName = columnNameArray[i];
2423 if ((null != columnName) && (0 < columnName.Length)) {
2424 columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2426 if (hash.TryGetValue(columnName, out index)) {
2427 startIndex = Math.Min(startIndex, index);
2429 hash[columnName] = i;
2432 columnNameArray[i] = ADP.StrEmpty; // MDAC 66681
2436 int uniqueIndex = 1;
2437 for (int i = startIndex; i < columnNameArray.Length; ++i) {
2438 string columnName = columnNameArray[i];
2439 if (0 == columnName.Length) { // generate a unique name
2440 columnNameArray[i] = "Column";
2441 uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
2444 columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2445 if (i != hash[columnName]) {
2446 GenerateUniqueName(hash, ref columnNameArray[i], i, 1); // MDAC 66718
2452 static private int GenerateUniqueName(Dictionary<string,int> hash, ref string columnName, int index, int uniqueIndex) {
2453 for (;; ++uniqueIndex) {
2454 string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
2455 string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); // MDAC 66978
2456 if (!hash.ContainsKey(lowerName)) {
2458 columnName = uniqueName;
2459 hash.Add(lowerName, index);
2466 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2467 static internal IntPtr IntPtrOffset(IntPtr pbase, Int32 offset) {
2468 if (4 == ADP.PtrSize) {
2469 return (IntPtr) checked(pbase.ToInt32() + offset);
2471 Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747
2472 return (IntPtr) checked(pbase.ToInt64() + offset);
2475 static internal int IntPtrToInt32(IntPtr value) {
2476 if (4 == ADP.PtrSize) {
2480 long lval = (long)value;
2481 lval = Math.Min((long)Int32.MaxValue, lval);
2482 lval = Math.Max((long)Int32.MinValue, lval);
2488 static internal int SrcCompare(string strA, string strB) { // this is null safe
2489 return ((strA == strB) ? 0 : 1);
2492 static internal int DstCompare(string strA, string strB) { // this is null safe
2493 return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
2496 static internal bool IsDirection(IDataParameter value, ParameterDirection condition) {
2498 IsDirectionValid(condition);
2500 return (condition == (condition & value.Direction));
2503 static private void IsDirectionValid(ParameterDirection value) {
2504 switch (value) { // @perfnote: Enum.IsDefined
2505 case ParameterDirection.Input:
2506 case ParameterDirection.Output:
2507 case ParameterDirection.InputOutput:
2508 case ParameterDirection.ReturnValue:
2511 throw ADP.InvalidParameterDirection(value);
2516 static internal bool IsEmpty(string str) {
2517 return ((null == str) || (0 == str.Length));
2520 static internal bool IsEmptyArray(string[] array) {
2521 return ((null == array) || (0 == array.Length));
2524 static internal bool IsNull(object value) {
2525 if ((null == value) || (DBNull.Value == value)) {
2528 INullable nullable = (value as INullable);
2529 return ((null != nullable) && nullable.IsNull);
2532 static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) {
2533 if ((value == null) || (value == DBNull.Value)) {
2538 INullable nullable = (value as INullable);
2539 if (nullable != null) {
2540 isNull = nullable.IsNull;
2541 isSqlType = DataStorage.IsSqlType(value.GetType());
2550 private static Version _systemDataVersion;
2551 static internal Version GetAssemblyVersion() {
2552 // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
2553 if (_systemDataVersion == null) {
2554 _systemDataVersion = new Version(ThisAssembly.InformationalVersion);
2557 return _systemDataVersion;
2560 static internal readonly string[] AzureSqlServerEndpoints = {Res.GetString(Res.AZURESQL_GenericEndpoint),
2561 Res.GetString(Res.AZURESQL_GermanEndpoint),
2562 Res.GetString(Res.AZURESQL_UsGovEndpoint),
2563 Res.GetString(Res.AZURESQL_ChinaEndpoint)};
2565 // This method assumes dataSource parameter is in TCP connection string format.
2566 static internal bool IsAzureSqlServerEndpoint(string dataSource)
2568 // remove server port
2569 int i = dataSource.LastIndexOf(',');
2572 dataSource = dataSource.Substring(0, i);
2575 // check for the instance name
2576 i = dataSource.LastIndexOf('\\');
2579 dataSource = dataSource.Substring(0, i);
2582 // trim redundant whitespaces
2583 dataSource = dataSource.Trim();
2585 // check if servername end with any azure endpoints
2586 for (i = 0; i < AzureSqlServerEndpoints.Length; i++)
2588 if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))