1 //------------------------------------------------------------------------------
2 // <copyright file="AdapterUtil.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // <owner current="true" primary="true">[....]</owner>
6 // <owner current="true" primary="false">[....]</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 static internal Task<T> CreatedTaskWithException<T>(Exception ex) {
59 TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
60 completion.SetException(ex);
61 return completion.Task;
64 static internal Task<T> CreatedTaskWithCancellation<T>() {
65 TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
66 completion.SetCanceled();
67 return completion.Task;
70 static internal Exception ExceptionWithStackTrace(Exception e)
75 catch (Exception caught) {
80 // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx)
81 // Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features (See Dev11 Bug #193253)
82 static private Task<bool> _trueTask = null;
83 static internal Task<bool> TrueTask {
85 if (_trueTask == null) {
86 _trueTask = Task.FromResult<bool>(true);
92 static private Task<bool> _falseTask = null;
93 static internal Task<bool> FalseTask {
95 if (_falseTask == null) {
96 _falseTask = Task.FromResult<bool>(false);
102 [BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
103 static private void TraceException(
105 [BidArgumentType(typeof(String))] Exception e) {
106 Debug.Assert(null != e, "TraceException: null Exception");
108 Bid.Trace(trace, e.ToString()); // will include callstack if permission is available
112 static internal void TraceExceptionAsReturnValue(Exception e) {
113 TraceException("<comm.ADP.TraceException|ERR|THROW> '%ls'\n", e);
115 static internal void TraceExceptionForCapture(Exception e) {
116 Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
117 TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
119 static internal void TraceExceptionWithoutRethrow(Exception e) {
120 Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
121 TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
127 static internal ArgumentException Argument(string error) {
128 ArgumentException e = new ArgumentException(error);
129 TraceExceptionAsReturnValue(e);
132 static internal ArgumentException Argument(string error, Exception inner) {
133 ArgumentException e = new ArgumentException(error, inner);
134 TraceExceptionAsReturnValue(e);
137 static internal ArgumentException Argument(string error, string parameter) {
138 ArgumentException e = new ArgumentException(error, parameter);
139 TraceExceptionAsReturnValue(e);
142 static internal ArgumentException Argument(string error, string parameter, Exception inner) {
143 ArgumentException e = new ArgumentException(error, parameter, inner);
144 TraceExceptionAsReturnValue(e);
147 static internal ArgumentNullException ArgumentNull(string parameter) {
148 ArgumentNullException e = new ArgumentNullException(parameter);
149 TraceExceptionAsReturnValue(e);
152 static internal ArgumentNullException ArgumentNull(string parameter, string error) {
153 ArgumentNullException e = new ArgumentNullException(parameter, error);
154 TraceExceptionAsReturnValue(e);
157 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) {
158 ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
159 TraceExceptionAsReturnValue(e);
162 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) {
163 ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
164 TraceExceptionAsReturnValue(e);
167 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) {
168 ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message);
169 TraceExceptionAsReturnValue(e);
173 static internal ConfigurationException Configuration(string message) {
174 ConfigurationException e = new ConfigurationErrorsException(message);
175 TraceExceptionAsReturnValue(e);
178 static internal ConfigurationException Configuration(string message, XmlNode node) {
179 ConfigurationException e = new ConfigurationErrorsException(message, node);
180 TraceExceptionAsReturnValue(e);
184 static internal DataException Data(string message) {
185 DataException e = new DataException(message);
186 TraceExceptionAsReturnValue(e);
189 static internal IndexOutOfRangeException IndexOutOfRange(int value) {
190 IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
191 TraceExceptionAsReturnValue(e);
194 static internal IndexOutOfRangeException IndexOutOfRange(string error) {
195 IndexOutOfRangeException e = new IndexOutOfRangeException(error);
196 TraceExceptionAsReturnValue(e);
199 static internal IndexOutOfRangeException IndexOutOfRange() {
200 IndexOutOfRangeException e = new IndexOutOfRangeException();
201 TraceExceptionAsReturnValue(e);
204 static internal InvalidCastException InvalidCast(string error) {
205 return InvalidCast(error, null);
207 static internal InvalidCastException InvalidCast(string error, Exception inner) {
208 InvalidCastException e = new InvalidCastException(error, inner);
209 TraceExceptionAsReturnValue(e);
212 static internal InvalidOperationException InvalidOperation(string error) {
213 InvalidOperationException e = new InvalidOperationException(error);
214 TraceExceptionAsReturnValue(e);
217 static internal TimeoutException TimeoutException(string error) {
218 TimeoutException e = new TimeoutException(error);
219 TraceExceptionAsReturnValue(e);
222 static internal InvalidOperationException InvalidOperation(string error, Exception inner)
224 InvalidOperationException e = new InvalidOperationException(error, inner);
225 TraceExceptionAsReturnValue(e);
228 static internal NotImplementedException NotImplemented(string error) {
229 NotImplementedException e = new NotImplementedException(error);
230 TraceExceptionAsReturnValue(e);
233 static internal NotSupportedException NotSupported() {
234 NotSupportedException e = new NotSupportedException();
235 TraceExceptionAsReturnValue(e);
238 static internal NotSupportedException NotSupported(string error) {
239 NotSupportedException e = new NotSupportedException(error);
240 TraceExceptionAsReturnValue(e);
243 static internal OverflowException Overflow(string error) {
244 return Overflow(error, null);
246 static internal OverflowException Overflow(string error, Exception inner) {
247 OverflowException e = new OverflowException(error, inner);
248 TraceExceptionAsReturnValue(e);
251 static internal PlatformNotSupportedException PropertyNotSupported(string property) {
252 PlatformNotSupportedException e = new PlatformNotSupportedException(Res.GetString(Res.ADP_PropertyNotSupported, property));
253 TraceExceptionAsReturnValue(e);
256 static internal TypeLoadException TypeLoad(string error) {
257 TypeLoadException e = new TypeLoadException(error);
258 TraceExceptionAsReturnValue(e);
261 static internal InvalidCastException InvalidCast() {
262 InvalidCastException e = new InvalidCastException();
263 TraceExceptionAsReturnValue(e);
266 static internal IOException IO(string error) {
267 IOException e = new IOException(error);
268 TraceExceptionAsReturnValue(e);
271 static internal IOException IO(string error, Exception inner) {
272 IOException e = new IOException(error, inner);
273 TraceExceptionAsReturnValue(e);
276 static internal InvalidOperationException DataAdapter(string error) {
277 return InvalidOperation(error);
279 static internal InvalidOperationException DataAdapter(string error, Exception inner) {
280 return InvalidOperation(error, inner);
282 static private InvalidOperationException Provider(string error) {
283 return InvalidOperation(error);
285 static internal ObjectDisposedException ObjectDisposed(object instance) {
286 ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
287 TraceExceptionAsReturnValue(e);
291 static internal InvalidOperationException MethodCalledTwice(string method) {
292 InvalidOperationException e = new InvalidOperationException(Res.GetString(Res.ADP_CalledTwice, method));
293 TraceExceptionAsReturnValue(e);
297 static internal ArgumentException IncorrectAsyncResult() {
298 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_IncorrectAsyncResult), "AsyncResult");
299 TraceExceptionAsReturnValue(e);
303 static internal ArgumentException SingleValuedProperty(string propertyName, string value) {
304 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_SingleValuedProperty, propertyName, value));
305 TraceExceptionAsReturnValue(e);
309 static internal ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) {
310 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_DoubleValuedProperty, propertyName, value1, value2));
311 TraceExceptionAsReturnValue(e);
315 static internal ArgumentException InvalidPrefixSuffix() {
316 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidPrefixSuffix));
317 TraceExceptionAsReturnValue(e);
321 static internal ArgumentException InvalidMultipartName(string property, string value) {
322 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartName, Res.GetString(property), value));
323 TraceExceptionAsReturnValue(e);
327 static internal ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) {
328 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameQuoteUsage, Res.GetString(property), value));
329 TraceExceptionAsReturnValue(e);
333 static internal ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) {
334 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameToManyParts, Res.GetString(property), value, limit));
335 TraceExceptionAsReturnValue(e);
339 static internal ArgumentException BadParameterName(string parameterName) {
340 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_BadParameterName, parameterName));
341 TraceExceptionAsReturnValue(e);
345 static internal ArgumentException MultipleReturnValue() {
346 ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_MultipleReturnValue));
347 TraceExceptionAsReturnValue(e);
354 static internal void CheckArgumentLength(string value, string parameterName) {
355 CheckArgumentNull(value, parameterName);
356 if (0 == value.Length) {
357 throw Argument(Res.GetString(Res.ADP_EmptyString, parameterName)); // MDAC 94859
360 static internal void CheckArgumentLength(Array value, string parameterName) {
361 CheckArgumentNull(value, parameterName);
362 if (0 == value.Length) {
363 throw Argument(Res.GetString(Res.ADP_EmptyArray, parameterName));
366 static internal void CheckArgumentNull(object value, string parameterName) {
368 throw ArgumentNull(parameterName);
373 // only StackOverflowException & ThreadAbortException are sealed classes
374 static private readonly Type StackOverflowType = typeof(StackOverflowException);
375 static private readonly Type OutOfMemoryType = typeof(OutOfMemoryException);
376 static private readonly Type ThreadAbortType = typeof(ThreadAbortException);
377 static private readonly Type NullReferenceType = typeof(NullReferenceException);
378 static private readonly Type AccessViolationType = typeof(AccessViolationException);
379 static private readonly Type SecurityType = typeof(SecurityException);
381 static internal bool IsCatchableExceptionType (Exception e) {
382 // a 'catchable' exception is defined by what it is not.
383 Debug.Assert(e != null, "Unexpected null exception!");
384 Type type = e.GetType();
386 return ( (type != StackOverflowType) &&
387 (type != OutOfMemoryType) &&
388 (type != ThreadAbortType) &&
389 (type != NullReferenceType) &&
390 (type != AccessViolationType) &&
391 !SecurityType.IsAssignableFrom(type));
394 static internal bool IsCatchableOrSecurityExceptionType(Exception e) {
395 // a 'catchable' exception is defined by what it is not.
396 // since IsCatchableExceptionType defined SecurityException as not 'catchable'
397 // this method will return true for SecurityException has being catchable.
399 // the other way to write this method is, but then SecurityException is checked twice
400 // return ((e is SecurityException) || IsCatchableExceptionType(e));
402 Debug.Assert(e != null, "Unexpected null exception!");
403 Type type = e.GetType();
405 return ( (type != StackOverflowType) &&
406 (type != OutOfMemoryType) &&
407 (type != ThreadAbortType) &&
408 (type != NullReferenceType) &&
409 (type != AccessViolationType));
412 // Invalid Enumeration
414 static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) {
415 return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
418 static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) {
419 return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
422 static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) {
425 case AcceptRejectRule.None:
426 case AcceptRejectRule.Cascade:
427 Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
431 return InvalidEnumerationValue(typeof(AcceptRejectRule), (int) value);
433 // DbCommandBuilder.CatalogLocation
434 static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) {
437 case CatalogLocation.Start:
438 case CatalogLocation.End:
439 Debug.Assert(false, "valid CatalogLocation " + value.ToString());
443 return InvalidEnumerationValue(typeof(CatalogLocation), (int) value);
446 static internal ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) {
448 if ((0 <= (int)value) && ((int)value <= 0x3F)) {
449 Debug.Assert(false, "valid CommandType " + value.ToString());
452 return InvalidEnumerationValue(typeof(CommandBehavior), (int) value);
454 static internal void ValidateCommandBehavior(CommandBehavior value) {
455 if (((int)value < 0) || (0x3F < (int)value)) {
456 throw InvalidCommandBehavior(value);
459 static internal ArgumentException InvalidArgumentLength(string argumentName, int limit) {
460 return Argument(Res.GetString(Res.ADP_InvalidArgumentLength, argumentName, limit));
463 static internal ArgumentException MustBeReadOnly(string argumentName) {
464 return Argument(Res.GetString(Res.ADP_MustBeReadOnly, argumentName));
467 // IDbCommand.CommandType
468 static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) {
471 case CommandType.Text:
472 case CommandType.StoredProcedure:
473 case CommandType.TableDirect:
474 Debug.Assert(false, "valid CommandType " + value.ToString());
478 return InvalidEnumerationValue(typeof(CommandType), (int) value);
481 static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) {
484 case ConflictOption.CompareAllSearchableValues:
485 case ConflictOption.CompareRowVersion:
486 case ConflictOption.OverwriteChanges:
487 Debug.Assert(false, "valid ConflictOption " + value.ToString());
491 return InvalidEnumerationValue(typeof(ConflictOption), (int) value);
494 // IDataAdapter.Update
495 static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) {
498 case DataRowState.Detached:
499 case DataRowState.Unchanged:
500 case DataRowState.Added:
501 case DataRowState.Deleted:
502 case DataRowState.Modified:
503 Debug.Assert(false, "valid DataRowState " + value.ToString());
507 return InvalidEnumerationValue(typeof(DataRowState), (int) value);
510 // IDataParameter.SourceVersion
511 static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) {
514 case DataRowVersion.Default:
515 case DataRowVersion.Current:
516 case DataRowVersion.Original:
517 case DataRowVersion.Proposed:
518 Debug.Assert(false, "valid DataRowVersion " + value.ToString());
522 return InvalidEnumerationValue(typeof(DataRowVersion), (int) value);
525 // IDbConnection.BeginTransaction, OleDbTransaction.Begin
526 static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) {
529 case IsolationLevel.Unspecified:
530 case IsolationLevel.Chaos:
531 case IsolationLevel.ReadUncommitted:
532 case IsolationLevel.ReadCommitted:
533 case IsolationLevel.RepeatableRead:
534 case IsolationLevel.Serializable:
535 case IsolationLevel.Snapshot:
536 Debug.Assert(false, "valid IsolationLevel " + value.ToString());
540 return InvalidEnumerationValue(typeof(IsolationLevel), (int) value);
543 // DBDataPermissionAttribute.KeyRestrictionBehavior
544 static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) {
547 case KeyRestrictionBehavior.PreventUsage:
548 case KeyRestrictionBehavior.AllowOnly:
549 Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
553 return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int) value);
556 // IDataAdapter.FillLoadOption
557 static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) {
560 case LoadOption.OverwriteChanges:
561 case LoadOption.PreserveChanges:
562 case LoadOption.Upsert:
563 Debug.Assert(false, "valid LoadOption " + value.ToString());
567 return InvalidEnumerationValue(typeof(LoadOption), (int) value);
570 // IDataAdapter.MissingMappingAction
571 static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) {
574 case MissingMappingAction.Passthrough:
575 case MissingMappingAction.Ignore:
576 case MissingMappingAction.Error:
577 Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
581 return InvalidEnumerationValue(typeof(MissingMappingAction), (int) value);
584 // IDataAdapter.MissingSchemaAction
585 static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) {
588 case MissingSchemaAction.Add:
589 case MissingSchemaAction.Ignore:
590 case MissingSchemaAction.Error:
591 case MissingSchemaAction.AddWithKey:
592 Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
596 return InvalidEnumerationValue(typeof(MissingSchemaAction), (int) value);
599 // IDataParameter.Direction
600 static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) {
603 case ParameterDirection.Input:
604 case ParameterDirection.Output:
605 case ParameterDirection.InputOutput:
606 case ParameterDirection.ReturnValue:
607 Debug.Assert(false, "valid ParameterDirection " + value.ToString());
611 return InvalidEnumerationValue(typeof(ParameterDirection), (int) value);
614 static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionState value) {
617 case PermissionState.Unrestricted:
618 case PermissionState.None:
619 Debug.Assert(false, "valid PermissionState " + value.ToString());
623 return InvalidEnumerationValue(typeof(PermissionState), (int) value);
626 static internal ArgumentOutOfRangeException InvalidRule(Rule value) {
632 case Rule.SetDefault:
633 Debug.Assert(false, "valid Rule " + value.ToString());
637 return InvalidEnumerationValue(typeof(Rule), (int) value);
640 // IDataAdapter.FillSchema
641 static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) {
644 case SchemaType.Source:
645 case SchemaType.Mapped:
646 Debug.Assert(false, "valid SchemaType " + value.ToString());
650 return InvalidEnumerationValue(typeof(SchemaType), (int) value);
653 // RowUpdatingEventArgs.StatementType
654 static internal ArgumentOutOfRangeException InvalidStatementType(StatementType value) {
657 case StatementType.Select:
658 case StatementType.Insert:
659 case StatementType.Update:
660 case StatementType.Delete:
661 case StatementType.Batch:
662 Debug.Assert(false, "valid StatementType " + value.ToString());
666 return InvalidEnumerationValue(typeof(StatementType), (int) value);
669 // IDbCommand.UpdateRowSource
670 static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) {
673 case UpdateRowSource.None:
674 case UpdateRowSource.OutputParameters:
675 case UpdateRowSource.FirstReturnedRecord:
676 case UpdateRowSource.Both:
677 Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
681 return InvalidEnumerationValue(typeof(UpdateRowSource), (int) value);
684 // RowUpdatingEventArgs.UpdateStatus
685 static internal ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) {
688 case UpdateStatus.Continue:
689 case UpdateStatus.ErrorsOccurred:
690 case UpdateStatus.SkipAllRemainingRows:
691 case UpdateStatus.SkipCurrentRow:
692 Debug.Assert(false, "valid UpdateStatus " + value.ToString());
696 return InvalidEnumerationValue(typeof(UpdateStatus), (int) value);
699 static internal ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) {
700 return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
703 static internal ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method) {
704 return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method);
707 static internal ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value) {
710 case Microsoft.SqlServer.Server.Format.Unknown:
711 case Microsoft.SqlServer.Server.Format.Native:
712 case Microsoft.SqlServer.Server.Format.UserDefined:
713 Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString());
717 return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int) value);
720 static internal ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method) {
721 return ADP.NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method);
725 // DbProviderFactories
727 static internal ArgumentException ConfigProviderNotFound() {
728 return Argument(Res.GetString(Res.ConfigProviderNotFound));
730 static internal InvalidOperationException ConfigProviderInvalid() {
731 return InvalidOperation(Res.GetString(Res.ConfigProviderInvalid));
734 static internal ConfigurationException ConfigProviderNotInstalled() {
735 return Configuration(Res.GetString(Res.ConfigProviderNotInstalled));
737 static internal ConfigurationException ConfigProviderMissing() {
738 return Configuration(Res.GetString(Res.ConfigProviderMissing));
742 // DbProviderConfigurationHandler
744 static internal ConfigurationException ConfigBaseNoChildNodes(XmlNode node) { // Res.Config_base_no_child_nodes
745 return Configuration(Res.GetString(Res.ConfigBaseNoChildNodes), node);
747 static internal ConfigurationException ConfigBaseElementsOnly(XmlNode node) { // Res.Config_base_elements_only
748 return Configuration(Res.GetString(Res.ConfigBaseElementsOnly), node);
750 static internal ConfigurationException ConfigUnrecognizedAttributes(XmlNode node) { // Res.Config_base_unrecognized_attribute
751 return Configuration(Res.GetString(Res.ConfigUnrecognizedAttributes, node.Attributes[0].Name), node);
753 static internal ConfigurationException ConfigUnrecognizedElement(XmlNode node) { // Res.Config_base_unrecognized_element
754 return Configuration(Res.GetString(Res.ConfigUnrecognizedElement), node);
756 static internal ConfigurationException ConfigSectionsUnique(string sectionName) { // Res.Res.ConfigSectionsUnique
757 return Configuration(Res.GetString(Res.ConfigSectionsUnique, sectionName));
759 static internal ConfigurationException ConfigRequiredAttributeMissing(string name, XmlNode node) { // Res.Config_base_required_attribute_missing
760 return Configuration(Res.GetString(Res.ConfigRequiredAttributeMissing, name), node);
762 static internal ConfigurationException ConfigRequiredAttributeEmpty(string name, XmlNode node) { // Res.Config_base_required_attribute_empty
763 return Configuration(Res.GetString(Res.ConfigRequiredAttributeEmpty, name), node);
767 // DbConnectionOptions, DataAccess
769 static internal ArgumentException ConnectionStringSyntax(int index) {
770 return Argument(Res.GetString(Res.ADP_ConnectionStringSyntax, index));
772 static internal ArgumentException KeywordNotSupported(string keyword) {
773 return Argument(Res.GetString(Res.ADP_KeywordNotSupported, keyword));
776 static internal ArgumentException EmptyKeyValue(string keyword) { // MDAC 80715
777 return Argument(Res.GetString(Res.ADP_EmptyKeyValue, keyword));
780 static internal ArgumentException UdlFileError(Exception inner) {
781 return Argument(Res.GetString(Res.ADP_UdlFileError), inner);
783 static internal ArgumentException InvalidUDL() {
784 return Argument(Res.GetString(Res.ADP_InvalidUDL));
786 static internal InvalidOperationException InvalidDataDirectory() {
787 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidDataDirectory));
789 static internal ArgumentException InvalidKeyname(string parameterName) {
790 return Argument(Res.GetString(Res.ADP_InvalidKey), parameterName);
792 static internal ArgumentException InvalidValue(string parameterName) {
793 return Argument(Res.GetString(Res.ADP_InvalidValue), parameterName);
795 static internal ArgumentException InvalidMinMaxPoolSizeValues() {
796 return ADP.Argument(Res.GetString(Res.ADP_InvalidMinMaxPoolSizeValues));
798 static internal ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) {
799 return ADP.Argument(Res.GetString(Res.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
802 static internal InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() {
803 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
806 static internal ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() {
807 return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
810 static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() {
811 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
814 static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() {
815 return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
818 static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndContextConnection()
820 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
823 static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndContextConnection()
825 return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
828 static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndContextConnection() {
829 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndContextConnection));
832 static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() {
833 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity));
836 static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() {
837 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword));
840 static internal Exception InvalidMixedUsageOfAccessTokenAndCredential() {
841 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndCredential));
844 static internal Exception InvalidMixedUsageOfAccessTokenAndAuthentication() {
845 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication));
848 static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() {
849 return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
855 static internal InvalidOperationException NoConnectionString() {
856 return InvalidOperation(Res.GetString(Res.ADP_NoConnectionString));
859 static internal NotImplementedException MethodNotImplemented(string methodName) {
860 NotImplementedException e = new NotImplementedException(methodName);
861 TraceExceptionAsReturnValue(e);
864 static private string ConnectionStateMsg(ConnectionState state) { // MDAC 82165, if the ConnectionState enum to msg the localization looks weird
866 case (ConnectionState.Closed):
867 case (ConnectionState.Connecting|ConnectionState.Broken): // treated the same as closed
868 return Res.GetString(Res.ADP_ConnectionStateMsg_Closed);
869 case (ConnectionState.Connecting):
870 return Res.GetString(Res.ADP_ConnectionStateMsg_Connecting);
871 case (ConnectionState.Open):
872 return Res.GetString(Res.ADP_ConnectionStateMsg_Open);
873 case (ConnectionState.Open|ConnectionState.Executing):
874 return Res.GetString(Res.ADP_ConnectionStateMsg_OpenExecuting);
875 case (ConnectionState.Open|ConnectionState.Fetching):
876 return Res.GetString(Res.ADP_ConnectionStateMsg_OpenFetching);
878 return Res.GetString(Res.ADP_ConnectionStateMsg, state.ToString());
882 static internal ConfigurationException ConfigUnableToLoadXmlMetaDataFile(string settingName){
883 return Configuration(Res.GetString(Res.OleDb_ConfigUnableToLoadXmlMetaDataFile, settingName));
886 static internal ConfigurationException ConfigWrongNumberOfValues(string settingName){
887 return Configuration(Res.GetString(Res.OleDb_ConfigWrongNumberOfValues, settingName));
891 // : DbConnectionOptions, DataAccess, SqlClient
893 static internal Exception InvalidConnectionOptionValue(string key) {
894 return InvalidConnectionOptionValue(key, null);
896 static internal Exception InvalidConnectionOptionValueLength(string key, int limit) {
897 return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValueLength, key, limit));
899 static internal Exception InvalidConnectionOptionValue(string key, Exception inner) {
900 return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValue, key), inner);
902 static internal Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) {
903 return Argument(Res.GetString(Res.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
907 // DBDataPermission, DataAccess, Odbc
909 static internal Exception InvalidXMLBadVersion() {
910 return Argument(Res.GetString(Res.ADP_InvalidXMLBadVersion));
912 static internal Exception NotAPermissionElement() {
913 return Argument(Res.GetString(Res.ADP_NotAPermissionElement));
915 static internal Exception PermissionTypeMismatch() {
916 return Argument(Res.GetString(Res.ADP_PermissionTypeMismatch));
919 static internal Exception WrongType(Type got, Type expected) {
920 return Argument(Res.GetString(Res.SQL_WrongType, got.ToString(), expected.ToString()));
923 static internal Exception OdbcNoTypesFromProvider() {
924 return InvalidOperation(Res.GetString(Res.ADP_OdbcNoTypesFromProvider));
928 // DbConnectionPool and related
930 static internal Exception PooledOpenTimeout() {
931 return ADP.InvalidOperation(Res.GetString(Res.ADP_PooledOpenTimeout));
934 static internal Exception NonPooledOpenTimeout() {
935 return ADP.TimeoutException(Res.GetString(Res.ADP_NonPooledOpenTimeout));
939 // Generic Data Provider Collection
941 static internal ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) {
942 return Argument(Res.GetString(Res.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); // MDAC 68201
944 static internal ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) {
945 return ArgumentNull(parameter, Res.GetString(Res.ADP_CollectionNullValue, collection.Name, itemType.Name));
947 static internal IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) {
948 return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
950 static internal IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) {
951 return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
953 static internal InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) {
954 return InvalidCast(Res.GetString(Res.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
956 static internal Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue) {
957 return Argument(Res.GetString(Res.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue));
959 static internal ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) {
960 return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
962 static internal ArgumentException ParametersIsParent(Type parameterType, ICollection collection) {
963 return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
967 // DbProviderException
969 static internal InvalidOperationException TransactionConnectionMismatch() {
970 return Provider(Res.GetString(Res.ADP_TransactionConnectionMismatch));
972 static internal InvalidOperationException TransactionCompletedButNotDisposed()
974 return Provider(Res.GetString(Res.ADP_TransactionCompletedButNotDisposed));
976 static internal InvalidOperationException TransactionRequired(string method) {
977 return Provider(Res.GetString(Res.ADP_TransactionRequired, method));
980 // IDbDataAdapter.Fill(Schema)
981 static internal InvalidOperationException MissingSelectCommand(string method) {
982 return Provider(Res.GetString(Res.ADP_MissingSelectCommand, method));
986 // AdapterMappingException
988 static private InvalidOperationException DataMapping(string error) {
989 return InvalidOperation(error);
992 // DataColumnMapping.GetDataColumnBySchemaAction
993 static internal InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn) {
994 return DataMapping(Res.GetString(Res.ADP_ColumnSchemaExpression, srcColumn, cacheColumn));
997 // DataColumnMapping.GetDataColumnBySchemaAction
998 static internal InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column) {
999 return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name));
1002 // DataColumnMapping.GetDataColumnBySchemaAction
1003 static internal InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn) {
1004 if (ADP.IsEmpty(tableName)) {
1005 return InvalidOperation(Res.GetString(Res.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn));
1007 return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn));
1010 // DataColumnMappingCollection.GetColumnMappingBySchemaAction
1011 static internal InvalidOperationException MissingColumnMapping(string srcColumn) {
1012 return DataMapping(Res.GetString(Res.ADP_MissingColumnMapping, srcColumn));
1015 // DataTableMapping.GetDataTableBySchemaAction
1016 static internal InvalidOperationException MissingTableSchema(string cacheTable, string srcTable) {
1017 return DataMapping(Res.GetString(Res.ADP_MissingTableSchema, cacheTable, srcTable));
1020 // DataTableMappingCollection.GetTableMappingBySchemaAction
1021 static internal InvalidOperationException MissingTableMapping(string srcTable) {
1022 return DataMapping(Res.GetString(Res.ADP_MissingTableMapping, srcTable));
1025 // DbDataAdapter.Update
1026 static internal InvalidOperationException MissingTableMappingDestination(string dstTable) {
1027 return DataMapping(Res.GetString(Res.ADP_MissingTableMappingDestination, dstTable));
1031 // DataColumnMappingCollection, DataAccess
1033 static internal Exception InvalidSourceColumn(string parameter) {
1034 return Argument(Res.GetString(Res.ADP_InvalidSourceColumn), parameter);
1036 static internal Exception ColumnsAddNullAttempt(string parameter) {
1037 return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping));
1039 static internal Exception ColumnsDataSetColumn(string cacheColumn) {
1040 return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection));
1042 static internal Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection) {
1043 return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1045 static internal Exception ColumnsIndexSource(string srcColumn) {
1046 return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection));
1048 static internal Exception ColumnsIsNotParent(ICollection collection) {
1049 return ParametersIsNotParent(typeof(DataColumnMapping), collection);
1051 static internal Exception ColumnsIsParent(ICollection collection) {
1052 return ParametersIsParent(typeof(DataColumnMapping), collection);
1054 static internal Exception ColumnsUniqueSourceColumn(string srcColumn) {
1055 return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn);
1057 static internal Exception NotADataColumnMapping(object value) {
1058 return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value);
1062 // DataTableMappingCollection, DataAccess
1064 static internal Exception InvalidSourceTable(string parameter) {
1065 return Argument(Res.GetString(Res.ADP_InvalidSourceTable), parameter);
1067 static internal Exception TablesAddNullAttempt(string parameter) {
1068 return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping));
1070 static internal Exception TablesDataSetTable(string cacheTable) {
1071 return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection));
1073 static internal Exception TablesIndexInt32(int index, ITableMappingCollection collection) {
1074 return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1076 static internal Exception TablesIsNotParent(ICollection collection) {
1077 return ParametersIsNotParent(typeof(DataTableMapping), collection);
1079 static internal Exception TablesIsParent(ICollection collection) {
1080 return ParametersIsParent(typeof(DataTableMapping), collection);
1082 static internal Exception TablesSourceIndex(string srcTable) {
1083 return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection));
1085 static internal Exception TablesUniqueSourceTable(string srcTable) {
1086 return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable);
1088 static internal Exception NotADataTableMapping(object value) {
1089 return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value);
1096 static internal InvalidOperationException CommandAsyncOperationCompleted() {
1097 return InvalidOperation(Res.GetString(Res.SQL_AsyncOperationCompleted));
1100 static internal Exception CommandTextRequired(string method) {
1101 return InvalidOperation(Res.GetString(Res.ADP_CommandTextRequired, method));
1104 static internal InvalidOperationException ConnectionRequired(string method) {
1105 return InvalidOperation(Res.GetString(Res.ADP_ConnectionRequired, method));
1107 static internal InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) {
1108 return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
1112 static internal InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand) {
1114 if (isRowUpdatingCommand) {
1115 resource = Res.ADP_ConnectionRequired_Clone;
1118 switch(statementType) {
1119 case StatementType.Insert:
1120 resource = Res.ADP_ConnectionRequired_Insert;
1122 case StatementType.Update:
1123 resource = Res.ADP_ConnectionRequired_Update;
1125 case StatementType.Delete:
1126 resource = Res.ADP_ConnectionRequired_Delete;
1128 case StatementType.Batch:
1129 resource = Res.ADP_ConnectionRequired_Batch;
1132 case StatementType.Select:
1133 Debug.Assert(false, "shouldn't be here");
1137 throw ADP.InvalidStatementType(statementType);
1140 return InvalidOperation(Res.GetString(resource));
1143 static internal InvalidOperationException ConnectionRequired_Res(string method) {
1144 string resource = "ADP_ConnectionRequired_" + method;
1147 case Res.ADP_ConnectionRequired_Fill:
1148 case Res.ADP_ConnectionRequired_FillPage:
1149 case Res.ADP_ConnectionRequired_FillSchema:
1150 case Res.ADP_ConnectionRequired_Update:
1151 case Res.ADP_ConnecitonRequired_UpdateRows:
1154 Debug.Assert(false, "missing resource string: " + resource);
1158 return InvalidOperation(Res.GetString(resource));
1160 static internal InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state) {
1162 if (isRowUpdatingCommand) {
1163 resource = Res.ADP_OpenConnectionRequired_Clone;
1166 switch(statementType) {
1167 case StatementType.Insert:
1168 resource = Res.ADP_OpenConnectionRequired_Insert;
1170 case StatementType.Update:
1171 resource = Res.ADP_OpenConnectionRequired_Update;
1173 case StatementType.Delete:
1174 resource = Res.ADP_OpenConnectionRequired_Delete;
1177 case StatementType.Select:
1178 Debug.Assert(false, "shouldn't be here");
1180 case StatementType.Batch:
1181 Debug.Assert(false, "isRowUpdatingCommand should have been true");
1185 throw ADP.InvalidStatementType(statementType);
1188 return InvalidOperation(Res.GetString(resource, ADP.ConnectionStateMsg(state)));
1191 static internal Exception NoStoredProcedureExists(string sproc) {
1192 return InvalidOperation(Res.GetString(Res.ADP_NoStoredProcedureExists, sproc));
1194 static internal Exception OpenReaderExists() {
1195 return OpenReaderExists(null);
1198 static internal Exception OpenReaderExists(Exception e) {
1199 return InvalidOperation(Res.GetString(Res.ADP_OpenReaderExists), e);
1202 static internal Exception TransactionCompleted() {
1203 return DataAdapter(Res.GetString(Res.ADP_TransactionCompleted));
1209 static internal Exception NonSeqByteAccess(long badIndex, long currIndex, string method) {
1210 return InvalidOperation(Res.GetString(Res.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
1213 static internal Exception NegativeParameter(string parameterName) {
1214 return InvalidOperation(Res.GetString(Res.ADP_NegativeParameter, parameterName));
1217 static internal Exception NumericToDecimalOverflow() {
1218 return InvalidCast(Res.GetString(Res.ADP_NumericToDecimalOverflow));
1222 // Stream, SqlTypes, SqlClient
1225 static internal Exception ExceedsMaxDataLength(long specifiedLength, long maxLength) {
1226 return IndexOutOfRange(Res.GetString(Res.SQL_ExceedsMaxDataLength, specifiedLength.ToString(CultureInfo.InvariantCulture), maxLength.ToString(CultureInfo.InvariantCulture)));
1229 static internal Exception InvalidSeekOrigin(string parameterName) {
1230 return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSeekOrigin), parameterName);
1234 // SqlMetaData, SqlTypes, SqlClient
1236 static internal Exception InvalidImplicitConversion(Type fromtype, string totype) {
1237 return InvalidCast(Res.GetString(Res.ADP_InvalidImplicitConversion, fromtype.Name, totype));
1239 static internal Exception InvalidMetaDataValue() {
1240 return ADP.Argument(Res.GetString(Res.ADP_InvalidMetaDataValue));
1243 static internal Exception NotRowType() {
1244 return InvalidOperation(Res.GetString(Res.ADP_NotRowType));
1250 static internal ArgumentException UnwantedStatementType(StatementType statementType) {
1251 return Argument(Res.GetString(Res.ADP_UnwantedStatementType, statementType.ToString()));
1253 static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) {
1254 return InvalidOperation(Res.GetString(Res.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
1258 // DbDataAdapter.FillSchema
1260 static internal Exception FillSchemaRequiresSourceTableName(string parameter) {
1261 return Argument(Res.GetString(Res.ADP_FillSchemaRequiresSourceTableName), parameter);
1265 // DbDataAdapter.Fill
1267 static internal Exception InvalidMaxRecords(string parameter, int max) {
1268 return Argument(Res.GetString(Res.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter);
1270 static internal Exception InvalidStartRecord(string parameter, int start) {
1271 return Argument(Res.GetString(Res.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter);
1273 static internal Exception FillRequires(string parameter) {
1274 return ArgumentNull(parameter);
1276 static internal Exception FillRequiresSourceTableName(string parameter) {
1277 return Argument(Res.GetString(Res.ADP_FillRequiresSourceTableName), parameter);
1279 static internal Exception FillChapterAutoIncrement() {
1280 return InvalidOperation(Res.GetString(Res.ADP_FillChapterAutoIncrement));
1282 static internal InvalidOperationException MissingDataReaderFieldType(int index) {
1283 return DataAdapter(Res.GetString(Res.ADP_MissingDataReaderFieldType, index));
1285 static internal InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords() {
1286 return DataAdapter(Res.GetString(Res.ADP_OnlyOneTableForStartRecordOrMaxRecords));
1289 // DbDataAdapter.Update
1291 static internal ArgumentNullException UpdateRequiresNonNullDataSet(string parameter) {
1292 return ArgumentNull(parameter);
1294 static internal InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName) {
1295 return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTable, defaultSrcTableName));
1297 static internal InvalidOperationException UpdateRequiresSourceTableName(string srcTable) {
1298 return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTableName, srcTable)); // MDAC 70448
1300 static internal ArgumentNullException UpdateRequiresDataTable(string parameter) {
1301 return ArgumentNull(parameter);
1304 static internal Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows) {
1306 switch(statementType) {
1307 case StatementType.Update:
1308 resource = Res.ADP_UpdateConcurrencyViolation_Update;
1310 case StatementType.Delete:
1311 resource = Res.ADP_UpdateConcurrencyViolation_Delete;
1313 case StatementType.Batch:
1314 resource = Res.ADP_UpdateConcurrencyViolation_Batch;
1317 case StatementType.Select:
1318 case StatementType.Insert:
1319 Debug.Assert(false, "should be here");
1323 throw ADP.InvalidStatementType(statementType);
1325 DBConcurrencyException exception = new DBConcurrencyException(Res.GetString(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows);
1326 TraceExceptionAsReturnValue(exception);
1330 static internal InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand) {
1332 if (isRowUpdatingCommand) {
1333 resource = Res.ADP_UpdateRequiresCommandClone;
1336 switch(statementType) {
1337 case StatementType.Select:
1338 resource = Res.ADP_UpdateRequiresCommandSelect;
1340 case StatementType.Insert:
1341 resource = Res.ADP_UpdateRequiresCommandInsert;
1343 case StatementType.Update:
1344 resource = Res.ADP_UpdateRequiresCommandUpdate;
1346 case StatementType.Delete:
1347 resource = Res.ADP_UpdateRequiresCommandDelete;
1350 case StatementType.Batch:
1351 Debug.Assert(false, "isRowUpdatingCommand should have been true");
1355 throw ADP.InvalidStatementType(statementType);
1358 return InvalidOperation(Res.GetString(resource));
1360 static internal ArgumentException UpdateMismatchRowTable(int i) {
1361 return Argument(Res.GetString(Res.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture)));
1363 static internal DataException RowUpdatedErrors() {
1364 return Data(Res.GetString(Res.ADP_RowUpdatedErrors));
1366 static internal DataException RowUpdatingErrors() {
1367 return Data(Res.GetString(Res.ADP_RowUpdatingErrors));
1369 static internal InvalidOperationException ResultsNotAllowedDuringBatch() {
1370 return DataAdapter(Res.GetString(Res.ADP_ResultsNotAllowedDuringBatch));
1376 static internal Exception InvalidCommandTimeout(int value) {
1377 return Argument(Res.GetString(Res.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout);
1379 static internal Exception DeriveParametersNotSupported(IDbCommand value) {
1380 return DataAdapter(Res.GetString(Res.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
1382 static internal Exception UninitializedParameterSize(int index, Type dataType) {
1383 return InvalidOperation(Res.GetString(Res.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
1385 static internal Exception PrepareParameterType(IDbCommand cmd) {
1386 return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterType, cmd.GetType().Name));
1388 static internal Exception PrepareParameterSize(IDbCommand cmd) {
1389 return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name));
1391 static internal Exception PrepareParameterScale(IDbCommand cmd, string type) {
1392 return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterScale, cmd.GetType().Name, type));
1394 static internal Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) {
1395 return InvalidOperation(Res.GetString(Res.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
1401 static internal Exception ConnectionIsDisabled (Exception InnerException) {
1402 return InvalidOperation(Res.GetString(Res.ADP_ConnectionIsDisabled), InnerException);
1404 static internal Exception ClosedConnectionError() {
1405 return InvalidOperation(Res.GetString(Res.ADP_ClosedConnectionError));
1407 static internal Exception ConnectionAlreadyOpen(ConnectionState state) {
1408 return InvalidOperation(Res.GetString(Res.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
1410 static internal Exception DelegatedTransactionPresent() {
1411 return InvalidOperation(Res.GetString(Res.ADP_DelegatedTransactionPresent));
1413 static internal Exception TransactionPresent() {
1414 return InvalidOperation(Res.GetString(Res.ADP_TransactionPresent));
1416 static internal Exception LocalTransactionPresent() {
1417 return InvalidOperation(Res.GetString(Res.ADP_LocalTransactionPresent));
1419 static internal Exception OpenConnectionPropertySet(string property, ConnectionState state) {
1420 return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
1422 static internal Exception EmptyDatabaseName() {
1423 return Argument(Res.GetString(Res.ADP_EmptyDatabaseName));
1425 static internal Exception DatabaseNameTooLong() {
1426 return Argument(Res.GetString(Res.ADP_DatabaseNameTooLong));
1429 internal enum ConnectionError {
1430 BeginGetConnectionReturnsNull,
1431 GetConnectionReturnsNull,
1432 ConnectionOptionsMissing,
1433 CouldNotSwitchToClosedPreviouslyOpenedState,
1435 static internal Exception InternalConnectionError(ConnectionError internalError) {
1436 return InvalidOperation(Res.GetString(Res.ADP_InternalConnectionError, (int)internalError));
1439 internal enum InternalErrorCode {
1440 UnpooledObjectHasOwner = 0,
1441 UnpooledObjectHasWrongOwner = 1,
1442 PushingObjectSecondTime = 2,
1443 PooledObjectHasOwner = 3,
1444 PooledObjectInPoolMoreThanOnce = 4,
1445 CreateObjectReturnedNull = 5,
1446 NewObjectCannotBePooled = 6,
1447 NonPooledObjectUsedMoreThanOnce = 7,
1448 AttemptingToPoolOnRestrictedToken = 8,
1449 // ConnectionOptionsInUse = 9,
1450 ConvertSidToStringSidWReturnedNull = 10,
1451 // UnexpectedTransactedObject = 11,
1452 AttemptingToConstructReferenceCollectionOnStaticObject = 12,
1453 AttemptingToEnlistTwice = 13,
1454 CreateReferenceCollectionReturnedNull = 14,
1455 PooledObjectWithoutPool = 15,
1456 UnexpectedWaitAnyResult = 16,
1457 SynchronousConnectReturnedPending = 17,
1458 CompletedConnectReturnedPending = 18,
1460 NameValuePairNext = 20,
1461 InvalidParserState1 = 21,
1462 InvalidParserState2 = 22,
1463 InvalidParserState3 = 23,
1467 UnimplementedSMIMethod = 40,
1468 InvalidSmiCall = 41,
1470 SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
1471 SqlDependencyProcessDispatcherFailureCreateInstance = 51,
1472 SqlDependencyProcessDispatcherFailureAppDomain = 52,
1473 SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
1475 UnknownTransactionFailure = 60,
1477 static internal Exception InternalError(InternalErrorCode internalError) {
1478 return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError));
1480 static internal Exception InternalError(InternalErrorCode internalError, Exception innerException) {
1481 return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError), innerException);
1483 static internal Exception InvalidConnectTimeoutValue() {
1484 return Argument(Res.GetString(Res.ADP_InvalidConnectTimeoutValue));
1487 static internal Exception InvalidConnectRetryCountValue() {
1488 return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryCountValue));
1491 static internal Exception InvalidConnectRetryIntervalValue() {
1492 return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryIntervalValue));
1498 static internal Exception DataReaderNoData() {
1499 return InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData));
1501 static internal Exception DataReaderClosed(string method) {
1502 return InvalidOperation(Res.GetString(Res.ADP_DataReaderClosed, method));
1504 static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) {
1505 return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
1507 static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) {
1508 return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
1510 static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) {
1511 return IndexOutOfRange(Res.GetString(Res.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
1513 static internal Exception InvalidDataLength(long length) {
1514 return IndexOutOfRange(Res.GetString(Res.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
1516 static internal InvalidOperationException AsyncOperationPending() {
1517 return InvalidOperation(Res.GetString(Res.ADP_PendingAsyncOperation));
1523 static internal Exception StreamClosed(string method) {
1524 return InvalidOperation(Res.GetString(Res.ADP_StreamClosed, method));
1526 static internal IOException ErrorReadingFromStream(Exception internalException) {
1527 return IO(Res.GetString(Res.SqlMisc_StreamErrorMessage), internalException);
1533 static internal InvalidOperationException DynamicSQLJoinUnsupported() {
1534 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLJoinUnsupported));
1536 static internal InvalidOperationException DynamicSQLNoTableInfo() {
1537 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoTableInfo));
1539 static internal InvalidOperationException DynamicSQLNoKeyInfoDelete() {
1540 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoDelete));
1542 static internal InvalidOperationException DynamicSQLNoKeyInfoUpdate() {
1543 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoUpdate));
1545 static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete() {
1546 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionDelete));
1548 static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate() {
1549 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionUpdate));
1551 static internal InvalidOperationException DynamicSQLNestedQuote(string name, string quote) {
1552 return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNestedQuote, name, quote));
1554 static internal InvalidOperationException NoQuoteChange() {
1555 return InvalidOperation(Res.GetString(Res.ADP_NoQuoteChange));
1557 static internal InvalidOperationException ComputerNameEx(int lastError) {
1558 return InvalidOperation(Res.GetString(Res.ADP_ComputerNameEx, lastError));
1560 static internal InvalidOperationException MissingSourceCommand() {
1561 return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommand));
1563 static internal InvalidOperationException MissingSourceCommandConnection() {
1564 return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommandConnection));
1570 static internal ArgumentException InvalidDataType(TypeCode typecode) {
1571 return Argument(Res.GetString(Res.ADP_InvalidDataType, typecode.ToString()));
1573 static internal ArgumentException UnknownDataType(Type dataType) {
1574 return Argument(Res.GetString(Res.ADP_UnknownDataType, dataType.FullName));
1576 static internal ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype) {
1577 return Argument(Res.GetString(Res.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
1579 static internal ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) {
1580 return Argument(Res.GetString(Res.ADP_UnknownDataTypeCode, ((int) typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
1582 static internal ArgumentException InvalidOffsetValue(int value) {
1583 return Argument(Res.GetString(Res.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
1585 static internal ArgumentException InvalidSizeValue(int value) {
1586 return Argument(Res.GetString(Res.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
1588 static internal ArgumentException ParameterValueOutOfRange(Decimal value) {
1589 return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
1591 static internal ArgumentException ParameterValueOutOfRange(SqlDecimal value) {
1592 return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString()));
1595 static internal ArgumentException ParameterValueOutOfRange(String value) {
1596 return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value));
1599 static internal ArgumentException VersionDoesNotSupportDataType(string typeName) {
1600 return Argument(Res.GetString(Res.ADP_VersionDoesNotSupportDataType, typeName));
1602 static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) { // WebData 75433
1603 Debug.Assert(null != value, "null value on conversion failure");
1604 Debug.Assert(null != inner, "null inner on conversion failure");
1607 string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
1608 if (inner is ArgumentException) {
1609 e = new ArgumentException(message, inner);
1611 else if (inner is FormatException) {
1612 e = new FormatException(message, inner);
1614 else if (inner is InvalidCastException) {
1615 e = new InvalidCastException(message, inner);
1617 else if (inner is OverflowException) {
1618 e = new OverflowException(message, inner);
1623 TraceExceptionAsReturnValue(e);
1628 // : IDataParameterCollection
1630 static internal Exception ParametersMappingIndex(int index, IDataParameterCollection collection) {
1631 return CollectionIndexInt32(index, collection.GetType(), collection.Count);
1633 static internal Exception ParametersSourceIndex(string parameterName, IDataParameterCollection collection, Type parameterType) {
1634 return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
1636 static internal Exception ParameterNull(string parameter, IDataParameterCollection collection, Type parameterType) {
1637 return CollectionNullValue(parameter, collection.GetType(), parameterType);
1639 static internal Exception InvalidParameterType(IDataParameterCollection collection, Type parameterType, object invalidValue) {
1640 return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
1646 static internal Exception ParallelTransactionsNotSupported(IDbConnection obj) {
1647 return InvalidOperation(Res.GetString(Res.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
1649 static internal Exception TransactionZombied(IDbTransaction obj) {
1650 return InvalidOperation(Res.GetString(Res.ADP_TransactionZombied, obj.GetType().Name));
1653 static internal Exception DbRecordReadOnly(string methodname) {
1654 return InvalidOperation(Res.GetString(Res.ADP_DbRecordReadOnly, methodname));
1657 static internal Exception OffsetOutOfRangeException() {
1658 return InvalidOperation(Res.GetString(Res.ADP_OffsetOutOfRangeException));
1662 // : DbMetaDataFactory
1665 static internal Exception AmbigousCollectionName(string collectionName) {
1666 return Argument(Res.GetString(Res.MDF_AmbigousCollectionName,collectionName));
1669 static internal Exception CollectionNameIsNotUnique(string collectionName) {
1670 return Argument(Res.GetString(Res.MDF_CollectionNameISNotUnique,collectionName));
1673 static internal Exception DataTableDoesNotExist(string collectionName) {
1674 return Argument(Res.GetString(Res.MDF_DataTableDoesNotExist,collectionName));
1677 static internal Exception IncorrectNumberOfDataSourceInformationRows() {
1678 return Argument(Res.GetString(Res.MDF_IncorrectNumberOfDataSourceInformationRows));
1681 static internal ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue) {
1682 return ADP.Argument(Res.GetString(Res.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue));
1685 static internal Exception InvalidXml() {
1686 return Argument(Res.GetString(Res.MDF_InvalidXml));
1689 static internal Exception InvalidXmlMissingColumn(string collectionName, string columnName) {
1690 return Argument(Res.GetString(Res.MDF_InvalidXmlMissingColumn, collectionName, columnName));
1693 static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName) {
1694 return Argument(Res.GetString(Res.MDF_InvalidXmlInvalidValue, collectionName, columnName));
1697 static internal Exception MissingDataSourceInformationColumn() {
1698 return Argument(Res.GetString(Res.MDF_MissingDataSourceInformationColumn));
1701 static internal Exception MissingRestrictionColumn() {
1702 return Argument(Res.GetString(Res.MDF_MissingRestrictionColumn));
1705 static internal Exception MissingRestrictionRow() {
1706 return Argument(Res.GetString(Res.MDF_MissingRestrictionRow));
1709 static internal Exception NoColumns() {
1710 return Argument(Res.GetString(Res.MDF_NoColumns));
1713 static internal Exception QueryFailed(string collectionName, Exception e) {
1714 return InvalidOperation(Res.GetString(Res.MDF_QueryFailed,collectionName), e);
1717 static internal Exception TooManyRestrictions(string collectionName) {
1718 return Argument(Res.GetString(Res.MDF_TooManyRestrictions,collectionName));
1721 static internal Exception UnableToBuildCollection(string collectionName) {
1722 return Argument(Res.GetString(Res.MDF_UnableToBuildCollection,collectionName));
1725 static internal Exception UndefinedCollection(string collectionName) {
1726 return Argument(Res.GetString(Res.MDF_UndefinedCollection,collectionName));
1729 static internal Exception UndefinedPopulationMechanism(string populationMechanism) {
1730 return Argument(Res.GetString(Res.MDF_UndefinedPopulationMechanism,populationMechanism));
1733 static internal Exception UnsupportedVersion(string collectionName) {
1734 return Argument(Res.GetString(Res.MDF_UnsupportedVersion,collectionName));
1742 static internal InvalidOperationException InvalidDateTimeDigits(string dataTypeName) {
1743 return InvalidOperation(Res.GetString(Res.ADP_InvalidDateTimeDigits, dataTypeName));
1746 static internal Exception InvalidFormatValue() {
1747 return Argument(Res.GetString(Res.ADP_InvalidFormatValue));
1750 static internal InvalidOperationException InvalidMaximumScale(string dataTypeName) {
1751 return InvalidOperation(Res.GetString(Res.ADP_InvalidMaximumScale, dataTypeName));
1754 static internal Exception LiteralValueIsInvalid(string dataTypeName){
1755 return Argument(Res.GetString(Res.ADP_LiteralValueIsInvalid,dataTypeName));
1758 static internal Exception EvenLengthLiteralValue(string argumentName) {
1759 return Argument(Res.GetString(Res.ADP_EvenLengthLiteralValue), argumentName );
1762 static internal Exception HexDigitLiteralValue(string argumentName) {
1763 return Argument(Res.GetString(Res.ADP_HexDigitLiteralValue), argumentName );
1766 static internal InvalidOperationException QuotePrefixNotSet(string method) {
1767 return InvalidOperation(Res.GetString(Res.ADP_QuotePrefixNotSet, method));
1770 static internal InvalidOperationException UnableToCreateBooleanLiteral() {
1771 return ADP.InvalidOperation(Res.GetString(Res.ADP_UnableToCreateBooleanLiteral));
1774 static internal Exception UnsupportedNativeDataTypeOleDb(string dataTypeName) {
1775 return Argument(Res.GetString(Res.ADP_UnsupportedNativeDataTypeOleDb, dataTypeName));
1778 // Sql Result Set and other generic message
1779 static internal Exception InvalidArgumentValue(string methodName) {
1780 return Argument(Res.GetString(Res.ADP_InvalidArgumentValue, methodName));
1783 // global constant strings
1784 internal const string Append = "Append";
1785 internal const string BeginExecuteNonQuery = "BeginExecuteNonQuery";
1786 internal const string BeginExecuteReader = "BeginExecuteReader";
1787 internal const string BeginTransaction = "BeginTransaction";
1788 internal const string BeginExecuteXmlReader = "BeginExecuteXmlReader";
1789 internal const string ChangeDatabase = "ChangeDatabase";
1790 internal const string Cancel = "Cancel";
1791 internal const string Clone = "Clone";
1792 internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_";
1793 internal const string CommitTransaction = "CommitTransaction";
1794 internal const string CommandTimeout = "CommandTimeout";
1795 internal const string ConnectionString = "ConnectionString";
1796 internal const string DataSetColumn = "DataSetColumn";
1797 internal const string DataSetTable = "DataSetTable";
1798 internal const string Delete = "Delete";
1799 internal const string DeleteCommand = "DeleteCommand";
1800 internal const string DeriveParameters = "DeriveParameters";
1801 internal const string EndExecuteNonQuery = "EndExecuteNonQuery";
1802 internal const string EndExecuteReader = "EndExecuteReader";
1803 internal const string EndExecuteXmlReader = "EndExecuteXmlReader";
1804 internal const string ExecuteReader = "ExecuteReader";
1805 internal const string ExecuteRow = "ExecuteRow";
1806 internal const string ExecuteNonQuery = "ExecuteNonQuery";
1807 internal const string ExecuteScalar = "ExecuteScalar";
1808 internal const string ExecuteSqlScalar = "ExecuteSqlScalar";
1809 internal const string ExecuteXmlReader = "ExecuteXmlReader";
1810 internal const string Fill = "Fill";
1811 internal const string FillPage = "FillPage";
1812 internal const string FillSchema = "FillSchema";
1813 internal const string GetBytes = "GetBytes";
1814 internal const string GetChars = "GetChars";
1815 internal const string GetOleDbSchemaTable = "GetOleDbSchemaTable";
1816 internal const string GetProperties = "GetProperties";
1817 internal const string GetSchema = "GetSchema";
1818 internal const string GetSchemaTable = "GetSchemaTable";
1819 internal const string GetServerTransactionLevel = "GetServerTransactionLevel";
1820 internal const string Insert = "Insert";
1821 internal const string Open = "Open";
1822 internal const string Parameter = "Parameter";
1823 internal const string ParameterBuffer = "buffer";
1824 internal const string ParameterCount = "count";
1825 internal const string ParameterDestinationType = "destinationType";
1826 internal const string ParameterIndex = "index";
1827 internal const string ParameterName = "ParameterName";
1828 internal const string ParameterOffset = "offset";
1829 internal const string ParameterSetPosition = "set_Position";
1830 internal const string ParameterService = "Service";
1831 internal const string ParameterTimeout = "Timeout";
1832 internal const string ParameterUserData = "UserData";
1833 internal const string Prepare = "Prepare";
1834 internal const string QuoteIdentifier = "QuoteIdentifier";
1835 internal const string Read = "Read";
1836 internal const string ReadAsync = "ReadAsync";
1837 internal const string Remove = "Remove";
1838 internal const string RollbackTransaction = "RollbackTransaction";
1839 internal const string SaveTransaction = "SaveTransaction";
1840 internal const string SetProperties = "SetProperties";
1841 internal const string SourceColumn = "SourceColumn";
1842 internal const string SourceVersion = "SourceVersion";
1843 internal const string SourceTable = "SourceTable";
1844 internal const string UnquoteIdentifier = "UnquoteIdentifier";
1845 internal const string Update = "Update";
1846 internal const string UpdateCommand = "UpdateCommand";
1847 internal const string UpdateRows = "UpdateRows";
1849 internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
1850 internal const int DecimalMaxPrecision = 29;
1851 internal const int DecimalMaxPrecision28 = 28; // there are some cases in Odbc where we need that ...
1852 internal const int DefaultCommandTimeout = 30;
1853 internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
1854 internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
1855 internal const int FirstTransparentAttemptTimeout = 500; // The first login attempt in Transparent network IP Resolution
1857 // security issue, don't rely upon static public readonly values - AS/URT 109635
1858 static internal readonly String StrEmpty = ""; // String.Empty
1860 static internal readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
1861 static internal readonly int PtrSize = IntPtr.Size;
1862 static internal readonly IntPtr InvalidPtr = new IntPtr(-1); // use for INVALID_HANDLE
1863 static internal readonly IntPtr RecordsUnaffected = new IntPtr(-1);
1865 static internal readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
1867 internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
1869 static internal bool CompareInsensitiveInvariant(string strvalue, string strconst) {
1870 return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase));
1873 static internal Delegate FindBuilder(MulticastDelegate mcd) { // V1.2.3300
1875 Delegate[] d = mcd.GetInvocationList();
1876 for (int i = 0; i < d.Length; i++) {
1877 if (d[i].Target is DbCommandBuilder)
1885 static internal readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform);
1886 static internal readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
1888 static internal SysTx.Transaction GetCurrentTransaction() {
1889 SysTx.Transaction transaction = SysTx.Transaction.Current;
1893 static internal void SetCurrentTransaction(SysTx.Transaction transaction)
1895 SysTx.Transaction.Current = transaction;
1898 static internal SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction){
1899 SysTx.IDtcTransaction oleTxTransaction = null;
1901 if (null != transaction) {
1902 oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction);
1904 return oleTxTransaction;
1907 [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
1908 static internal bool IsSysTxEqualSysEsTransaction() {
1912 // This Method won't JIT inproc (ES isn't available), so we code it
1913 // separately and call it behind an if statement.
1914 bool result = (!SysES.ContextUtil.IsInTransaction && null == SysTx.Transaction.Current)
1915 || (SysES.ContextUtil.IsInTransaction && SysTx.Transaction.Current == (SysTx.Transaction)SysES.ContextUtil.SystemTransaction);
1920 static internal bool NeedManualEnlistment() {
1921 #if !MOBILE && !MONO_PARTIAL_DATA_IMPORT
1922 // We need to force a manual enlistment of transactions for ODBC and
1923 // OLEDB whenever the current SysTx transaction != the SysTx transaction
1924 // on the EnterpriseServices ContextUtil, or when ES.ContextUtil is
1925 // not available and there is a non-null current SysTx transaction.
1926 if (IsWindowsNT) { // we can reference SysTx just not use it on Win9X, we can't ever reference SysES on Win9X
1927 bool isEnterpriseServicesOK = !InOutOfProcHelper.InProc;
1928 if ((isEnterpriseServicesOK && !IsSysTxEqualSysEsTransaction())
1929 || (!isEnterpriseServicesOK && null != SysTx.Transaction.Current)) {
1937 static internal void TimerCurrent(out long ticks) {
1938 ticks = DateTime.UtcNow.ToFileTimeUtc();
1941 static internal long TimerCurrent() {
1942 return DateTime.UtcNow.ToFileTimeUtc();
1945 static internal long TimerFromSeconds(int seconds) {
1946 long result = checked((long)seconds * TimeSpan.TicksPerSecond);
1950 static internal long TimerFromMilliseconds(long milliseconds) {
1951 long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
1955 static internal bool TimerHasExpired(long timerExpire) {
1956 bool result = TimerCurrent() > timerExpire;
1960 static internal long TimerRemaining(long timerExpire) {
1961 long timerNow = TimerCurrent();
1962 long result = checked(timerExpire - timerNow);
1966 static internal long TimerRemainingMilliseconds(long timerExpire) {
1967 long result = TimerToMilliseconds(TimerRemaining(timerExpire));
1971 static internal long TimerRemainingSeconds(long timerExpire) {
1972 long result = TimerToSeconds(TimerRemaining(timerExpire));
1976 static internal long TimerToMilliseconds(long timerValue) {
1977 long result = timerValue / TimeSpan.TicksPerMillisecond;
1981 static private long TimerToSeconds(long timerValue) {
1982 long result = timerValue / TimeSpan.TicksPerSecond;
1986 [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")]
1987 static internal string MachineName()
1989 // Note: In Longhorn you'll be able to rename a machine without
1990 // rebooting. Therefore, don't cache this machine name.
1991 return Environment.MachineName;
1994 static internal string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) {
1995 StringBuilder resultString = new StringBuilder();
1996 if (ADP.IsEmpty(quotePrefix) == false) {
1997 resultString.Append(quotePrefix);
2000 // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
2001 if (ADP.IsEmpty(quoteSuffix) == false) {
2002 resultString.Append(unQuotedString.Replace(quoteSuffix,quoteSuffix+quoteSuffix));
2003 resultString.Append(quoteSuffix);
2006 resultString.Append(unQuotedString);
2009 return resultString.ToString();
2012 private static readonly string hexDigits = "0123456789abcdef";
2014 static internal byte[] ByteArrayFromString(string hexString, string dataTypeName) {
2015 if ((hexString.Length & 0x1) != 0) {
2016 throw ADP.LiteralValueIsInvalid(dataTypeName);
2018 char[] c = hexString.ToCharArray();
2019 byte[] b = new byte[hexString.Length / 2];
2021 CultureInfo invariant = CultureInfo.InvariantCulture;
2022 for (int i = 0; i < hexString.Length; i += 2) {
2023 int h = hexDigits.IndexOf(Char.ToLower(c[i], invariant));
2024 int l = hexDigits.IndexOf(Char.ToLower(c[i+1], invariant));
2026 if (h < 0 || l < 0) {
2027 throw ADP.LiteralValueIsInvalid(dataTypeName);
2029 b[i/2] = (byte)((h << 4) | l);
2034 static internal void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString){
2036 // note special characters list is from character escapes
2037 // in the MSDN regular expression language elements documentation
2038 // added ] since escaping it seems necessary
2039 const string specialCharacters = ".$^{[(|)*+?\\]";
2041 foreach (char currentChar in unescapedString){
2042 if (specialCharacters.IndexOf(currentChar) >= 0) {
2043 escapedString.Append("\\");
2045 escapedString.Append(currentChar);
2053 static internal string FixUpDecimalSeparator(string numericString,
2054 Boolean formatLiteral,
2055 string decimalSeparator,
2056 char[] exponentSymbols) {
2057 String returnString;
2058 // don't replace the decimal separator if the string is in exponent format
2059 if (numericString.IndexOfAny(exponentSymbols) == -1){
2061 // if the user has set a decimal separator use it, if not use the current culture's value
2062 if (ADP.IsEmpty(decimalSeparator) == true) {
2063 decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
2065 if (formatLiteral == true){
2066 returnString = numericString.Replace(".",decimalSeparator);
2069 returnString = numericString.Replace(decimalSeparator,".");
2073 returnString = numericString;
2075 return returnString;
2078 [FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
2079 [ResourceExposure(ResourceScope.Machine)]
2080 [ResourceConsumption(ResourceScope.Machine)]
2081 static internal string GetFullPath(string filename) { // MDAC 77686
2082 return Path.GetFullPath(filename);
2086 static internal string GetComputerNameDnsFullyQualified() {
2087 const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT
2088 const int ERROR_MORE_DATA = 234; // winerror.h
2092 value = ADP.MachineName();
2094 if (IsPlatformNT5) {
2095 int length = 0; // length parameter must be zero if buffer is null
2096 // query for the required length
2097 // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive
2098 int getComputerNameExError = 0;
2099 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) {
2100 getComputerNameExError = Marshal.GetLastWin32Error();
2102 if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) {
2103 throw ADP.ComputerNameEx(getComputerNameExError);
2106 StringBuilder buffer = new StringBuilder(length);
2107 length = buffer.Capacity;
2108 if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) {
2109 throw ADP.ComputerNameEx(Marshal.GetLastWin32Error());
2112 // Note: In Longhorn you'll be able to rename a machine without
2113 // rebooting. Therefore, don't cache this machine name.
2114 value = buffer.ToString();
2117 value = ADP.MachineName();
2124 // SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously
2125 [ResourceExposure(ResourceScope.Machine)]
2126 [ResourceConsumption(ResourceScope.Machine)]
2127 static internal Stream GetFileStream(string filename) {
2128 #if MONO_FEATURE_CAS
2129 (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert();
2131 return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2134 FileIOPermission.RevertAssert();
2137 return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
2141 [ResourceExposure(ResourceScope.Machine)]
2142 [ResourceConsumption(ResourceScope.Machine)]
2143 static internal FileVersionInfo GetVersionInfo(string filename) {
2144 #if MONO_FEATURE_CAS
2145 (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); // MDAC 62038
2147 return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2150 FileIOPermission.RevertAssert();
2153 return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
2158 static internal object LocalMachineRegistryValue(string subkey, string queryvalue) {
2162 [ResourceExposure(ResourceScope.Machine)]
2163 [ResourceConsumption(ResourceScope.Machine)]
2164 static internal Stream GetXmlStreamFromValues(String[] values, String errorString) {
2165 if (values.Length != 1){
2166 throw ADP.ConfigWrongNumberOfValues(errorString);
2168 return ADP.GetXmlStream(values[0],errorString);
2171 // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
2172 // this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata
2173 // under the runtime folder.
2174 // This method returns stream to open file, so its ResourceExposure value is ResourceScope.Machine.
2175 [ResourceExposure(ResourceScope.Machine)]
2176 [ResourceConsumption(ResourceScope.Machine)]
2177 static internal Stream GetXmlStream(String value, String errorString) {
2179 const string config = "config\\";
2180 // get location of config directory
2181 string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
2182 if (rootPath == null) {
2183 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2185 StringBuilder tempstring = new StringBuilder(rootPath.Length+config.Length+value.Length);
2186 tempstring.Append(rootPath);
2187 tempstring.Append(config);
2188 tempstring.Append(value);
2189 String fullPath = tempstring.ToString();
2191 // don't allow relative paths
2192 if (ADP.GetFullPath(fullPath) != fullPath) {
2193 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2197 XmlStream = ADP.GetFileStream(fullPath);
2201 if (!ADP.IsCatchableExceptionType(e)) {
2204 throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
2211 [ResourceExposure(ResourceScope.Machine)]
2212 [ResourceConsumption(ResourceScope.Machine)]
2213 static internal object ClassesRootRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2214 (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CLASSES_ROOT\\" + subkey)).Assert(); // MDAC 62028
2216 using(RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) {
2217 return ((null != key) ? key.GetValue(queryvalue) : null);
2220 catch(SecurityException e) {
2221 // Even though we assert permission - it's possible there are
2222 // ACL's on registry that cause SecurityException to be thrown.
2223 ADP.TraceExceptionWithoutRethrow(e);
2227 RegistryPermission.RevertAssert();
2231 [ResourceExposure(ResourceScope.Machine)]
2232 [ResourceConsumption(ResourceScope.Machine)]
2233 static internal object LocalMachineRegistryValue(string subkey, string queryvalue) { // MDAC 77697
2234 (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028
2236 using(RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) {
2237 return ((null != key) ? key.GetValue(queryvalue) : null);
2240 catch(SecurityException e) {
2241 // Even though we assert permission - it's possible there are
2242 // ACL's on registry that cause SecurityException to be thrown.
2243 ADP.TraceExceptionWithoutRethrow(e);
2247 RegistryPermission.RevertAssert();
2251 // SxS: although this method uses registry, it does not expose anything out
2252 [ResourceExposure(ResourceScope.None)]
2253 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2254 static internal void CheckVersionMDAC(bool ifodbcelseoledb) {
2255 // we don't have that version info on the registry implementation, so it won't work.
2256 if (Environment.OSVersion.Platform == PlatformID.Unix)
2258 int major, minor, build;
2262 version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer");
2263 if (ADP.IsEmpty(version)) {
2264 string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, ADP.StrEmpty);
2265 FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); // MDAC 60411
2266 major = versionInfo.FileMajorPart;
2267 minor = versionInfo.FileMinorPart;
2268 build = versionInfo.FileBuildPart;
2269 version = versionInfo.FileVersion;
2272 string[] parts = version.Split('.');
2273 major = Int32.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture);
2274 minor = Int32.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture);
2275 build = Int32.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture);
2276 Int32.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture);
2279 catch(Exception e) {
2281 if (!ADP.IsCatchableExceptionType(e)) {
2285 throw System.Data.OleDb.ODB.MDACNotAvailable(e);
2288 // disallow any MDAC version before MDAC 2.6 rtm
2289 // include MDAC 2.51 that ships with Win2k
2290 if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526))))) { // MDAC 66628
2291 if (ifodbcelseoledb) {
2292 throw ADP.DataAdapter(Res.GetString(Res.Odbc_MDACWrongVersion, version));
2295 throw ADP.DataAdapter(Res.GetString(Res.OleDb_MDACWrongVersion, version));
2300 // the return value is true if the string was quoted and false if it was not
2301 // this allows the caller to determine if it is an error or not for the quotedString to not be quoted
2302 static internal Boolean RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) {
2305 if (quotePrefix == null){
2309 prefixLength = quotePrefix.Length;
2313 if (quoteSuffix == null){
2317 suffixLength = quoteSuffix.Length;
2320 if ((suffixLength + prefixLength) == 0) {
2321 unquotedString = quotedString;
2325 if (quotedString == null){
2326 unquotedString = quotedString;
2330 int quotedStringLength = quotedString.Length;
2332 // is the source string too short to be quoted
2333 if (quotedStringLength < prefixLength + suffixLength){
2334 unquotedString = quotedString;
2338 // is the prefix present?
2339 if ( prefixLength > 0) {
2340 if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false){
2341 unquotedString = quotedString;
2346 // is the suffix present?
2347 if ( suffixLength > 0) {
2348 if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false){
2349 unquotedString = quotedString;
2352 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix+quoteSuffix,quoteSuffix);
2355 unquotedString = quotedString.Substring(prefixLength,quotedStringLength - prefixLength);
2360 static internal DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) {
2361 const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
2363 // equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
2364 int countAdded = 0, countDeleted = 0, countModifed = 0;
2365 DataRowCollection rowCollection = dataTable.Rows;
2366 foreach(DataRow dataRow in rowCollection) {
2367 switch(dataRow.RowState) {
2368 case DataRowState.Added:
2371 case DataRowState.Deleted:
2374 case DataRowState.Modified:
2378 Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2382 DataRow[] dataRows = new DataRow[countAdded + countDeleted + countModifed];
2384 countModifed = countAdded + countDeleted;
2385 countDeleted = countAdded;
2388 foreach(DataRow dataRow in rowCollection) {
2389 switch(dataRow.RowState) {
2390 case DataRowState.Added:
2391 dataRows[countAdded++] = dataRow;
2393 case DataRowState.Deleted:
2394 dataRows[countDeleted++] = dataRow;
2396 case DataRowState.Modified:
2397 dataRows[countModifed++] = dataRow;
2400 Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
2407 foreach(DataRow dataRow in rowCollection) {
2408 if (0 != (dataRow.RowState & rowStates)) {
2409 dataRows[index++] = dataRow;
2410 if (index == dataRows.Length) {
2419 internal static int StringLength(string inputString) {
2420 return ((null != inputString) ? inputString.Length : 0);
2423 // { "a", "a", "a" } -> { "a", "a1", "a2" }
2424 // { "a", "a", "a1" } -> { "a", "a2", "a1" }
2425 // { "a", "A", "a" } -> { "a", "A1", "a2" }
2426 // { "a", "A", "a1" } -> { "a", "A2", "a1" } // MDAC 66718
2427 static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray) {
2428 Dictionary<string,int> hash = new Dictionary<string,int>(columnNameArray.Length);
2430 int startIndex = columnNameArray.Length; // lowest non-unique index
2431 for (int i = columnNameArray.Length - 1; 0 <= i; --i) {
2432 string columnName = columnNameArray[i];
2433 if ((null != columnName) && (0 < columnName.Length)) {
2434 columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2436 if (hash.TryGetValue(columnName, out index)) {
2437 startIndex = Math.Min(startIndex, index);
2439 hash[columnName] = i;
2442 columnNameArray[i] = ADP.StrEmpty; // MDAC 66681
2446 int uniqueIndex = 1;
2447 for (int i = startIndex; i < columnNameArray.Length; ++i) {
2448 string columnName = columnNameArray[i];
2449 if (0 == columnName.Length) { // generate a unique name
2450 columnNameArray[i] = "Column";
2451 uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
2454 columnName = columnName.ToLower(CultureInfo.InvariantCulture);
2455 if (i != hash[columnName]) {
2456 GenerateUniqueName(hash, ref columnNameArray[i], i, 1); // MDAC 66718
2462 static private int GenerateUniqueName(Dictionary<string,int> hash, ref string columnName, int index, int uniqueIndex) {
2463 for (;; ++uniqueIndex) {
2464 string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
2465 string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); // MDAC 66978
2466 if (!hash.ContainsKey(lowerName)) {
2468 columnName = uniqueName;
2469 hash.Add(lowerName, index);
2476 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2477 static internal IntPtr IntPtrOffset(IntPtr pbase, Int32 offset) {
2478 if (4 == ADP.PtrSize) {
2479 return (IntPtr) checked(pbase.ToInt32() + offset);
2481 Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747
2482 return (IntPtr) checked(pbase.ToInt64() + offset);
2485 static internal int IntPtrToInt32(IntPtr value) {
2486 if (4 == ADP.PtrSize) {
2490 long lval = (long)value;
2491 lval = Math.Min((long)Int32.MaxValue, lval);
2492 lval = Math.Max((long)Int32.MinValue, lval);
2498 static internal int SrcCompare(string strA, string strB) { // this is null safe
2499 return ((strA == strB) ? 0 : 1);
2502 static internal int DstCompare(string strA, string strB) { // this is null safe
2503 return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
2506 static internal bool IsDirection(IDataParameter value, ParameterDirection condition) {
2508 IsDirectionValid(condition);
2510 return (condition == (condition & value.Direction));
2513 static private void IsDirectionValid(ParameterDirection value) {
2514 switch (value) { // @perfnote: Enum.IsDefined
2515 case ParameterDirection.Input:
2516 case ParameterDirection.Output:
2517 case ParameterDirection.InputOutput:
2518 case ParameterDirection.ReturnValue:
2521 throw ADP.InvalidParameterDirection(value);
2526 static internal bool IsEmpty(string str) {
2527 return ((null == str) || (0 == str.Length));
2530 static internal bool IsEmptyArray(string[] array) {
2531 return ((null == array) || (0 == array.Length));
2534 static internal bool IsNull(object value) {
2535 if ((null == value) || (DBNull.Value == value)) {
2538 INullable nullable = (value as INullable);
2539 return ((null != nullable) && nullable.IsNull);
2542 static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) {
2543 if ((value == null) || (value == DBNull.Value)) {
2548 INullable nullable = (value as INullable);
2549 if (nullable != null) {
2550 isNull = nullable.IsNull;
2551 isSqlType = DataStorage.IsSqlType(value.GetType());
2560 private static Version _systemDataVersion;
2561 static internal Version GetAssemblyVersion() {
2562 // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
2563 if (_systemDataVersion == null) {
2564 _systemDataVersion = new Version(ThisAssembly.InformationalVersion);
2567 return _systemDataVersion;