diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.Drivers.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.Drivers.cs deleted file mode 100644 index 8647b4f81c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.Drivers.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Threading; - -namespace Microsoft.Data.Common -{ - internal static partial class ADP - { - - internal static Timer UnsafeCreateTimer(TimerCallback callback, object state, int dueTime, int period) - { - // Don't capture the current ExecutionContext and its AsyncLocals onto - // a global timer causing them to live forever - bool restoreFlow = false; - try - { - if (!ExecutionContext.IsFlowSuppressed()) - { - ExecutionContext.SuppressFlow(); - restoreFlow = true; - } - - return new Timer(callback, state, dueTime, period); - } - finally - { - // Restore the current ExecutionContext - if (restoreFlow) - ExecutionContext.RestoreFlow(); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs deleted file mode 100644 index f318560914..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs +++ /dev/null @@ -1,540 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections; -using System.Data; -using System.Data.SqlTypes; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Security; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Transactions; -using Microsoft.Data.SqlClient; - -namespace Microsoft.Data.Common -{ - internal static partial class ADP - { - // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx) - // Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features - private static Task _trueTask; - internal static Task TrueTask => _trueTask ?? (_trueTask = Task.FromResult(true)); - - private static Task _falseTask; - internal static Task FalseTask => _falseTask ?? (_falseTask = Task.FromResult(false)); - - internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; - - internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; - internal const int InfiniteConnectionTimeout = 0; // infinite connection timeout identifier in seconds - internal const int MaxBufferAccessTokenExpiry = 600; // max duration for buffer in seconds - - static private void TraceException(string trace, Exception e) - { - Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e) - { - SqlClientEventSource.Log.TryTraceEvent(trace, e); - } - } - - internal static void TraceExceptionAsReturnValue(Exception e) - { - TraceException(" '{0}'", e); - } - - internal static void TraceExceptionWithoutRethrow(Exception e) - { - Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); - TraceException(" '{0}'", e); - } - - internal static ArgumentException Argument(string error) - { - ArgumentException e = new ArgumentException(error); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException Argument(string error, Exception inner) - { - ArgumentException e = new ArgumentException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException Argument(string error, string parameter) - { - ArgumentException e = new ArgumentException(error, parameter); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentNullException ArgumentNull(string parameter) - { - ArgumentNullException e = new ArgumentNullException(parameter); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentNullException ArgumentNull(string parameter, string error) - { - ArgumentNullException e = new ArgumentNullException(parameter, error); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) - { - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) - { - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static IndexOutOfRangeException IndexOutOfRange(string error) - { - IndexOutOfRangeException e = new IndexOutOfRangeException(error); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static InvalidCastException InvalidCast(string error) - { - return InvalidCast(error, null); - } - - internal static InvalidCastException InvalidCast(string error, Exception inner) - { - InvalidCastException e = new InvalidCastException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static InvalidOperationException InvalidOperation(string error) - { - InvalidOperationException e = new InvalidOperationException(error); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static NotSupportedException NotSupported() - { - NotSupportedException e = new NotSupportedException(); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static NotSupportedException NotSupported(string error) - { - NotSupportedException e = new NotSupportedException(error); - TraceExceptionAsReturnValue(e); - return e; - } - - // the return value is true if the string was quoted and false if it was not - // this allows the caller to determine if it is an error or not for the quotedString to not be quoted - internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) - { - int prefixLength = quotePrefix != null ? quotePrefix.Length : 0; - int suffixLength = quoteSuffix != null ? quoteSuffix.Length : 0; - - if ((suffixLength + prefixLength) == 0) - { - unquotedString = quotedString; - return true; - } - - if (quotedString == null) - { - unquotedString = quotedString; - return false; - } - - int quotedStringLength = quotedString.Length; - - // is the source string too short to be quoted - if (quotedStringLength < prefixLength + suffixLength) - { - unquotedString = quotedString; - return false; - } - - // is the prefix present? - if (prefixLength > 0) - { - if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal)) - { - unquotedString = quotedString; - return false; - } - } - - // is the suffix present? - if (suffixLength > 0) - { - if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal)) - { - unquotedString = quotedString; - return false; - } - unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix); - } - else - { - unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength); - } - return true; - } - - internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) - { - return ArgumentOutOfRange(StringsHelper.Format(Strings.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name); - } - - internal static InvalidOperationException DataAdapter(string error) - { - return InvalidOperation(error); - } - - private static InvalidOperationException Provider(string error) - { - return InvalidOperation(error); - } - - internal static ArgumentException InvalidMultipartName(string property, string value) - { - ArgumentException e = new ArgumentException(StringsHelper.Format(Strings.ADP_InvalidMultipartName, property, value)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) - { - ArgumentException e = new ArgumentException(StringsHelper.Format(Strings.ADP_InvalidMultipartNameQuoteUsage, property, value)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) - { - ArgumentException e = new ArgumentException(StringsHelper.Format(Strings.ADP_InvalidMultipartNameToManyParts, property, value, limit)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static void CheckArgumentNull(object value, string parameterName) - { - if (null == value) - { - throw ArgumentNull(parameterName); - } - } - - // only StackOverflowException & ThreadAbortException are sealed classes - private static readonly Type s_stackOverflowType = typeof(StackOverflowException); - private static readonly Type s_outOfMemoryType = typeof(OutOfMemoryException); - private static readonly Type s_threadAbortType = typeof(ThreadAbortException); - private static readonly Type s_nullReferenceType = typeof(NullReferenceException); - private static readonly Type s_accessViolationType = typeof(AccessViolationException); - private static readonly Type s_securityType = typeof(SecurityException); - - internal static bool IsCatchableExceptionType(Exception e) - { - // a 'catchable' exception is defined by what it is not. - Debug.Assert(e != null, "Unexpected null exception!"); - Type type = e.GetType(); - - return ((type != s_stackOverflowType) && - (type != s_outOfMemoryType) && - (type != s_threadAbortType) && - (type != s_nullReferenceType) && - (type != s_accessViolationType) && - !s_securityType.IsAssignableFrom(type)); - } - - internal static bool IsCatchableOrSecurityExceptionType(Exception e) - { - // a 'catchable' exception is defined by what it is not. - // since IsCatchableExceptionType defined SecurityException as not 'catchable' - // this method will return true for SecurityException has being catchable. - - // the other way to write this method is, but then SecurityException is checked twice - // return ((e is SecurityException) || IsCatchableExceptionType(e)); - - Debug.Assert(e != null, "Unexpected null exception!"); - Type type = e.GetType(); - - return ((type != s_stackOverflowType) && - (type != s_outOfMemoryType) && - (type != s_threadAbortType) && - (type != s_nullReferenceType) && - (type != s_accessViolationType)); - } - - // Invalid Enumeration - internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) - { - return ArgumentOutOfRange(StringsHelper.Format(Strings.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name); - } - - // - // DbConnectionOptions, DataAccess - // - internal static ArgumentException ConnectionStringSyntax(int index) - { - return Argument(StringsHelper.Format(Strings.ADP_ConnectionStringSyntax, index)); - } - internal static ArgumentException KeywordNotSupported(string keyword) - { - return Argument(StringsHelper.Format(Strings.ADP_KeywordNotSupported, keyword)); - } - internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) - { - return ADP.Argument(StringsHelper.Format(Strings.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); - } - - // - // DbConnectionOptions, DataAccess, SqlClient - // - internal static Exception InvalidConnectionOptionValue(string key) - { - return InvalidConnectionOptionValue(key, null); - } - internal static Exception InvalidConnectionOptionValue(string key, Exception inner) - { - return Argument(StringsHelper.Format(Strings.ADP_InvalidConnectionOptionValue, key), inner); - } - static internal InvalidOperationException InvalidDataDirectory() - { - InvalidOperationException e = new InvalidOperationException(Strings.ADP_InvalidDataDirectory); - return e; - } - - // - // Generic Data Provider Collection - // - internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) - { - return Argument(StringsHelper.Format(Strings.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); - } - internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) - { - return ArgumentNull(parameter, StringsHelper.Format(Strings.ADP_CollectionNullValue, collection.Name, itemType.Name)); - } - internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) - { - return IndexOutOfRange(StringsHelper.Format(Strings.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); - } - internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) - { - return IndexOutOfRange(StringsHelper.Format(Strings.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); - } - internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) - { - return InvalidCast(StringsHelper.Format(Strings.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); - } - - // - // DbConnection - // - private static string ConnectionStateMsg(ConnectionState state) - { - switch (state) - { - case (ConnectionState.Closed): - case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed - return Strings.ADP_ConnectionStateMsg_Closed; - case (ConnectionState.Connecting): - return Strings.ADP_ConnectionStateMsg_Connecting; - case (ConnectionState.Open): - return Strings.ADP_ConnectionStateMsg_Open; - case (ConnectionState.Open | ConnectionState.Executing): - return Strings.ADP_ConnectionStateMsg_OpenExecuting; - case (ConnectionState.Open | ConnectionState.Fetching): - return Strings.ADP_ConnectionStateMsg_OpenFetching; - default: - return StringsHelper.Format(Strings.ADP_ConnectionStateMsg, state.ToString()); - } - } - - // - // : Stream - // - internal static Exception StreamClosed([CallerMemberName] string method = "") - { - return InvalidOperation(StringsHelper.Format(Strings.ADP_StreamClosed, method)); - } - - internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) - { - var resultString = new StringBuilder(unQuotedString.Length + quoteSuffix.Length + quoteSuffix.Length); - AppendQuotedString(resultString, quotePrefix, quoteSuffix, unQuotedString); - return resultString.ToString(); - } - - internal static string AppendQuotedString(StringBuilder buffer, string quotePrefix, string quoteSuffix, string unQuotedString) - { - - if (!string.IsNullOrEmpty(quotePrefix)) - { - buffer.Append(quotePrefix); - } - - // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar". - if (!string.IsNullOrEmpty(quoteSuffix)) - { - int start = buffer.Length; - buffer.Append(unQuotedString); - buffer.Replace(quoteSuffix, quoteSuffix + quoteSuffix, start, unQuotedString.Length); - buffer.Append(quoteSuffix); - } - else - { - buffer.Append(unQuotedString); - } - - return buffer.ToString(); - } - - static internal string BuildMultiPartName(string[] strings) - { - StringBuilder bld = new StringBuilder(); - // Assume we want to build a full multi-part name with all parts except trimming separators for - // leading empty names (null or empty strings, but not whitespace). Separators in the middle - // should be added, even if the name part is null/empty, to maintain proper location of the parts. - for (int i = 0; i < strings.Length; i++) - { - if (0 < bld.Length) - { - bld.Append('.'); - } - if (null != strings[i] && 0 != strings[i].Length) - { - bld.Append(BuildQuotedString("[", "]", strings[i])); - } - } - return bld.ToString(); - } - - // - // Generic Data Provider Collection - // - internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) - { - return Argument(StringsHelper.Format(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); - } - internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection) - { - return Argument(StringsHelper.Format(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); - } - - - internal enum InternalErrorCode - { - UnpooledObjectHasOwner = 0, - UnpooledObjectHasWrongOwner = 1, - PushingObjectSecondTime = 2, - PooledObjectHasOwner = 3, - PooledObjectInPoolMoreThanOnce = 4, - CreateObjectReturnedNull = 5, - NewObjectCannotBePooled = 6, - NonPooledObjectUsedMoreThanOnce = 7, - AttemptingToPoolOnRestrictedToken = 8, - // ConnectionOptionsInUse = 9, - ConvertSidToStringSidWReturnedNull = 10, - // UnexpectedTransactedObject = 11, - AttemptingToConstructReferenceCollectionOnStaticObject = 12, - AttemptingToEnlistTwice = 13, - CreateReferenceCollectionReturnedNull = 14, - PooledObjectWithoutPool = 15, - UnexpectedWaitAnyResult = 16, - SynchronousConnectReturnedPending = 17, - CompletedConnectReturnedPending = 18, - - NameValuePairNext = 20, - InvalidParserState1 = 21, - InvalidParserState2 = 22, - InvalidParserState3 = 23, - - InvalidBuffer = 30, - - UnimplementedSMIMethod = 40, - InvalidSmiCall = 41, - - SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50, - SqlDependencyProcessDispatcherFailureCreateInstance = 51, - SqlDependencyProcessDispatcherFailureAppDomain = 52, - SqlDependencyCommandHashIsNotAssociatedWithNotification = 53, - - UnknownTransactionFailure = 60, - } - - internal static Exception InternalError(InternalErrorCode internalError) - { - return InvalidOperation(StringsHelper.Format(Strings.ADP_InternalProviderError, (int)internalError)); - } - - // - // : DbDataReader - // - internal static Exception DataReaderClosed([CallerMemberName] string method = "") - { - return InvalidOperation(StringsHelper.Format(Strings.ADP_DataReaderClosed, method)); - } - internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) - { - return ArgumentOutOfRange(StringsHelper.Format(Strings.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); - } - internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) - { - return ArgumentOutOfRange(StringsHelper.Format(Strings.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); - } - internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) - { - return IndexOutOfRange(StringsHelper.Format(Strings.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture))); - } - internal static Exception InvalidDataLength(long length) - { - return IndexOutOfRange(StringsHelper.Format(Strings.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); - } - - internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) => - 0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase); - - internal static int DstCompare(string strA, string strB) => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions); - - internal static bool IsEmptyArray(string[] array) => (null == array) || (0 == array.Length); - - internal static bool IsNull(object value) - { - if ((null == value) || (DBNull.Value == value)) - { - return true; - } - INullable nullable = (value as INullable); - return ((null != nullable) && nullable.IsNull); - } - - internal static Exception InvalidSeekOrigin(string parameterName) - { - return ArgumentOutOfRange(Strings.ADP_InvalidSeekOrigin, parameterName); - } - - internal static void SetCurrentTransaction(Transaction transaction) - { - Transaction.Current = transaction; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index 4a1e9a7742..77a87f7c8f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -357,6 +357,9 @@ Resources\StringsHelper.cs + + Microsoft\Data\Common\AdapterUtil.cs + @@ -451,13 +454,6 @@ - - Microsoft\Data\Common\AdapterUtil.cs - - - Microsoft\Data\Common\AdapterUtil.Drivers.cs - - diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs deleted file mode 100644 index d4b9c98678..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs +++ /dev/null @@ -1,944 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Data; -using System.Data.Common; -using System.Data.SqlTypes; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; -using System.Transactions; - -namespace Microsoft.Data.Common -{ - internal static partial class ADP - { - // The class ADP defines the exceptions that are specific to the Adapters. - // The class contains functions that take the proper informational variables and then construct - // the appropriate exception with an error string obtained from the resource framework. - // The exception is then returned to the caller, so that the caller may then throw from its - // location so that the catcher of the exception will have the appropriate call stack. - // This class is used so that there will be compile time checking of error messages. - internal static Exception ExceptionWithStackTrace(Exception e) - { - try - { - throw e; - } - catch (Exception caught) - { - return caught; - } - } - - // - // COM+ exceptions - // - internal static IndexOutOfRangeException IndexOutOfRange(int value) - { - IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture)); - return e; - } - internal static IndexOutOfRangeException IndexOutOfRange() - { - IndexOutOfRangeException e = new IndexOutOfRangeException(); - return e; - } - internal static TimeoutException TimeoutException(string error) - { - TimeoutException e = new TimeoutException(error); - return e; - } - internal static InvalidOperationException InvalidOperation(string error, Exception inner) - { - InvalidOperationException e = new InvalidOperationException(error, inner); - return e; - } - internal static OverflowException Overflow(string error) - { - return Overflow(error, null); - } - internal static OverflowException Overflow(string error, Exception inner) - { - OverflowException e = new OverflowException(error, inner); - return e; - } - internal static TypeLoadException TypeLoad(string error) - { - TypeLoadException e = new TypeLoadException(error); - TraceExceptionAsReturnValue(e); - return e; - } - internal static PlatformNotSupportedException DbTypeNotSupported(string dbType) - { - PlatformNotSupportedException e = new PlatformNotSupportedException(StringsHelper.GetString(Strings.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); - return e; - } - internal static InvalidCastException InvalidCast() - { - InvalidCastException e = new InvalidCastException(); - return e; - } - internal static IOException IO(string error) - { - IOException e = new IOException(error); - return e; - } - internal static IOException IO(string error, Exception inner) - { - IOException e = new IOException(error, inner); - return e; - } - internal static ObjectDisposedException ObjectDisposed(object instance) - { - ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name); - return e; - } - - internal static Exception DataTableDoesNotExist(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_DataTableDoesNotExist, collectionName)); - } - - internal static InvalidOperationException MethodCalledTwice(string method) - { - InvalidOperationException e = new InvalidOperationException(StringsHelper.GetString(Strings.ADP_CalledTwice, method)); - return e; - } - - - // IDbCommand.CommandType - internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value) - { -#if DEBUG - switch (value) - { - case CommandType.Text: - case CommandType.StoredProcedure: - case CommandType.TableDirect: - Debug.Fail("valid CommandType " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(CommandType), (int)value); - } - - // IDbConnection.BeginTransaction, OleDbTransaction.Begin - internal static ArgumentOutOfRangeException InvalidIsolationLevel(System.Data.IsolationLevel value) - { -#if DEBUG - switch (value) - { - case System.Data.IsolationLevel.Unspecified: - case System.Data.IsolationLevel.Chaos: - case System.Data.IsolationLevel.ReadUncommitted: - case System.Data.IsolationLevel.ReadCommitted: - case System.Data.IsolationLevel.RepeatableRead: - case System.Data.IsolationLevel.Serializable: - case System.Data.IsolationLevel.Snapshot: - Debug.Fail("valid IsolationLevel " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(System.Data.IsolationLevel), (int)value); - } - - - // IDataParameter.Direction - internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) - { -#if DEBUG - switch (value) - { - case ParameterDirection.Input: - case ParameterDirection.Output: - case ParameterDirection.InputOutput: - case ParameterDirection.ReturnValue: - Debug.Fail("valid ParameterDirection " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); - } - - internal static Exception TooManyRestrictions(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_TooManyRestrictions, collectionName)); - } - - - // IDbCommand.UpdateRowSource - internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) - { -#if DEBUG - switch (value) - { - case UpdateRowSource.None: - case UpdateRowSource.OutputParameters: - case UpdateRowSource.FirstReturnedRecord: - case UpdateRowSource.Both: - Debug.Fail("valid UpdateRowSource " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); - } - - // - // DbConnectionOptions, DataAccess - // - internal static ArgumentException InvalidMinMaxPoolSizeValues() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMinMaxPoolSizeValues)); - } - - - // - // DbConnection - // - internal static InvalidOperationException NoConnectionString() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NoConnectionString)); - } - - internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "") - { - return NotImplemented.ByDesignWithMessage(methodName); - } - - internal static Exception QueryFailed(string collectionName, Exception e) - { - return InvalidOperation(StringsHelper.GetString(Strings.MDF_QueryFailed, collectionName), e); - } - - - // - // : DbConnectionOptions, DataAccess, SqlClient - // - internal static Exception InvalidConnectionOptionValueLength(string key, int limit) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidConnectionOptionValueLength, key, limit)); - } - internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) - { - return Argument(StringsHelper.GetString(Strings.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); - } - - - // - // DbConnectionPool and related - // - internal static Exception PooledOpenTimeout() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_PooledOpenTimeout)); - } - - internal static Exception NonPooledOpenTimeout() - { - return ADP.TimeoutException(StringsHelper.GetString(Strings.ADP_NonPooledOpenTimeout)); - } - - // - // DbProviderException - // - internal static InvalidOperationException TransactionConnectionMismatch() - { - return Provider(StringsHelper.GetString(Strings.ADP_TransactionConnectionMismatch)); - } - internal static InvalidOperationException TransactionRequired(string method) - { - return Provider(StringsHelper.GetString(Strings.ADP_TransactionRequired, method)); - } - - - internal static Exception CommandTextRequired(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_CommandTextRequired, method)); - } - - internal static Exception NoColumns() - { - return Argument(StringsHelper.GetString(Strings.MDF_NoColumns)); - } - - internal static InvalidOperationException ConnectionRequired(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionRequired, method)); - } - internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); - } - - internal static Exception OpenReaderExists(bool marsOn) - { - return OpenReaderExists(null, marsOn); - } - - internal static Exception OpenReaderExists(Exception e, bool marsOn) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenReaderExists, marsOn ? ADP.Command : ADP.Connection), e); - } - - - // - // DbDataReader - // - internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); - } - - internal static Exception InvalidXml() - { - return Argument(StringsHelper.GetString(Strings.MDF_InvalidXml)); - } - - internal static Exception NegativeParameter(string parameterName) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NegativeParameter, parameterName)); - } - - internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName) - { - return Argument(StringsHelper.GetString(Strings.MDF_InvalidXmlMissingColumn, collectionName, columnName)); - } - - // - // SqlMetaData, SqlTypes, SqlClient - // - internal static Exception InvalidMetaDataValue() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMetaDataValue)); - } - - internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); - } - - internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName) - { - return Argument(StringsHelper.GetString(Strings.MDF_InvalidXmlInvalidValue, collectionName, columnName)); - } - - internal static Exception CollectionNameIsNotUnique(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_CollectionNameISNotUnique, collectionName)); - } - - - // - // : IDbCommand - // - internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "") - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); - } - internal static Exception UninitializedParameterSize(int index, Type dataType) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); - } - - internal static Exception UnableToBuildCollection(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_UnableToBuildCollection, collectionName)); - } - - internal static Exception PrepareParameterType(DbCommand cmd) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterType, cmd.GetType().Name)); - } - - internal static Exception UndefinedCollection(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_UndefinedCollection, collectionName)); - } - - internal static Exception UnsupportedVersion(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_UnsupportedVersion, collectionName)); - } - - internal static Exception AmbiguousCollectionName(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_AmbiguousCollectionName, collectionName)); - } - - internal static Exception PrepareParameterSize(DbCommand cmd) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterSize, cmd.GetType().Name)); - } - internal static Exception PrepareParameterScale(DbCommand cmd, string type) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterScale, cmd.GetType().Name, type)); - } - - internal static Exception MissingDataSourceInformationColumn() - { - return Argument(StringsHelper.GetString(Strings.MDF_MissingDataSourceInformationColumn)); - } - - internal static Exception IncorrectNumberOfDataSourceInformationRows() - { - return Argument(StringsHelper.GetString(Strings.MDF_IncorrectNumberOfDataSourceInformationRows)); - } - - internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); - } - - // - // : ConnectionUtil - // - internal static Exception ClosedConnectionError() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ClosedConnectionError)); - } - internal static Exception ConnectionAlreadyOpen(ConnectionState state) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); - } - internal static Exception TransactionPresent() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_TransactionPresent)); - } - internal static Exception LocalTransactionPresent() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_LocalTransactionPresent)); - } - internal static Exception OpenConnectionPropertySet(string property, ConnectionState state) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); - } - internal static Exception EmptyDatabaseName() - { - return Argument(StringsHelper.GetString(Strings.ADP_EmptyDatabaseName)); - } - - internal enum ConnectionError - { - BeginGetConnectionReturnsNull, - GetConnectionReturnsNull, - ConnectionOptionsMissing, - CouldNotSwitchToClosedPreviouslyOpenedState, - } - - internal static Exception MissingRestrictionColumn() - { - return Argument(StringsHelper.GetString(Strings.MDF_MissingRestrictionColumn)); - } - - internal static Exception InternalConnectionError(ConnectionError internalError) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InternalConnectionError, (int)internalError)); - } - - internal static Exception InvalidConnectRetryCountValue() - { - return Argument(StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryCountValue)); - } - - internal static Exception MissingRestrictionRow() - { - return Argument(StringsHelper.GetString(Strings.MDF_MissingRestrictionRow)); - } - - internal static Exception InvalidConnectRetryIntervalValue() - { - return Argument(StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryIntervalValue)); - } - - // - // : DbDataReader - // - internal static InvalidOperationException AsyncOperationPending() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PendingAsyncOperation)); - } - - // - // : Stream - // - internal static IOException ErrorReadingFromStream(Exception internalException) - { - return IO(StringsHelper.GetString(Strings.SqlMisc_StreamErrorMessage), internalException); - } - - internal static ArgumentException InvalidDataType(TypeCode typecode) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidDataType, typecode.ToString())); - } - - internal static ArgumentException UnknownDataType(Type dataType) - { - return Argument(StringsHelper.GetString(Strings.ADP_UnknownDataType, dataType.FullName)); - } - - internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype) - { - return Argument(StringsHelper.GetString(Strings.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); - } - internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) - { - return Argument(StringsHelper.GetString(Strings.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); - } - internal static ArgumentException InvalidOffsetValue(int value) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); - } - internal static ArgumentException InvalidSizeValue(int value) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); - } - internal static ArgumentException ParameterValueOutOfRange(decimal value) - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); - } - internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value) - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString())); - } - internal static ArgumentException ParameterValueOutOfRange(String value) - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value)); - } - internal static ArgumentException VersionDoesNotSupportDataType(string typeName) - { - return Argument(StringsHelper.GetString(Strings.ADP_VersionDoesNotSupportDataType, typeName)); - } - internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) - { - Debug.Assert(null != value, "null value on conversion failure"); - Debug.Assert(null != inner, "null inner on conversion failure"); - - Exception e; - string message = StringsHelper.GetString(Strings.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); - if (inner is ArgumentException) - { - e = new ArgumentException(message, inner); - } - else if (inner is FormatException) - { - e = new FormatException(message, inner); - } - else if (inner is InvalidCastException) - { - e = new InvalidCastException(message, inner); - } - else if (inner is OverflowException) - { - e = new OverflowException(message, inner); - } - else - { - e = inner; - } - return e; - } - - // - // : IDataParameterCollection - // - internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection) - { - return CollectionIndexInt32(index, collection.GetType(), collection.Count); - } - internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType) - { - return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType()); - } - internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType) - { - return CollectionNullValue(parameter, collection.GetType(), parameterType); - } - - internal static Exception UndefinedPopulationMechanism(string populationMechanism) - { - throw new NotImplementedException(); - } - - internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue) - { - return CollectionInvalidType(collection.GetType(), parameterType, invalidValue); - } - - // - // : IDbTransaction - // - internal static Exception ParallelTransactionsNotSupported(DbConnection obj) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); - } - internal static Exception TransactionZombied(DbTransaction obj) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_TransactionZombied, obj.GetType().Name)); - } - - // global constant strings - internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_"; - internal const string Command = "Command"; - internal const string Connection = "Connection"; - internal const string Parameter = "Parameter"; - internal const string ParameterName = "ParameterName"; - internal const string ParameterSetPosition = "set_Position"; - - internal const int DefaultCommandTimeout = 30; - internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections - - // security issue, don't rely upon public static readonly values - internal static readonly string StrEmpty = ""; // String.Empty - - internal const int CharSize = sizeof(char); - - internal static Delegate FindBuilder(MulticastDelegate mcd) - { - if (null != mcd) - { - foreach (Delegate del in mcd.GetInvocationList()) - { - if (del.Target is DbCommandBuilder) - return del; - } - } - - return null; - } - - internal static long TimerCurrent() - { - return DateTime.UtcNow.ToFileTimeUtc(); - } - - internal static long TimerFromSeconds(int seconds) - { - long result = checked((long)seconds * TimeSpan.TicksPerSecond); - return result; - } - - internal static long TimerFromMilliseconds(long milliseconds) - { - long result = checked(milliseconds * TimeSpan.TicksPerMillisecond); - return result; - } - - internal static bool TimerHasExpired(long timerExpire) - { - bool result = TimerCurrent() > timerExpire; - return result; - } - - internal static long TimerRemaining(long timerExpire) - { - long timerNow = TimerCurrent(); - long result = checked(timerExpire - timerNow); - return result; - } - - internal static long TimerRemainingMilliseconds(long timerExpire) - { - long result = TimerToMilliseconds(TimerRemaining(timerExpire)); - return result; - } - - internal static long TimerRemainingSeconds(long timerExpire) - { - long result = TimerToSeconds(TimerRemaining(timerExpire)); - return result; - } - - internal static long TimerToMilliseconds(long timerValue) - { - long result = timerValue / TimeSpan.TicksPerMillisecond; - return result; - } - - private static long TimerToSeconds(long timerValue) - { - long result = timerValue / TimeSpan.TicksPerSecond; - return result; - } - - internal static string MachineName() - { - return Environment.MachineName; - } - - internal static Transaction GetCurrentTransaction() - { - return Transaction.Current; - } - - internal static bool IsDirection(DbParameter value, ParameterDirection condition) - { -#if DEBUG - IsDirectionValid(condition); -#endif - return (condition == (condition & value.Direction)); - } -#if DEBUG - private static void IsDirectionValid(ParameterDirection value) - { - switch (value) - { // @perfnote: Enum.IsDefined - case ParameterDirection.Input: - case ParameterDirection.Output: - case ParameterDirection.InputOutput: - case ParameterDirection.ReturnValue: - break; - default: - throw ADP.InvalidParameterDirection(value); - } - } -#endif - - internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) - { - if ((value == null) || (value == DBNull.Value)) - { - isNull = true; - isSqlType = false; - } - else - { - INullable nullable = (value as INullable); - if (nullable != null) - { - isNull = nullable.IsNull; - // Duplicated from DataStorage.cs - // For back-compat, SqlXml is not in this list - isSqlType = ((value is SqlBinary) || - (value is SqlBoolean) || - (value is SqlByte) || - (value is SqlBytes) || - (value is SqlChars) || - (value is SqlDateTime) || - (value is SqlDecimal) || - (value is SqlDouble) || - (value is SqlGuid) || - (value is SqlInt16) || - (value is SqlInt32) || - (value is SqlInt64) || - (value is SqlMoney) || - (value is SqlSingle) || - (value is SqlString)); - } - else - { - isNull = false; - isSqlType = false; - } - } - } - - private static Version s_systemDataVersion; - - internal static Version GetAssemblyVersion() - { - // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time - if (s_systemDataVersion == null) - { - s_systemDataVersion = new Version(ThisAssembly.InformationalVersion); - } - - return s_systemDataVersion; - } - - - internal static readonly string[] AzureSqlServerEndpoints = {StringsHelper.GetString(Strings.AZURESQL_GenericEndpoint), - StringsHelper.GetString(Strings.AZURESQL_GermanEndpoint), - StringsHelper.GetString(Strings.AZURESQL_UsGovEndpoint), - StringsHelper.GetString(Strings.AZURESQL_ChinaEndpoint)}; - - // This method assumes dataSource parameter is in TCP connection string format. - internal static bool IsAzureSqlServerEndpoint(string dataSource) - { - int length = dataSource.Length; - // remove server port - int foundIndex = dataSource.LastIndexOf(','); - if (foundIndex >= 0) - { - length = foundIndex; - } - - // check for the instance name - foundIndex = dataSource.LastIndexOf('\\', length - 1, length - 1); - if (foundIndex > 0) - { - length = foundIndex; - } - - // trim trailing whitespace - while (length > 0 && char.IsWhiteSpace(dataSource[length - 1])) - { - length -= 1; - } - - // check if servername end with any azure endpoints - for (int index = 0; index < AzureSqlServerEndpoints.Length; index++) - { - string endpoint = AzureSqlServerEndpoints[index]; - if (length > endpoint.Length) - { - if (string.Compare(dataSource, length - endpoint.Length, endpoint, 0, endpoint.Length, StringComparison.OrdinalIgnoreCase) == 0) - { - return true; - } - } - } - - return false; - } - - internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) - { -#if DEBUG - switch (value) - { - case DataRowVersion.Default: - case DataRowVersion.Current: - case DataRowVersion.Original: - case DataRowVersion.Proposed: - Debug.Fail($"Invalid DataRowVersion {value}"); - break; - } -#endif - return InvalidEnumerationValue(typeof(DataRowVersion), (int)value); - } - - internal static ArgumentException SingleValuedProperty(string propertyName, string value) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_SingleValuedProperty, propertyName, value)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_DoubleValuedProperty, propertyName, value1, value2)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException InvalidPrefixSuffix() - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_InvalidPrefixSuffix)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) - { - Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString()); - - return InvalidEnumerationValue(typeof(CommandBehavior), (int)value); - } - - internal static void ValidateCommandBehavior(CommandBehavior value) - { - if (((int)value < 0) || (0x3F < (int)value)) - { - throw InvalidCommandBehavior(value); - } - } - - internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) - { - return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method); - } - - internal static ArgumentException BadParameterName(string parameterName) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_BadParameterName, parameterName)); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static Exception DeriveParametersNotSupported(IDbCommand value) - { - return DataAdapter(StringsHelper.GetString(Strings.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); - } - - internal static Exception NoStoredProcedureExists(string sproc) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NoStoredProcedureExists, sproc)); - } - - // - // DbProviderException - // - internal static InvalidOperationException TransactionCompletedButNotDisposed() - { - return Provider(StringsHelper.GetString(Strings.ADP_TransactionCompletedButNotDisposed)); - } - - internal static ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.Data.SqlClient.Server.Format value) - { - return InvalidEnumerationValue(typeof(Microsoft.Data.SqlClient.Server.Format), (int)value); - } - - internal static ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.Data.SqlClient.Server.Format value, string method) - { - return NotSupportedEnumerationValue(typeof(Microsoft.Data.SqlClient.Server.Format), value.ToString(), method); - } - - internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) - { - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message); - TraceExceptionAsReturnValue(e); - return e; - } - - internal static ArgumentException InvalidArgumentLength(string argumentName, int limit) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidArgumentLength, argumentName, limit)); - } - - internal static ArgumentException MustBeReadOnly(string argumentName) - { - return Argument(StringsHelper.GetString(Strings.ADP_MustBeReadOnly, argumentName)); - } - - internal static InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); - } - - internal static ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); - } - - internal static InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); - } - - internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); - } - internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity)); - } - static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword)); - } - - static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndAuthentication() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication)); - } - - static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfCredentialAndAccessToken)); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs index 98ba42bdc8..be41cce7aa 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -614,11 +614,7 @@ protected override DbTransaction DbTransaction [ResDescription(StringsHelper.ResourceNames.DbCommand_CommandText)] public override string CommandText { - get - { - string value = _commandText; - return ((null != value) ? value : ADP.StrEmpty); - } + get => _commandText ?? ""; set { if (_commandText != value) @@ -3187,8 +3183,7 @@ internal void DeriveParameters() else { p.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short)r[colNames[(int)ProcParamsColIndex.DataType]], - ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ? - ADP.StrEmpty : + ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ? "" : (string)r[colNames[(int)ProcParamsColIndex.TypeName]]); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnums.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnums.cs index e07a449607..cdf9a4799e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnums.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnums.cs @@ -813,7 +813,7 @@ internal static string GetStringFromXml(XmlReader xmlreader) // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user. private static readonly MetaType s_metaSmallVarBinary = new MetaType - (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); + (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, "", typeof(byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs index 4dbf0e5e6e..694255a206 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -5622,7 +5622,7 @@ private bool TryReadSqlStringValue(SqlBuffer value, byte type, int length, Encod } else { - s = ADP.StrEmpty; + s = ""; } } else @@ -7446,7 +7446,7 @@ private Task WriteEncodingChar(string s, int numChars, int offset, Encoding enco internal int GetEncodingCharLength(string value, int numChars, int charOffset, Encoding encoding) { - if (value == null || value == ADP.StrEmpty) + if (string.IsNullOrEmpty(value)) { return 0; } @@ -9560,13 +9560,13 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet if (_isYukon && (mt.SqlDbType == SqlDbType.Xml)) { - if (((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != ADP.StrEmpty)) || - ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != ADP.StrEmpty)) || - ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != ADP.StrEmpty))) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionDatabase) || + !string.IsNullOrEmpty(param.XmlSchemaCollectionOwningSchema) || + !string.IsNullOrEmpty(param.XmlSchemaCollectionName)) { stateObj.WriteByte(1); //Schema present flag - if ((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != ADP.StrEmpty)) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionDatabase)) { tempLen = (param.XmlSchemaCollectionDatabase).Length; stateObj.WriteByte((byte)(tempLen)); @@ -9577,7 +9577,7 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet stateObj.WriteByte(0); // No dbname } - if ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != ADP.StrEmpty)) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionOwningSchema)) { tempLen = (param.XmlSchemaCollectionOwningSchema).Length; stateObj.WriteByte((byte)(tempLen)); @@ -9588,7 +9588,7 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet stateObj.WriteByte(0); // no xml schema name } - if ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != ADP.StrEmpty)) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionName)) { tempLen = (param.XmlSchemaCollectionName).Length; WriteShort((short)(tempLen), stateObj); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs index 339f9a9d93..a2ee7e51d2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs @@ -23,7 +23,7 @@ private static bool UsingResourceKeys() public static string Format(string resourceFormat, params object[] args) { - if (args != null) + if (args is not null) { if (UsingResourceKeys()) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index d1443d0754..d625a5ea92 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -438,6 +438,9 @@ Resources\ResDescriptionAttribute.cs + + Microsoft\Data\Common\AdapterUtil.cs + @@ -528,7 +531,6 @@ - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs deleted file mode 100644 index eba346f34a..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ /dev/null @@ -1,3079 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Data.Common; -using System.Data.SqlTypes; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Runtime.ConstrainedExecution; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using System.Security; -using System.Security.Permissions; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Xml; -using Microsoft.Data.SqlClient; -using Microsoft.Data.SqlClient.Server; -using Microsoft.Win32; -using SysES = System.EnterpriseServices; -using SysTx = System.Transactions; - -namespace Microsoft.Data.Common -{ - - internal static class ADP - { - // The class ADP defines the exceptions that are specific to the Adapters.f - // The class contains functions that take the proper informational variables and then construct - // the appropriate exception with an error string obtained from the resource Framework.txt. - // The exception is then returned to the caller, so that the caller may then throw from its - // location so that the catcher of the exception will have the appropriate call stack. - // This class is used so that there will be compile time checking of error messages. - // The resource Framework.txt will ensure proper string text based on the appropriate - // locale. - - internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; - - static internal Task CreatedTaskWithException(Exception ex) - { - TaskCompletionSource completion = new TaskCompletionSource(); - completion.SetException(ex); - return completion.Task; - } - - static internal Task CreatedTaskWithCancellation() - { - TaskCompletionSource completion = new TaskCompletionSource(); - completion.SetCanceled(); - return completion.Task; - } - - static internal Exception ExceptionWithStackTrace(Exception e) - { - try - { - throw e; - } - catch (Exception caught) - { - return caught; - } - } - - // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx) - // 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) - static private Task _trueTask = null; - static internal Task TrueTask - { - get - { - if (_trueTask == null) - { - _trueTask = Task.FromResult(true); - } - return _trueTask; - } - } - - static private Task _falseTask = null; - static internal Task FalseTask - { - get - { - if (_falseTask == null) - { - _falseTask = Task.FromResult(false); - } - return _falseTask; - } - } - - static private void TraceException(string trace, Exception e) - { - Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e) - { - SqlClientEventSource.Log.TryTraceEvent(trace, e); - } - } - - static internal void TraceExceptionAsReturnValue(Exception e) - { - TraceException(" {0}", e); - } - static internal void TraceExceptionForCapture(Exception e) - { - Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); - TraceException(" '{0}'", e); - } - static internal void TraceExceptionWithoutRethrow(Exception e) - { - Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); - TraceException(" '{0}'", e); - } - - // - // COM+ exceptions - // - static internal ArgumentException Argument(string error) - { - ArgumentException e = new ArgumentException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentException Argument(string error, Exception inner) - { - ArgumentException e = new ArgumentException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentException Argument(string error, string parameter) - { - ArgumentException e = new ArgumentException(error, parameter); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentException Argument(string error, string parameter, Exception inner) - { - ArgumentException e = new ArgumentException(error, parameter, inner); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentNullException ArgumentNull(string parameter) - { - ArgumentNullException e = new ArgumentNullException(parameter); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentNullException ArgumentNull(string parameter, string error) - { - ArgumentNullException e = new ArgumentNullException(parameter, error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) - { - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) - { - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) - { - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ConfigurationException Configuration(string message) - { - ConfigurationException e = new ConfigurationErrorsException(message); - TraceExceptionAsReturnValue(e); - return e; - } - static internal ConfigurationException Configuration(string message, XmlNode node) - { - ConfigurationException e = new ConfigurationErrorsException(message, node); - TraceExceptionAsReturnValue(e); - return e; - } - static internal DataException Data(string message) - { - DataException e = new DataException(message); - TraceExceptionAsReturnValue(e); - return e; - } - static internal IndexOutOfRangeException IndexOutOfRange(int value) - { - IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture)); - TraceExceptionAsReturnValue(e); - return e; - } - static internal IndexOutOfRangeException IndexOutOfRange(string error) - { - IndexOutOfRangeException e = new IndexOutOfRangeException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal IndexOutOfRangeException IndexOutOfRange() - { - IndexOutOfRangeException e = new IndexOutOfRangeException(); - TraceExceptionAsReturnValue(e); - return e; - } - static internal InvalidCastException InvalidCast(string error) - { - return InvalidCast(error, null); - } - static internal InvalidCastException InvalidCast(string error, Exception inner) - { - InvalidCastException e = new InvalidCastException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - static internal InvalidOperationException InvalidOperation(string error) - { - InvalidOperationException e = new InvalidOperationException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal TimeoutException TimeoutException(string error) - { - TimeoutException e = new TimeoutException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal InvalidOperationException InvalidOperation(string error, Exception inner) - { - InvalidOperationException e = new InvalidOperationException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - static internal NotImplementedException NotImplemented(string error) - { - NotImplementedException e = new NotImplementedException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal NotSupportedException NotSupported() - { - NotSupportedException e = new NotSupportedException(); - TraceExceptionAsReturnValue(e); - return e; - } - static internal NotSupportedException NotSupported(string error) - { - NotSupportedException e = new NotSupportedException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal OverflowException Overflow(string error) - { - return Overflow(error, null); - } - static internal OverflowException Overflow(string error, Exception inner) - { - OverflowException e = new OverflowException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - static internal PlatformNotSupportedException PropertyNotSupported(string property) - { - PlatformNotSupportedException e = new PlatformNotSupportedException(StringsHelper.GetString(Strings.ADP_PropertyNotSupported, property)); - TraceExceptionAsReturnValue(e); - return e; - } - static internal TypeLoadException TypeLoad(string error) - { - TypeLoadException e = new TypeLoadException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal InvalidCastException InvalidCast() - { - InvalidCastException e = new InvalidCastException(); - TraceExceptionAsReturnValue(e); - return e; - } - static internal IOException IO(string error) - { - IOException e = new IOException(error); - TraceExceptionAsReturnValue(e); - return e; - } - static internal IOException IO(string error, Exception inner) - { - IOException e = new IOException(error, inner); - TraceExceptionAsReturnValue(e); - return e; - } - static internal InvalidOperationException DataAdapter(string error) - { - return InvalidOperation(error); - } - static internal InvalidOperationException DataAdapter(string error, Exception inner) - { - return InvalidOperation(error, inner); - } - static private InvalidOperationException Provider(string error) - { - return InvalidOperation(error); - } - static internal ObjectDisposedException ObjectDisposed(object instance) - { - ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal InvalidOperationException MethodCalledTwice(string method) - { - InvalidOperationException e = new InvalidOperationException(StringsHelper.GetString(Strings.ADP_CalledTwice, method)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException IncorrectAsyncResult() - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_IncorrectAsyncResult), "AsyncResult"); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException SingleValuedProperty(string propertyName, string value) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_SingleValuedProperty, propertyName, value)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_DoubleValuedProperty, propertyName, value1, value2)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException InvalidPrefixSuffix() - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_InvalidPrefixSuffix)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException InvalidMultipartName(string property, string value) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_InvalidMultipartName, StringsHelper.GetString(property), value)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_InvalidMultipartNameQuoteUsage, StringsHelper.GetString(property), value)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_InvalidMultipartNameToManyParts, StringsHelper.GetString(property), value, limit)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException BadParameterName(string parameterName) - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_BadParameterName, parameterName)); - TraceExceptionAsReturnValue(e); - return e; - } - - static internal ArgumentException MultipleReturnValue() - { - ArgumentException e = new ArgumentException(StringsHelper.GetString(Strings.ADP_MultipleReturnValue)); - TraceExceptionAsReturnValue(e); - return e; - } - - // - // Helper Functions - // - static internal void CheckArgumentLength(string value, string parameterName) - { - CheckArgumentNull(value, parameterName); - if (0 == value.Length) - { - throw Argument(StringsHelper.GetString(Strings.ADP_EmptyString, parameterName)); // MDAC 94859 - } - } - static internal void CheckArgumentLength(Array value, string parameterName) - { - CheckArgumentNull(value, parameterName); - if (0 == value.Length) - { - throw Argument(StringsHelper.GetString(Strings.ADP_EmptyArray, parameterName)); - } - } - static internal void CheckArgumentNull(object value, string parameterName) - { - if (null == value) - { - throw ArgumentNull(parameterName); - } - } - - - // only StackOverflowException & ThreadAbortException are sealed classes - static private readonly Type StackOverflowType = typeof(StackOverflowException); - static private readonly Type OutOfMemoryType = typeof(OutOfMemoryException); - static private readonly Type ThreadAbortType = typeof(ThreadAbortException); - static private readonly Type NullReferenceType = typeof(NullReferenceException); - static private readonly Type AccessViolationType = typeof(AccessViolationException); - static private readonly Type SecurityType = typeof(SecurityException); - - static internal bool IsCatchableExceptionType(Exception e) - { - // a 'catchable' exception is defined by what it is not. - Debug.Assert(e != null, "Unexpected null exception!"); - Type type = e.GetType(); - - return ((type != StackOverflowType) && - (type != OutOfMemoryType) && - (type != ThreadAbortType) && - (type != NullReferenceType) && - (type != AccessViolationType) && - !SecurityType.IsAssignableFrom(type)); - } - - static internal bool IsCatchableOrSecurityExceptionType(Exception e) - { - // a 'catchable' exception is defined by what it is not. - // since IsCatchableExceptionType defined SecurityException as not 'catchable' - // this method will return true for SecurityException has being catchable. - - // the other way to write this method is, but then SecurityException is checked twice - // return ((e is SecurityException) || IsCatchableExceptionType(e)); - - Debug.Assert(e != null, "Unexpected null exception!"); - Type type = e.GetType(); - - return ((type != StackOverflowType) && - (type != OutOfMemoryType) && - (type != ThreadAbortType) && - (type != NullReferenceType) && - (type != AccessViolationType)); - } - - // Invalid Enumeration - - static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) - { - return ADP.ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name); - } - - static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) - { - return ADP.ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name); - } - - static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) - { -#if DEBUG - switch (value) - { - case AcceptRejectRule.None: - case AcceptRejectRule.Cascade: - Debug.Assert(false, "valid AcceptRejectRule " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(AcceptRejectRule), (int)value); - } - // DbCommandBuilder.CatalogLocation - static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) - { -#if DEBUG - switch (value) - { - case CatalogLocation.Start: - case CatalogLocation.End: - Debug.Assert(false, "valid CatalogLocation " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(CatalogLocation), (int)value); - } - - static internal ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) - { -#if DEBUG - if ((0 <= (int)value) && ((int)value <= 0x3F)) - { - Debug.Assert(false, "valid CommandType " + value.ToString()); - } -#endif - return InvalidEnumerationValue(typeof(CommandBehavior), (int)value); - } - static internal void ValidateCommandBehavior(CommandBehavior value) - { - if (((int)value < 0) || (0x3F < (int)value)) - { - throw InvalidCommandBehavior(value); - } - } - static internal ArgumentException InvalidArgumentLength(string argumentName, int limit) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidArgumentLength, argumentName, limit)); - } - - static internal ArgumentException MustBeReadOnly(string argumentName) - { - return Argument(StringsHelper.GetString(Strings.ADP_MustBeReadOnly, argumentName)); - } - - // IDbCommand.CommandType - static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) - { -#if DEBUG - switch (value) - { - case CommandType.Text: - case CommandType.StoredProcedure: - case CommandType.TableDirect: - Debug.Assert(false, "valid CommandType " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(CommandType), (int)value); - } - - static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) - { -#if DEBUG - switch (value) - { - case ConflictOption.CompareAllSearchableValues: - case ConflictOption.CompareRowVersion: - case ConflictOption.OverwriteChanges: - Debug.Assert(false, "valid ConflictOption " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(ConflictOption), (int)value); - } - - // IDataAdapter.Update - static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) - { -#if DEBUG - switch (value) - { - case DataRowState.Detached: - case DataRowState.Unchanged: - case DataRowState.Added: - case DataRowState.Deleted: - case DataRowState.Modified: - Debug.Assert(false, "valid DataRowState " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(DataRowState), (int)value); - } - - // IDataParameter.SourceVersion - static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) - { -#if DEBUG - switch (value) - { - case DataRowVersion.Default: - case DataRowVersion.Current: - case DataRowVersion.Original: - case DataRowVersion.Proposed: - Debug.Assert(false, "valid DataRowVersion " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(DataRowVersion), (int)value); - } - - // IDbConnection.BeginTransaction, OleDbTransaction.Begin - static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) - { -#if DEBUG - switch (value) - { - case IsolationLevel.Unspecified: - case IsolationLevel.Chaos: - case IsolationLevel.ReadUncommitted: - case IsolationLevel.ReadCommitted: - case IsolationLevel.RepeatableRead: - case IsolationLevel.Serializable: - case IsolationLevel.Snapshot: - Debug.Assert(false, "valid IsolationLevel " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); - } - - // DBDataPermissionAttribute.KeyRestrictionBehavior - static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) - { -#if DEBUG - switch (value) - { - case KeyRestrictionBehavior.PreventUsage: - case KeyRestrictionBehavior.AllowOnly: - Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int)value); - } - - // IDataAdapter.FillLoadOption - static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) - { -#if DEBUG - switch (value) - { - case LoadOption.OverwriteChanges: - case LoadOption.PreserveChanges: - case LoadOption.Upsert: - Debug.Assert(false, "valid LoadOption " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(LoadOption), (int)value); - } - - // IDataAdapter.MissingMappingAction - static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) - { -#if DEBUG - switch (value) - { - case MissingMappingAction.Passthrough: - case MissingMappingAction.Ignore: - case MissingMappingAction.Error: - Debug.Assert(false, "valid MissingMappingAction " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(MissingMappingAction), (int)value); - } - - // IDataAdapter.MissingSchemaAction - static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) - { -#if DEBUG - switch (value) - { - case MissingSchemaAction.Add: - case MissingSchemaAction.Ignore: - case MissingSchemaAction.Error: - case MissingSchemaAction.AddWithKey: - Debug.Assert(false, "valid MissingSchemaAction " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(MissingSchemaAction), (int)value); - } - - // IDataParameter.Direction - static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) - { -#if DEBUG - switch (value) - { - case ParameterDirection.Input: - case ParameterDirection.Output: - case ParameterDirection.InputOutput: - case ParameterDirection.ReturnValue: - Debug.Assert(false, "valid ParameterDirection " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); - } - - static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionState value) - { -#if DEBUG - switch (value) - { - case PermissionState.Unrestricted: - case PermissionState.None: - Debug.Assert(false, "valid PermissionState " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(PermissionState), (int)value); - } - - static internal ArgumentOutOfRangeException InvalidRule(Rule value) - { -#if DEBUG - switch (value) - { - case Rule.None: - case Rule.Cascade: - case Rule.SetNull: - case Rule.SetDefault: - Debug.Assert(false, "valid Rule " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(Rule), (int)value); - } - - // IDataAdapter.FillSchema - static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) - { -#if DEBUG - switch (value) - { - case SchemaType.Source: - case SchemaType.Mapped: - Debug.Assert(false, "valid SchemaType " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(SchemaType), (int)value); - } - - // RowUpdatingEventArgs.StatementType - static internal ArgumentOutOfRangeException InvalidStatementType(StatementType value) - { -#if DEBUG - switch (value) - { - case StatementType.Select: - case StatementType.Insert: - case StatementType.Update: - case StatementType.Delete: - case StatementType.Batch: - Debug.Assert(false, "valid StatementType " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(StatementType), (int)value); - } - - // IDbCommand.UpdateRowSource - static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) - { -#if DEBUG - switch (value) - { - case UpdateRowSource.None: - case UpdateRowSource.OutputParameters: - case UpdateRowSource.FirstReturnedRecord: - case UpdateRowSource.Both: - Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); - } - - // RowUpdatingEventArgs.UpdateStatus - static internal ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) - { -#if DEBUG - switch (value) - { - case UpdateStatus.Continue: - case UpdateStatus.ErrorsOccurred: - case UpdateStatus.SkipAllRemainingRows: - case UpdateStatus.SkipCurrentRow: - Debug.Assert(false, "valid UpdateStatus " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(UpdateStatus), (int)value); - } - - static internal ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) - { - return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method); - } - - static internal ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method) - { - return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method); - } - - static internal ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Format value) - { -#if DEBUG - switch (value) - { - case Format.Unknown: - case Format.Native: - case Format.UserDefined: - Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString()); - break; - } -#endif - return InvalidEnumerationValue(typeof(Format), (int)value); - } - - static internal ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Format value, string method) - { - return ADP.NotSupportedEnumerationValue(typeof(Format), value.ToString(), method); - } - - // - // DbProviderFactories - // - static internal ArgumentException ConfigProviderNotFound() - { - return Argument(StringsHelper.GetString(Strings.ConfigProviderNotFound)); - } - static internal InvalidOperationException ConfigProviderInvalid() - { - return InvalidOperation(StringsHelper.GetString(Strings.ConfigProviderInvalid)); - } - static internal ConfigurationException ConfigProviderNotInstalled() - { - return Configuration(StringsHelper.GetString(Strings.ConfigProviderNotInstalled)); - } - static internal ConfigurationException ConfigProviderMissing() - { - return Configuration(StringsHelper.GetString(Strings.ConfigProviderMissing)); - } - - // - // DbProviderConfigurationHandler - // - static internal ConfigurationException ConfigBaseNoChildNodes(XmlNode node) - { // Strings.Config_base_no_child_nodes - return Configuration(StringsHelper.GetString(Strings.ConfigBaseNoChildNodes), node); - } - static internal ConfigurationException ConfigBaseElementsOnly(XmlNode node) - { // Strings.Config_base_elements_only - return Configuration(StringsHelper.GetString(Strings.ConfigBaseElementsOnly), node); - } - static internal ConfigurationException ConfigUnrecognizedAttributes(XmlNode node) - { // Strings.Config_base_unrecognized_attribute - return Configuration(StringsHelper.GetString(Strings.ConfigUnrecognizedAttributes, node.Attributes[0].Name), node); - } - static internal ConfigurationException ConfigUnrecognizedElement(XmlNode node) - { // Strings.Config_base_unrecognized_element - return Configuration(StringsHelper.GetString(Strings.ConfigUnrecognizedElement), node); - } - static internal ConfigurationException ConfigSectionsUnique(string sectionName) - { // Strings.Strings.ConfigSectionsUnique - return Configuration(StringsHelper.GetString(Strings.ConfigSectionsUnique, sectionName)); - } - static internal ConfigurationException ConfigRequiredAttributeMissing(string name, XmlNode node) - { // Strings.Config_base_required_attribute_missing - return Configuration(StringsHelper.GetString(Strings.ConfigRequiredAttributeMissing, name), node); - } - static internal ConfigurationException ConfigRequiredAttributeEmpty(string name, XmlNode node) - { // Strings.Config_base_required_attribute_empty - return Configuration(StringsHelper.GetString(Strings.ConfigRequiredAttributeEmpty, name), node); - } - - // - // DbConnectionOptions, DataAccess - // - static internal ArgumentException ConnectionStringSyntax(int index) - { - return Argument(StringsHelper.GetString(Strings.ADP_ConnectionStringSyntax, index)); - } - static internal ArgumentException KeywordNotSupported(string keyword) - { - return Argument(StringsHelper.GetString(Strings.ADP_KeywordNotSupported, keyword)); - } - /* - static internal ArgumentException EmptyKeyValue(string keyword) { // MDAC 80715 - return Argument(ResHelper.GetString(Strings.ADP_EmptyKeyValue, keyword)); - } - */ - static internal ArgumentException UdlFileError(Exception inner) - { - return Argument(StringsHelper.GetString(Strings.ADP_UdlFileError), inner); - } - static internal ArgumentException InvalidUDL() - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidUDL)); - } - static internal InvalidOperationException InvalidDataDirectory() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidDataDirectory)); - } - static internal ArgumentException InvalidKeyname(string parameterName) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidKey), parameterName); - } - static internal ArgumentException InvalidValue(string parameterName) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidValue), parameterName); - } - static internal ArgumentException InvalidMinMaxPoolSizeValues() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMinMaxPoolSizeValues)); - } - static internal ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) - { - return ADP.Argument(StringsHelper.GetString(Strings.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); - } - - static internal InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); - } - - static internal ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); - } - - static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); - } - - static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); - } - - static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndContextConnection() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection)); - } - - static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndContextConnection() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection)); - } - - static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndContextConnection() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndContextConnection)); - } - - static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity)); - } - - static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword)); - } - - static internal Exception InvalidMixedUsageOfAccessTokenAndCredential() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndCredential)); - } - - static internal Exception InvalidMixedUsageOfAccessTokenAndAuthentication() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication)); - } - - static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfCredentialAndAccessToken)); - } - - // - // DbConnection - // - static internal InvalidOperationException NoConnectionString() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NoConnectionString)); - } - - static internal NotImplementedException MethodNotImplemented(string methodName) - { - NotImplementedException e = new NotImplementedException(methodName); - TraceExceptionAsReturnValue(e); - return e; - } - static private string ConnectionStateMsg(ConnectionState state) - { // MDAC 82165, if the ConnectionState enum to msg the localization looks weird - switch (state) - { - case (ConnectionState.Closed): - case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed - return StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_Closed); - case (ConnectionState.Connecting): - return StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_Connecting); - case (ConnectionState.Open): - return StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_Open); - case (ConnectionState.Open | ConnectionState.Executing): - return StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_OpenExecuting); - case (ConnectionState.Open | ConnectionState.Fetching): - return StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_OpenFetching); - default: - return StringsHelper.GetString(Strings.ADP_ConnectionStateMsg, state.ToString()); - } - } - - static internal ConfigurationException ConfigUnableToLoadXmlMetaDataFile(string settingName) - { - return Configuration(StringsHelper.GetString(Strings.OleDb_ConfigUnableToLoadXmlMetaDataFile, settingName)); - } - - static internal ConfigurationException ConfigWrongNumberOfValues(string settingName) - { - return Configuration(StringsHelper.GetString(Strings.OleDb_ConfigWrongNumberOfValues, settingName)); - } - - // - // : DbConnectionOptions, DataAccess, SqlClient - // - static internal Exception InvalidConnectionOptionValue(string key) - { - return InvalidConnectionOptionValue(key, null); - } - static internal Exception InvalidConnectionOptionValueLength(string key, int limit) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidConnectionOptionValueLength, key, limit)); - } - static internal Exception InvalidConnectionOptionValue(string key, Exception inner) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidConnectionOptionValue, key), inner); - } - static internal Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) - { - return Argument(StringsHelper.GetString(Strings.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); - } - - // - // DBDataPermission, DataAccess, Odbc - // - static internal Exception InvalidXMLBadVersion() - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidXMLBadVersion)); - } - static internal Exception NotAPermissionElement() - { - return Argument(StringsHelper.GetString(Strings.ADP_NotAPermissionElement)); - } - static internal Exception PermissionTypeMismatch() - { - return Argument(StringsHelper.GetString(Strings.ADP_PermissionTypeMismatch)); - } - - static internal Exception WrongType(Type got, Type expected) - { - return Argument(StringsHelper.GetString(Strings.SQL_WrongType, got.ToString(), expected.ToString())); - } - - static internal Exception OdbcNoTypesFromProvider() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OdbcNoTypesFromProvider)); - } - - // - // DbConnectionPool and related - // - static internal Exception PooledOpenTimeout() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_PooledOpenTimeout)); - } - - static internal Exception NonPooledOpenTimeout() - { - return ADP.TimeoutException(StringsHelper.GetString(Strings.ADP_NonPooledOpenTimeout)); - } - - // - // Generic Data Provider Collection - // - static internal ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) - { - return Argument(StringsHelper.GetString(Strings.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); // MDAC 68201 - } - static internal ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) - { - return ArgumentNull(parameter, StringsHelper.GetString(Strings.ADP_CollectionNullValue, collection.Name, itemType.Name)); - } - static internal IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) - { - return IndexOutOfRange(StringsHelper.GetString(Strings.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); - } - static internal IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) - { - return IndexOutOfRange(StringsHelper.GetString(Strings.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); - } - static internal InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) - { - return InvalidCast(StringsHelper.GetString(Strings.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); - } - static internal Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue) - { - return Argument(StringsHelper.GetString(Strings.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue)); - } - static internal ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) - { - return Argument(StringsHelper.GetString(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); - } - static internal ArgumentException ParametersIsParent(Type parameterType, ICollection collection) - { - return Argument(StringsHelper.GetString(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); - } - - // - // DbProviderException - // - static internal InvalidOperationException TransactionConnectionMismatch() - { - return Provider(StringsHelper.GetString(Strings.ADP_TransactionConnectionMismatch)); - } - static internal InvalidOperationException TransactionCompletedButNotDisposed() - { - return Provider(StringsHelper.GetString(Strings.ADP_TransactionCompletedButNotDisposed)); - } - static internal InvalidOperationException TransactionRequired(string method) - { - return Provider(StringsHelper.GetString(Strings.ADP_TransactionRequired, method)); - } - - // IDbDataAdapter.Fill(Schema) - static internal InvalidOperationException MissingSelectCommand(string method) - { - return Provider(StringsHelper.GetString(Strings.ADP_MissingSelectCommand, method)); - } - - // - // AdapterMappingException - // - static private InvalidOperationException DataMapping(string error) - { - return InvalidOperation(error); - } - - // DataColumnMapping.GetDataColumnBySchemaAction - static internal InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn) - { - return DataMapping(StringsHelper.GetString(Strings.ADP_ColumnSchemaExpression, srcColumn, cacheColumn)); - } - - // DataColumnMapping.GetDataColumnBySchemaAction - static internal InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column) - { - return DataMapping(StringsHelper.GetString(Strings.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name)); - } - - // DataColumnMapping.GetDataColumnBySchemaAction - static internal InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn) - { - if (ADP.IsEmpty(tableName)) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn)); - } - return DataMapping(StringsHelper.GetString(Strings.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn)); - } - - // DataColumnMappingCollection.GetColumnMappingBySchemaAction - static internal InvalidOperationException MissingColumnMapping(string srcColumn) - { - return DataMapping(StringsHelper.GetString(Strings.ADP_MissingColumnMapping, srcColumn)); - } - - // DataTableMapping.GetDataTableBySchemaAction - static internal InvalidOperationException MissingTableSchema(string cacheTable, string srcTable) - { - return DataMapping(StringsHelper.GetString(Strings.ADP_MissingTableSchema, cacheTable, srcTable)); - } - - // DataTableMappingCollection.GetTableMappingBySchemaAction - static internal InvalidOperationException MissingTableMapping(string srcTable) - { - return DataMapping(StringsHelper.GetString(Strings.ADP_MissingTableMapping, srcTable)); - } - - // DbDataAdapter.Update - static internal InvalidOperationException MissingTableMappingDestination(string dstTable) - { - return DataMapping(StringsHelper.GetString(Strings.ADP_MissingTableMappingDestination, dstTable)); - } - - // - // DataColumnMappingCollection, DataAccess - // - static internal Exception InvalidSourceColumn(string parameter) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidSourceColumn), parameter); - } - static internal Exception ColumnsAddNullAttempt(string parameter) - { - return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping)); - } - static internal Exception ColumnsDataSetColumn(string cacheColumn) - { - return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection)); - } - static internal Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection) - { - return CollectionIndexInt32(index, collection.GetType(), collection.Count); - } - static internal Exception ColumnsIndexSource(string srcColumn) - { - return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection)); - } - static internal Exception ColumnsIsNotParent(ICollection collection) - { - return ParametersIsNotParent(typeof(DataColumnMapping), collection); - } - static internal Exception ColumnsIsParent(ICollection collection) - { - return ParametersIsParent(typeof(DataColumnMapping), collection); - } - static internal Exception ColumnsUniqueSourceColumn(string srcColumn) - { - return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn); - } - static internal Exception NotADataColumnMapping(object value) - { - return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value); - } - - // - // DataTableMappingCollection, DataAccess - // - static internal Exception InvalidSourceTable(string parameter) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidSourceTable), parameter); - } - static internal Exception TablesAddNullAttempt(string parameter) - { - return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping)); - } - static internal Exception TablesDataSetTable(string cacheTable) - { - return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection)); - } - static internal Exception TablesIndexInt32(int index, ITableMappingCollection collection) - { - return CollectionIndexInt32(index, collection.GetType(), collection.Count); - } - static internal Exception TablesIsNotParent(ICollection collection) - { - return ParametersIsNotParent(typeof(DataTableMapping), collection); - } - static internal Exception TablesIsParent(ICollection collection) - { - return ParametersIsParent(typeof(DataTableMapping), collection); - } - static internal Exception TablesSourceIndex(string srcTable) - { - return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection)); - } - static internal Exception TablesUniqueSourceTable(string srcTable) - { - return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable); - } - static internal Exception NotADataTableMapping(object value) - { - return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value); - } - - // - // IDbCommand - // - - static internal InvalidOperationException CommandAsyncOperationCompleted() - { - return InvalidOperation(StringsHelper.GetString(Strings.SQL_AsyncOperationCompleted)); - } - - static internal Exception CommandTextRequired(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_CommandTextRequired, method)); - } - - static internal InvalidOperationException ConnectionRequired(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionRequired, method)); - } - static internal InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); - } - - - static internal InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand) - { - string resource; - if (isRowUpdatingCommand) - { - resource = Strings.ADP_ConnectionRequired_Clone; - } - else - { - switch (statementType) - { - case StatementType.Insert: - resource = Strings.ADP_ConnectionRequired_Insert; - break; - case StatementType.Update: - resource = Strings.ADP_ConnectionRequired_Update; - break; - case StatementType.Delete: - resource = Strings.ADP_ConnectionRequired_Delete; - break; - case StatementType.Batch: - resource = Strings.ADP_ConnectionRequired_Batch; - goto default; -#if DEBUG - case StatementType.Select: - Debug.Assert(false, "shouldn't be here"); - goto default; -#endif - default: - throw ADP.InvalidStatementType(statementType); - } - } - return InvalidOperation(StringsHelper.GetString(resource)); - } - - static internal InvalidOperationException ConnectionRequired_Res(string method) - { - string resource = "ADP_ConnectionRequired_" + method; -#if DEBUG - switch (resource) - { - case StringsHelper.ResourceNames.ADP_ConnectionRequired_Fill: - case StringsHelper.ResourceNames.ADP_ConnectionRequired_FillPage: - case StringsHelper.ResourceNames.ADP_ConnectionRequired_FillSchema: - case StringsHelper.ResourceNames.ADP_ConnectionRequired_Update: - case StringsHelper.ResourceNames.ADP_ConnecitonRequired_UpdateRows: - break; - default: - Debug.Assert(false, "missing resource string: " + resource); - break; - } -#endif - return InvalidOperation(StringsHelper.GetString(resource)); - } - static internal InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state) - { - string resource; - if (isRowUpdatingCommand) - { - resource = Strings.ADP_OpenConnectionRequired_Clone; - } - else - { - switch (statementType) - { - case StatementType.Insert: - resource = Strings.ADP_OpenConnectionRequired_Insert; - break; - case StatementType.Update: - resource = Strings.ADP_OpenConnectionRequired_Update; - break; - case StatementType.Delete: - resource = Strings.ADP_OpenConnectionRequired_Delete; - break; -#if DEBUG - case StatementType.Select: - Debug.Assert(false, "shouldn't be here"); - goto default; - case StatementType.Batch: - Debug.Assert(false, "isRowUpdatingCommand should have been true"); - goto default; -#endif - default: - throw ADP.InvalidStatementType(statementType); - } - } - return InvalidOperation(StringsHelper.GetString(resource, ADP.ConnectionStateMsg(state))); - } - - static internal Exception NoStoredProcedureExists(string sproc) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NoStoredProcedureExists, sproc)); - } - static internal Exception OpenReaderExists(bool marsOn) - { - return OpenReaderExists(null, marsOn); - } - - static internal Exception OpenReaderExists(Exception e, bool marsOn) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenReaderExists, marsOn ? ADP.Command : ADP.Connection), e); - } - - static internal Exception TransactionCompleted() - { - return DataAdapter(StringsHelper.GetString(Strings.ADP_TransactionCompleted)); - } - - // - // DbDataReader - // - static internal Exception NonSeqByteAccess(long badIndex, long currIndex, string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); - } - - static internal Exception NegativeParameter(string parameterName) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NegativeParameter, parameterName)); - } - - static internal Exception NumericToDecimalOverflow() - { - return InvalidCast(StringsHelper.GetString(Strings.ADP_NumericToDecimalOverflow)); - } - - // - // Stream, SqlTypes, SqlClient - // - - static internal Exception ExceedsMaxDataLength(long specifiedLength, long maxLength) - { - return IndexOutOfRange(StringsHelper.GetString(Strings.SQL_ExceedsMaxDataLength, specifiedLength.ToString(CultureInfo.InvariantCulture), maxLength.ToString(CultureInfo.InvariantCulture))); - } - - static internal Exception InvalidSeekOrigin(string parameterName) - { - return ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidSeekOrigin), parameterName); - } - - // - // SqlMetaData, SqlTypes, SqlClient - // - static internal Exception InvalidImplicitConversion(Type fromtype, string totype) - { - return InvalidCast(StringsHelper.GetString(Strings.ADP_InvalidImplicitConversion, fromtype.Name, totype)); - } - static internal Exception InvalidMetaDataValue() - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMetaDataValue)); - } - - static internal Exception NotRowType() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NotRowType)); - } - - // - // DbDataAdapter - // - static internal ArgumentException UnwantedStatementType(StatementType statementType) - { - return Argument(StringsHelper.GetString(Strings.ADP_UnwantedStatementType, statementType.ToString())); - } - static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); - } - - // - // DbDataAdapter.FillSchema - // - static internal Exception FillSchemaRequiresSourceTableName(string parameter) - { - return Argument(StringsHelper.GetString(Strings.ADP_FillSchemaRequiresSourceTableName), parameter); - } - - // - // DbDataAdapter.Fill - // - static internal Exception InvalidMaxRecords(string parameter, int max) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter); - } - static internal Exception InvalidStartRecord(string parameter, int start) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter); - } - static internal Exception FillRequires(string parameter) - { - return ArgumentNull(parameter); - } - static internal Exception FillRequiresSourceTableName(string parameter) - { - return Argument(StringsHelper.GetString(Strings.ADP_FillRequiresSourceTableName), parameter); - } - static internal Exception FillChapterAutoIncrement() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_FillChapterAutoIncrement)); - } - static internal InvalidOperationException MissingDataReaderFieldType(int index) - { - return DataAdapter(StringsHelper.GetString(Strings.ADP_MissingDataReaderFieldType, index)); - } - static internal InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords() - { - return DataAdapter(StringsHelper.GetString(Strings.ADP_OnlyOneTableForStartRecordOrMaxRecords)); - } - // - // DbDataAdapter.Update - // - static internal ArgumentNullException UpdateRequiresNonNullDataSet(string parameter) - { - return ArgumentNull(parameter); - } - static internal InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_UpdateRequiresSourceTable, defaultSrcTableName)); - } - static internal InvalidOperationException UpdateRequiresSourceTableName(string srcTable) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_UpdateRequiresSourceTableName, srcTable)); // MDAC 70448 - } - static internal ArgumentNullException UpdateRequiresDataTable(string parameter) - { - return ArgumentNull(parameter); - } - - static internal Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows) - { - string resource; - switch (statementType) - { - case StatementType.Update: - resource = Strings.ADP_UpdateConcurrencyViolation_Update; - break; - case StatementType.Delete: - resource = Strings.ADP_UpdateConcurrencyViolation_Delete; - break; - case StatementType.Batch: - resource = Strings.ADP_UpdateConcurrencyViolation_Batch; - break; -#if DEBUG - case StatementType.Select: - case StatementType.Insert: - Debug.Assert(false, "should be here"); - goto default; -#endif - default: - throw ADP.InvalidStatementType(statementType); - } - DBConcurrencyException exception = new DBConcurrencyException(StringsHelper.GetString(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows); - TraceExceptionAsReturnValue(exception); - return exception; - } - - static internal InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand) - { - string resource; - if (isRowUpdatingCommand) - { - resource = Strings.ADP_UpdateRequiresCommandClone; - } - else - { - switch (statementType) - { - case StatementType.Select: - resource = Strings.ADP_UpdateRequiresCommandSelect; - break; - case StatementType.Insert: - resource = Strings.ADP_UpdateRequiresCommandInsert; - break; - case StatementType.Update: - resource = Strings.ADP_UpdateRequiresCommandUpdate; - break; - case StatementType.Delete: - resource = Strings.ADP_UpdateRequiresCommandDelete; - break; -#if DEBUG - case StatementType.Batch: - Debug.Assert(false, "isRowUpdatingCommand should have been true"); - goto default; -#endif - default: - throw ADP.InvalidStatementType(statementType); - } - } - return InvalidOperation(StringsHelper.GetString(resource)); - } - static internal ArgumentException UpdateMismatchRowTable(int i) - { - return Argument(StringsHelper.GetString(Strings.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture))); - } - static internal DataException RowUpdatedErrors() - { - return Data(StringsHelper.GetString(Strings.ADP_RowUpdatedErrors)); - } - static internal DataException RowUpdatingErrors() - { - return Data(StringsHelper.GetString(Strings.ADP_RowUpdatingErrors)); - } - static internal InvalidOperationException ResultsNotAllowedDuringBatch() - { - return DataAdapter(StringsHelper.GetString(Strings.ADP_ResultsNotAllowedDuringBatch)); - } - - // - // : IDbCommand - // - static internal Exception InvalidCommandTimeout(int value) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout); - } - static internal Exception DeriveParametersNotSupported(IDbCommand value) - { - return DataAdapter(StringsHelper.GetString(Strings.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); - } - static internal Exception UninitializedParameterSize(int index, Type dataType) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); - } - static internal Exception PrepareParameterType(IDbCommand cmd) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterType, cmd.GetType().Name)); - } - static internal Exception PrepareParameterSize(IDbCommand cmd) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterSize, cmd.GetType().Name)); - } - static internal Exception PrepareParameterScale(IDbCommand cmd, string type) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterScale, cmd.GetType().Name, type)); - } - static internal Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); - } - - // - // : ConnectionUtil - // - static internal Exception ConnectionIsDisabled(Exception InnerException) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionIsDisabled), InnerException); - } - static internal Exception ClosedConnectionError() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ClosedConnectionError)); - } - static internal Exception ConnectionAlreadyOpen(ConnectionState state) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); - } - static internal Exception DelegatedTransactionPresent() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DelegatedTransactionPresent)); - } - static internal Exception TransactionPresent() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_TransactionPresent)); - } - static internal Exception LocalTransactionPresent() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_LocalTransactionPresent)); - } - static internal Exception OpenConnectionPropertySet(string property, ConnectionState state) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); - } - static internal Exception EmptyDatabaseName() - { - return Argument(StringsHelper.GetString(Strings.ADP_EmptyDatabaseName)); - } - static internal Exception DatabaseNameTooLong() - { - return Argument(StringsHelper.GetString(Strings.ADP_DatabaseNameTooLong)); - } - - internal enum ConnectionError - { - BeginGetConnectionReturnsNull, - GetConnectionReturnsNull, - ConnectionOptionsMissing, - CouldNotSwitchToClosedPreviouslyOpenedState, - } - static internal Exception InternalConnectionError(ConnectionError internalError) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InternalConnectionError, (int)internalError)); - } - - internal enum InternalErrorCode - { - UnpooledObjectHasOwner = 0, - UnpooledObjectHasWrongOwner = 1, - PushingObjectSecondTime = 2, - PooledObjectHasOwner = 3, - PooledObjectInPoolMoreThanOnce = 4, - CreateObjectReturnedNull = 5, - NewObjectCannotBePooled = 6, - NonPooledObjectUsedMoreThanOnce = 7, - AttemptingToPoolOnRestrictedToken = 8, - // ConnectionOptionsInUse = 9, - ConvertSidToStringSidWReturnedNull = 10, - // UnexpectedTransactedObject = 11, - AttemptingToConstructReferenceCollectionOnStaticObject = 12, - AttemptingToEnlistTwice = 13, - CreateReferenceCollectionReturnedNull = 14, - PooledObjectWithoutPool = 15, - UnexpectedWaitAnyResult = 16, - SynchronousConnectReturnedPending = 17, - CompletedConnectReturnedPending = 18, - - NameValuePairNext = 20, - InvalidParserState1 = 21, - InvalidParserState2 = 22, - InvalidParserState3 = 23, - - InvalidBuffer = 30, - - UnimplementedSMIMethod = 40, - InvalidSmiCall = 41, - - SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50, - SqlDependencyProcessDispatcherFailureCreateInstance = 51, - SqlDependencyProcessDispatcherFailureAppDomain = 52, - SqlDependencyCommandHashIsNotAssociatedWithNotification = 53, - - UnknownTransactionFailure = 60, - } - static internal Exception InternalError(InternalErrorCode internalError) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InternalProviderError, (int)internalError)); - } - static internal Exception InternalError(InternalErrorCode internalError, Exception innerException) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InternalProviderError, (int)internalError), innerException); - } - static internal Exception InvalidConnectTimeoutValue() - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidConnectTimeoutValue)); - } - - static internal Exception InvalidConnectRetryCountValue() - { - return Argument(StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryCountValue)); - } - - static internal Exception InvalidConnectRetryIntervalValue() - { - return Argument(StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryIntervalValue)); - } - - // - // : DbDataReader - // - static internal Exception DataReaderNoData() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DataReaderNoData)); - } - static internal Exception DataReaderClosed(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DataReaderClosed, method)); - } - static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) - { - return ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); - } - static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) - { - return ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); - } - static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) - { - return IndexOutOfRange(StringsHelper.GetString(Strings.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture))); - } - static internal Exception InvalidDataLength(long length) - { - return IndexOutOfRange(StringsHelper.GetString(Strings.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); - } - static internal InvalidOperationException AsyncOperationPending() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_PendingAsyncOperation)); - } - - // - // : Stream - // - static internal Exception StreamClosed(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_StreamClosed, method)); - } - static internal IOException ErrorReadingFromStream(Exception internalException) - { - return IO(StringsHelper.GetString(Strings.SqlMisc_StreamErrorMessage), internalException); - } - - // - // : DbDataAdapter - // - static internal InvalidOperationException DynamicSQLJoinUnsupported() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLJoinUnsupported)); - } - static internal InvalidOperationException DynamicSQLNoTableInfo() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLNoTableInfo)); - } - static internal InvalidOperationException DynamicSQLNoKeyInfoDelete() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLNoKeyInfoDelete)); - } - static internal InvalidOperationException DynamicSQLNoKeyInfoUpdate() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLNoKeyInfoUpdate)); - } - static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLNoKeyInfoRowVersionDelete)); - } - static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLNoKeyInfoRowVersionUpdate)); - } - static internal InvalidOperationException DynamicSQLNestedQuote(string name, string quote) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DynamicSQLNestedQuote, name, quote)); - } - static internal InvalidOperationException NoQuoteChange() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_NoQuoteChange)); - } - static internal InvalidOperationException ComputerNameEx(int lastError) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ComputerNameEx, lastError)); - } - static internal InvalidOperationException MissingSourceCommand() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_MissingSourceCommand)); - } - static internal InvalidOperationException MissingSourceCommandConnection() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_MissingSourceCommandConnection)); - } - - // - // : IDataParameter - // - static internal ArgumentException InvalidDataType(TypeCode typecode) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidDataType, typecode.ToString())); - } - static internal ArgumentException UnknownDataType(Type dataType) - { - return Argument(StringsHelper.GetString(Strings.ADP_UnknownDataType, dataType.FullName)); - } - static internal ArgumentException DbTypeNotSupported(DbType type, Type enumtype) - { - return Argument(StringsHelper.GetString(Strings.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); - } - static internal ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) - { - return Argument(StringsHelper.GetString(Strings.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); - } - static internal ArgumentException InvalidOffsetValue(int value) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); - } - static internal ArgumentException InvalidSizeValue(int value) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); - } - static internal ArgumentException ParameterValueOutOfRange(Decimal value) - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); - } - static internal ArgumentException ParameterValueOutOfRange(SqlDecimal value) - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString())); - } - - static internal ArgumentException ParameterValueOutOfRange(String value) - { - return ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value)); - } - - static internal ArgumentException VersionDoesNotSupportDataType(string typeName) - { - return Argument(StringsHelper.GetString(Strings.ADP_VersionDoesNotSupportDataType, typeName)); - } - static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) - { // WebData 75433 - Debug.Assert(null != value, "null value on conversion failure"); - Debug.Assert(null != inner, "null inner on conversion failure"); - - Exception e; - string message = StringsHelper.GetString(Strings.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); - if (inner is ArgumentException) - { - e = new ArgumentException(message, inner); - } - else if (inner is FormatException) - { - e = new FormatException(message, inner); - } - else if (inner is InvalidCastException) - { - e = new InvalidCastException(message, inner); - } - else if (inner is OverflowException) - { - e = new OverflowException(message, inner); - } - else - { - e = inner; - } - TraceExceptionAsReturnValue(e); - return e; - } - - // - // : IDataParameterCollection - // - static internal Exception ParametersMappingIndex(int index, IDataParameterCollection collection) - { - return CollectionIndexInt32(index, collection.GetType(), collection.Count); - } - static internal Exception ParametersSourceIndex(string parameterName, IDataParameterCollection collection, Type parameterType) - { - return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType()); - } - static internal Exception ParameterNull(string parameter, IDataParameterCollection collection, Type parameterType) - { - return CollectionNullValue(parameter, collection.GetType(), parameterType); - } - static internal Exception InvalidParameterType(IDataParameterCollection collection, Type parameterType, object invalidValue) - { - return CollectionInvalidType(collection.GetType(), parameterType, invalidValue); - } - - // - // : IDbTransaction - // - static internal Exception ParallelTransactionsNotSupported(IDbConnection obj) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); - } - static internal Exception TransactionZombied(IDbTransaction obj) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_TransactionZombied, obj.GetType().Name)); - } - - static internal Exception DbRecordReadOnly(string methodname) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_DbRecordReadOnly, methodname)); - } - - static internal Exception OffsetOutOfRangeException() - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_OffsetOutOfRangeException)); - } - - // - // : DbMetaDataFactory - // - - static internal Exception AmbiguousCollectionName(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_AmbiguousCollectionName, collectionName)); - } - - static internal Exception CollectionNameIsNotUnique(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_CollectionNameISNotUnique, collectionName)); - } - - static internal Exception DataTableDoesNotExist(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_DataTableDoesNotExist, collectionName)); - } - - static internal Exception IncorrectNumberOfDataSourceInformationRows() - { - return Argument(StringsHelper.GetString(Strings.MDF_IncorrectNumberOfDataSourceInformationRows)); - } - - static internal ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue) - { - return ADP.Argument(StringsHelper.GetString(Strings.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue)); - } - - static internal Exception InvalidXml() - { - return Argument(StringsHelper.GetString(Strings.MDF_InvalidXml)); - } - - static internal Exception InvalidXmlMissingColumn(string collectionName, string columnName) - { - return Argument(StringsHelper.GetString(Strings.MDF_InvalidXmlMissingColumn, collectionName, columnName)); - } - - static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName) - { - return Argument(StringsHelper.GetString(Strings.MDF_InvalidXmlInvalidValue, collectionName, columnName)); - } - - static internal Exception MissingDataSourceInformationColumn() - { - return Argument(StringsHelper.GetString(Strings.MDF_MissingDataSourceInformationColumn)); - } - - static internal Exception MissingRestrictionColumn() - { - return Argument(StringsHelper.GetString(Strings.MDF_MissingRestrictionColumn)); - } - - static internal Exception MissingRestrictionRow() - { - return Argument(StringsHelper.GetString(Strings.MDF_MissingRestrictionRow)); - } - - static internal Exception NoColumns() - { - return Argument(StringsHelper.GetString(Strings.MDF_NoColumns)); - } - - static internal Exception QueryFailed(string collectionName, Exception e) - { - return InvalidOperation(StringsHelper.GetString(Strings.MDF_QueryFailed, collectionName), e); - } - - static internal Exception TooManyRestrictions(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_TooManyRestrictions, collectionName)); - } - - static internal Exception UnableToBuildCollection(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_UnableToBuildCollection, collectionName)); - } - - static internal Exception UndefinedCollection(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_UndefinedCollection, collectionName)); - } - - static internal Exception UndefinedPopulationMechanism(string populationMechanism) - { - return Argument(StringsHelper.GetString(Strings.MDF_UndefinedPopulationMechanism, populationMechanism)); - } - - static internal Exception UnsupportedVersion(string collectionName) - { - return Argument(StringsHelper.GetString(Strings.MDF_UnsupportedVersion, collectionName)); - } - - - // - // : CommandBuilder - // - - static internal InvalidOperationException InvalidDateTimeDigits(string dataTypeName) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidDateTimeDigits, dataTypeName)); - } - - static internal Exception InvalidFormatValue() - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidFormatValue)); - } - - static internal InvalidOperationException InvalidMaximumScale(string dataTypeName) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMaximumScale, dataTypeName)); - } - - static internal Exception LiteralValueIsInvalid(string dataTypeName) - { - return Argument(StringsHelper.GetString(Strings.ADP_LiteralValueIsInvalid, dataTypeName)); - } - - static internal Exception EvenLengthLiteralValue(string argumentName) - { - return Argument(StringsHelper.GetString(Strings.ADP_EvenLengthLiteralValue), argumentName); - } - - static internal Exception HexDigitLiteralValue(string argumentName) - { - return Argument(StringsHelper.GetString(Strings.ADP_HexDigitLiteralValue), argumentName); - } - - static internal InvalidOperationException QuotePrefixNotSet(string method) - { - return InvalidOperation(StringsHelper.GetString(Strings.ADP_QuotePrefixNotSet, method)); - } - - static internal InvalidOperationException UnableToCreateBooleanLiteral() - { - return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_UnableToCreateBooleanLiteral)); - } - - static internal Exception UnsupportedNativeDataTypeOleDb(string dataTypeName) - { - return Argument(StringsHelper.GetString(Strings.ADP_UnsupportedNativeDataTypeOleDb, dataTypeName)); - } - - // Sql Result Set and other generic message - static internal Exception InvalidArgumentValue(string methodName) - { - return Argument(StringsHelper.GetString(Strings.ADP_InvalidArgumentValue, methodName)); - } - - // global constant strings - internal const string Append = "Append"; - internal const string BeginExecuteNonQuery = "BeginExecuteNonQuery"; - internal const string BeginExecuteReader = "BeginExecuteReader"; - internal const string BeginTransaction = "BeginTransaction"; - internal const string BeginExecuteXmlReader = "BeginExecuteXmlReader"; - internal const string ChangeDatabase = "ChangeDatabase"; - internal const string Cancel = "Cancel"; - internal const string Clone = "Clone"; - internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_"; - internal const string CommitTransaction = "CommitTransaction"; - internal const string CommandTimeout = "CommandTimeout"; - internal const string Command = "Command"; - internal const string ConnectionString = "ConnectionString"; - internal const string Connection = "Connection"; - internal const string DataSetColumn = "DataSetColumn"; - internal const string DataSetTable = "DataSetTable"; - internal const string Delete = "Delete"; - internal const string DeleteCommand = "DeleteCommand"; - internal const string DeriveParameters = "DeriveParameters"; - internal const string EndExecuteNonQuery = "EndExecuteNonQuery"; - internal const string EndExecuteReader = "EndExecuteReader"; - internal const string EndExecuteXmlReader = "EndExecuteXmlReader"; - internal const string ExecuteReader = "ExecuteReader"; - internal const string ExecuteRow = "ExecuteRow"; - internal const string ExecuteNonQuery = "ExecuteNonQuery"; - internal const string ExecuteScalar = "ExecuteScalar"; - internal const string ExecuteSqlScalar = "ExecuteSqlScalar"; - internal const string ExecuteXmlReader = "ExecuteXmlReader"; - internal const string Fill = "Fill"; - internal const string FillPage = "FillPage"; - internal const string FillSchema = "FillSchema"; - internal const string GetBytes = "GetBytes"; - internal const string GetChars = "GetChars"; - internal const string GetOleDbSchemaTable = "GetOleDbSchemaTable"; - internal const string GetProperties = "GetProperties"; - internal const string GetSchema = "GetSchema"; - internal const string GetSchemaTable = "GetSchemaTable"; - internal const string GetServerTransactionLevel = "GetServerTransactionLevel"; - internal const string Insert = "Insert"; - internal const string Open = "Open"; - internal const string Parameter = "Parameter"; - internal const string ParameterBuffer = "buffer"; - internal const string ParameterCount = "count"; - internal const string ParameterDestinationType = "destinationType"; - internal const string ParameterIndex = "index"; - internal const string ParameterName = "ParameterName"; - internal const string ParameterOffset = "offset"; - internal const string ParameterSetPosition = "set_Position"; - internal const string ParameterService = "Service"; - internal const string ParameterTimeout = "Timeout"; - internal const string ParameterUserData = "UserData"; - internal const string Prepare = "Prepare"; - internal const string QuoteIdentifier = "QuoteIdentifier"; - internal const string Read = "Read"; - internal const string ReadAsync = "ReadAsync"; - internal const string Remove = "Remove"; - internal const string RollbackTransaction = "RollbackTransaction"; - internal const string SaveTransaction = "SaveTransaction"; - internal const string SetProperties = "SetProperties"; - internal const string SourceColumn = "SourceColumn"; - internal const string SourceVersion = "SourceVersion"; - internal const string SourceTable = "SourceTable"; - internal const string UnquoteIdentifier = "UnquoteIdentifier"; - internal const string Update = "Update"; - internal const string UpdateCommand = "UpdateCommand"; - internal const string UpdateRows = "UpdateRows"; - - internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; - internal const int DecimalMaxPrecision = 29; - internal const int DecimalMaxPrecision28 = 28; // there are some cases in Odbc where we need that ... - internal const int DefaultCommandTimeout = 30; - internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; - internal const int InfiniteConnectionTimeout = 0; // infinite connection timeout identifier in seconds - internal const int MaxBufferAccessTokenExpiry = 600; // max duration for buffer in seconds - internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections - internal const float FailoverTimeoutStepForTnir = 0.125F; // Fraction of timeout to use in case of Transparent Network IP resolution. - internal const int MinimumTimeoutForTnirMs = 500; // The first login attempt in Transparent network IP Resolution - - // security issue, don't rely upon static public readonly values - AS/URT 109635 - static internal readonly String StrEmpty = ""; // String.Empty - - static internal readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero - static internal readonly int PtrSize = IntPtr.Size; - static internal readonly IntPtr InvalidPtr = new IntPtr(-1); // use for INVALID_HANDLE - static internal readonly IntPtr RecordsUnaffected = new IntPtr(-1); - - static internal readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero); - - internal const int CharSize = System.Text.UnicodeEncoding.CharSize; - - static internal bool CompareInsensitiveInvariant(string strvalue, string strconst) - { - return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase)); - } - - static internal Delegate FindBuilder(MulticastDelegate mcd) - { // V1.2.3300 - if (null != mcd) - { - Delegate[] d = mcd.GetInvocationList(); - for (int i = 0; i < d.Length; i++) - { - if (d[i].Target is DbCommandBuilder) - return d[i]; - } - } - - return null; - } - - static internal readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform); - static internal readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5)); - - static internal SysTx.Transaction GetCurrentTransaction() - { - SysTx.Transaction transaction = SysTx.Transaction.Current; - return transaction; - } - - static internal void SetCurrentTransaction(SysTx.Transaction transaction) - { - SysTx.Transaction.Current = transaction; - } - - static internal SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction) - { - SysTx.IDtcTransaction oleTxTransaction = null; - - if (null != transaction) - { - oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction); - } - return oleTxTransaction; - } - - [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] - static internal bool IsSysTxEqualSysEsTransaction() - { - // This Method won't JIT inproc (ES isn't available), so we code it - // separately and call it behind an if statement. - bool result = (!SysES.ContextUtil.IsInTransaction && null == SysTx.Transaction.Current) - || (SysES.ContextUtil.IsInTransaction && SysTx.Transaction.Current == (SysTx.Transaction)SysES.ContextUtil.SystemTransaction); - return result; - } - - static internal bool NeedManualEnlistment() - { - // We need to force a manual enlistment of transactions for ODBC and - // OLEDB whenever the current SysTx transaction != the SysTx transaction - // on the EnterpriseServices ContextUtil, or when ES.ContextUtil is - // not available and there is a non-null current SysTx transaction. - if (IsWindowsNT) - { // we can reference SysTx just not use it on Win9X, we can't ever reference SysES on Win9X - bool isEnterpriseServicesOK = !InOutOfProcHelper.InProc; - if ((isEnterpriseServicesOK && !IsSysTxEqualSysEsTransaction()) - || (!isEnterpriseServicesOK && null != SysTx.Transaction.Current)) - { - return true; - } - } - return false; - } - - static internal long TimerCurrent() - { - return DateTime.UtcNow.ToFileTimeUtc(); - } - - static internal long TimerFromSeconds(int seconds) - { - long result = checked((long)seconds * TimeSpan.TicksPerSecond); - return result; - } - - static internal long TimerFromMilliseconds(long milliseconds) - { - long result = checked(milliseconds * TimeSpan.TicksPerMillisecond); - return result; - } - - static internal bool TimerHasExpired(long timerExpire) - { - bool result = TimerCurrent() > timerExpire; - return result; - } - - static internal long TimerRemaining(long timerExpire) - { - long timerNow = TimerCurrent(); - long result = checked(timerExpire - timerNow); - return result; - } - - static internal long TimerRemainingMilliseconds(long timerExpire) - { - long result = TimerToMilliseconds(TimerRemaining(timerExpire)); - return result; - } - - static internal long TimerRemainingSeconds(long timerExpire) - { - long result = TimerToSeconds(TimerRemaining(timerExpire)); - return result; - } - - static internal long TimerToMilliseconds(long timerValue) - { - long result = timerValue / TimeSpan.TicksPerMillisecond; - return result; - } - - static private long TimerToSeconds(long timerValue) - { - long result = timerValue / TimeSpan.TicksPerSecond; - return result; - } - - [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")] - static internal string MachineName() - { - // Note: In Longhorn you'll be able to rename a machine without - // rebooting. Therefore, don't cache this machine name. - return Environment.MachineName; - } - - internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) - { - var resultString = new StringBuilder(unQuotedString.Length + quoteSuffix.Length + quoteSuffix.Length); - AppendQuotedString(resultString, quotePrefix, quoteSuffix, unQuotedString); - return resultString.ToString(); - } - - internal static string AppendQuotedString(StringBuilder buffer, string quotePrefix, string quoteSuffix, string unQuotedString) - { - if (!string.IsNullOrEmpty(quotePrefix)) - { - buffer.Append(quotePrefix); - } - - // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar". - if (!string.IsNullOrEmpty(quoteSuffix)) - { - int start = buffer.Length; - buffer.Append(unQuotedString); - buffer.Replace(quoteSuffix, quoteSuffix + quoteSuffix, start, unQuotedString.Length); - buffer.Append(quoteSuffix); - } - else - { - buffer.Append(unQuotedString); - } - - return buffer.ToString(); - } - - static internal string BuildMultiPartName(string[] strings) - { - StringBuilder bld = new StringBuilder(); - // Assume we want to build a full multi-part name with all parts except trimming separators for - // leading empty names (null or empty strings, but not whitespace). Separators in the middle - // should be added, even if the name part is null/empty, to maintain proper location of the parts. - for (int i = 0; i < strings.Length; i++) - { - if (0 < bld.Length) - { - bld.Append('.'); - } - if (null != strings[i] && 0 != strings[i].Length) - { - bld.Append(BuildQuotedString("[", "]", strings[i])); - } - } - return bld.ToString(); - } - - private const string hexDigits = "0123456789abcdef"; - - static internal byte[] ByteArrayFromString(string hexString, string dataTypeName) - { - if ((hexString.Length & 0x1) != 0) - { - throw ADP.LiteralValueIsInvalid(dataTypeName); - } - char[] c = hexString.ToCharArray(); - byte[] b = new byte[hexString.Length / 2]; - - CultureInfo invariant = CultureInfo.InvariantCulture; - for (int i = 0; i < hexString.Length; i += 2) - { - int h = hexDigits.IndexOf(Char.ToLower(c[i], invariant)); - int l = hexDigits.IndexOf(Char.ToLower(c[i + 1], invariant)); - - if (h < 0 || l < 0) - { - throw ADP.LiteralValueIsInvalid(dataTypeName); - } - b[i / 2] = (byte)((h << 4) | l); - } - return b; - } - - static internal void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString) - { - - // note special characters list is from character escapes - // in the MSDN regular expression language elements documentation - // added ] since escaping it seems necessary - const string specialCharacters = ".$^{[(|)*+?\\]"; - - foreach (char currentChar in unescapedString) - { - if (specialCharacters.IndexOf(currentChar) >= 0) - { - escapedString.Append("\\"); - } - escapedString.Append(currentChar); - } - return; - } - - - - - static internal string FixUpDecimalSeparator(string numericString, - Boolean formatLiteral, - string decimalSeparator, - char[] exponentSymbols) - { - String returnString; - // don't replace the decimal separator if the string is in exponent format - if (numericString.IndexOfAny(exponentSymbols) == -1) - { - - // if the user has set a decimal separator use it, if not use the current culture's value - if (ADP.IsEmpty(decimalSeparator) == true) - { - decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; - } - if (formatLiteral == true) - { - returnString = numericString.Replace(".", decimalSeparator); - } - else - { - returnString = numericString.Replace(decimalSeparator, "."); - } - } - else - { - returnString = numericString; - } - return returnString; - } - - [FileIOPermission(SecurityAction.Assert, AllFiles = FileIOPermissionAccess.PathDiscovery)] - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal string GetFullPath(string filename) - { // MDAC 77686 - return Path.GetFullPath(filename); - } - - // TODO: cache machine name and listen to longhorn event to reset it - static internal string GetComputerNameDnsFullyQualified() - { - const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT - const int ERROR_MORE_DATA = 234; // winerror.h - - string value; - if (IsPlatformNT5) - { - int length = 0; // length parameter must be zero if buffer is null - // query for the required length - // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive - int getComputerNameExError = 0; - if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) - { - getComputerNameExError = Marshal.GetLastWin32Error(); - } - if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) - { - throw ADP.ComputerNameEx(getComputerNameExError); - } - - StringBuilder buffer = new StringBuilder(length); - length = buffer.Capacity; - if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) - { - throw ADP.ComputerNameEx(Marshal.GetLastWin32Error()); - } - - // Note: In Longhorn you'll be able to rename a machine without - // rebooting. Therefore, don't cache this machine name. - value = buffer.ToString(); - } - else - { - value = ADP.MachineName(); - } - return value; - } - - - // SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal Stream GetFileStream(string filename) - { - (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); - try - { - return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); - } - finally - { - FileIOPermission.RevertAssert(); - } - } - - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal FileVersionInfo GetVersionInfo(string filename) - { - (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); // MDAC 62038 - try - { - return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411 - } - finally - { - FileIOPermission.RevertAssert(); - } - } - - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal Stream GetXmlStreamFromValues(String[] values, String errorString) - { - if (values.Length != 1) - { - throw ADP.ConfigWrongNumberOfValues(errorString); - } - return ADP.GetXmlStream(values[0], errorString); - } - - // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\ - // 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 - // under the runtime folder. - // This method returns stream to open file, so its ResourceExposure value is ResourceScope.Machine. - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal Stream GetXmlStream(String value, String errorString) - { - Stream XmlStream; - const string config = "config\\"; - // get location of config directory - string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); - if (rootPath == null) - { - throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString); - } - StringBuilder tempstring = new StringBuilder(rootPath.Length + config.Length + value.Length); - tempstring.Append(rootPath); - tempstring.Append(config); - tempstring.Append(value); - String fullPath = tempstring.ToString(); - - // don't allow relative paths - if (ADP.GetFullPath(fullPath) != fullPath) - { - throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString); - } - - try - { - XmlStream = ADP.GetFileStream(fullPath); - } - catch (Exception e) - { - // UNDONE - should not be catching all exceptions!!! - if (!ADP.IsCatchableExceptionType(e)) - { - throw; - } - throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString); - } - - return XmlStream; - - } - - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal object ClassesRootRegistryValue(string subkey, string queryvalue) - { // MDAC 77697 - (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CLASSES_ROOT\\" + subkey)).Assert(); // MDAC 62028 - try - { - using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) - { - return ((null != key) ? key.GetValue(queryvalue) : null); - } - } - catch (SecurityException e) - { - // Even though we assert permission - it's possible there are - // ACL's on registry that cause SecurityException to be thrown. - ADP.TraceExceptionWithoutRethrow(e); - return null; - } - finally - { - RegistryPermission.RevertAssert(); - } - } - - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - static internal object LocalMachineRegistryValue(string subkey, string queryvalue) - { // MDAC 77697 - (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028 - try - { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) - { - return ((null != key) ? key.GetValue(queryvalue) : null); - } - } - catch (SecurityException e) - { - // Even though we assert permission - it's possible there are - // ACL's on registry that cause SecurityException to be thrown. - ADP.TraceExceptionWithoutRethrow(e); - return null; - } - finally - { - RegistryPermission.RevertAssert(); - } - } - - //// SxS: although this method uses registry, it does not expose anything out - //[ResourceExposure(ResourceScope.None)] - //[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - //static internal void CheckVersionMDAC(bool ifodbcelseoledb) { - // int major, minor, build; - // string version; - - // try { - // version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer"); - // if (ADP.IsEmpty(version)) { - // string filename = (string)ADP.ClassesRootRegistryValue(Microsoft.Data.OleDb.ODB.DataLinks_CLSID, ADP.StrEmpty); - // FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); // MDAC 60411 - // major = versionInfo.FileMajorPart; - // minor = versionInfo.FileMinorPart; - // build = versionInfo.FileBuildPart; - // version = versionInfo.FileVersion; - // } - // else { - // string[] parts = version.Split('.'); - // major = Int32.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture); - // minor = Int32.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture); - // build = Int32.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture); - // Int32.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture); - // } - // } - // catch(Exception e) { - // // UNDONE - should not be catching all exceptions!!! - // if (!ADP.IsCatchableExceptionType(e)) { - // throw; - // } - - // throw Microsoft.Data.OleDb.ODB.MDACNotAvailable(e); - // } - - // // disallow any MDAC version before MDAC 2.6 rtm - // // include MDAC 2.51 that ships with Win2k - // if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526))))) { // MDAC 66628 - // if (ifodbcelseoledb) { - // throw ADP.DataAdapter(ResHelper.GetString(Strings.Odbc_MDACWrongVersion, version)); - // } - // else { - // throw ADP.DataAdapter(ResHelper.GetString(Strings.OleDb_MDACWrongVersion, version)); - // } - // } - //} - - // the return value is true if the string was quoted and false if it was not - // this allows the caller to determine if it is an error or not for the quotedString to not be quoted - static internal Boolean RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) - { - - int prefixLength; - if (quotePrefix == null) - { - prefixLength = 0; - } - else - { - prefixLength = quotePrefix.Length; - } - - int suffixLength; - if (quoteSuffix == null) - { - suffixLength = 0; - } - else - { - suffixLength = quoteSuffix.Length; - } - - if ((suffixLength + prefixLength) == 0) - { - unquotedString = quotedString; - return true; - } - - if (quotedString == null) - { - unquotedString = quotedString; - return false; - } - - int quotedStringLength = quotedString.Length; - - // is the source string too short to be quoted - if (quotedStringLength < prefixLength + suffixLength) - { - unquotedString = quotedString; - return false; - } - - // is the prefix present? - if (prefixLength > 0) - { - if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false) - { - unquotedString = quotedString; - return false; - } - } - - // is the suffix present? - if (suffixLength > 0) - { - if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false) - { - unquotedString = quotedString; - return false; - } - unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix); - } - else - { - unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength); - } - return true; - } - - static internal DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) - { - const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified; - - // equivalent to but faster than 'return dataTable.Select("", "", rowStates);' - int countAdded = 0, countDeleted = 0, countModifed = 0; - DataRowCollection rowCollection = dataTable.Rows; - foreach (DataRow dataRow in rowCollection) - { - switch (dataRow.RowState) - { - case DataRowState.Added: - countAdded++; - break; - case DataRowState.Deleted: - countDeleted++; - break; - case DataRowState.Modified: - countModifed++; - break; - default: - Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState"); - break; - } - } - DataRow[] dataRows = new DataRow[countAdded + countDeleted + countModifed]; - if (sorted) - { - countModifed = countAdded + countDeleted; - countDeleted = countAdded; - countAdded = 0; - - foreach (DataRow dataRow in rowCollection) - { - switch (dataRow.RowState) - { - case DataRowState.Added: - dataRows[countAdded++] = dataRow; - break; - case DataRowState.Deleted: - dataRows[countDeleted++] = dataRow; - break; - case DataRowState.Modified: - dataRows[countModifed++] = dataRow; - break; - default: - Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState"); - break; - } - } - } - else - { - int index = 0; - foreach (DataRow dataRow in rowCollection) - { - if (0 != (dataRow.RowState & rowStates)) - { - dataRows[index++] = dataRow; - if (index == dataRows.Length) - { - break; - } - } - } - } - return dataRows; - } - - internal static int StringLength(string inputString) - { - return ((null != inputString) ? inputString.Length : 0); - } - - // { "a", "a", "a" } -> { "a", "a1", "a2" } - // { "a", "a", "a1" } -> { "a", "a2", "a1" } - // { "a", "A", "a" } -> { "a", "A1", "a2" } - // { "a", "A", "a1" } -> { "a", "A2", "a1" } // MDAC 66718 - static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray) - { - Dictionary hash = new Dictionary(columnNameArray.Length); - - int startIndex = columnNameArray.Length; // lowest non-unique index - for (int i = columnNameArray.Length - 1; 0 <= i; --i) - { - string columnName = columnNameArray[i]; - if ((null != columnName) && (0 < columnName.Length)) - { - columnName = columnName.ToLower(CultureInfo.InvariantCulture); - int index; - if (hash.TryGetValue(columnName, out index)) - { - startIndex = Math.Min(startIndex, index); - } - hash[columnName] = i; - } - else - { - columnNameArray[i] = ADP.StrEmpty; // MDAC 66681 - startIndex = i; - } - } - int uniqueIndex = 1; - for (int i = startIndex; i < columnNameArray.Length; ++i) - { - string columnName = columnNameArray[i]; - if (0 == columnName.Length) - { // generate a unique name - columnNameArray[i] = "Column"; - uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex); - } - else - { - columnName = columnName.ToLower(CultureInfo.InvariantCulture); - if (i != hash[columnName]) - { - GenerateUniqueName(hash, ref columnNameArray[i], i, 1); // MDAC 66718 - } - } - } - } - - static private int GenerateUniqueName(Dictionary hash, ref string columnName, int index, int uniqueIndex) - { - for (; ; ++uniqueIndex) - { - string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture); - string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); // MDAC 66978 - if (!hash.ContainsKey(lowerName)) - { - - columnName = uniqueName; - hash.Add(lowerName, index); - break; - } - } - return uniqueIndex; - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - static internal IntPtr IntPtrOffset(IntPtr pbase, Int32 offset) - { - if (4 == ADP.PtrSize) - { - return (IntPtr)checked(pbase.ToInt32() + offset); - } - Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747 - return (IntPtr)checked(pbase.ToInt64() + offset); - } - - static internal int IntPtrToInt32(IntPtr value) - { - if (4 == ADP.PtrSize) - { - return (int)value; - } - else - { - long lval = (long)value; - lval = Math.Min((long)Int32.MaxValue, lval); - lval = Math.Max((long)Int32.MinValue, lval); - return (int)lval; - } - } - - // TODO: are those names appropriate for common code? - static internal int SrcCompare(string strA, string strB) - { // this is null safe - return ((strA == strB) ? 0 : 1); - } - - static internal int DstCompare(string strA, string strB) - { // this is null safe - return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions); - } - - static internal bool IsDirection(IDataParameter value, ParameterDirection condition) - { -#if DEBUG - IsDirectionValid(condition); -#endif - return (condition == (condition & value.Direction)); - } -#if DEBUG - static private void IsDirectionValid(ParameterDirection value) - { - switch (value) - { // @perfnote: Enum.IsDefined - case ParameterDirection.Input: - case ParameterDirection.Output: - case ParameterDirection.InputOutput: - case ParameterDirection.ReturnValue: - break; - default: - throw ADP.InvalidParameterDirection(value); - } - } -#endif - - static internal bool IsEmpty(string str) - { - return ((null == str) || (0 == str.Length)); - } - - static internal bool IsEmptyArray(string[] array) - { - return ((null == array) || (0 == array.Length)); - } - - static internal bool IsNull(object value) - { - if ((null == value) || (DBNull.Value == value)) - { - return true; - } - INullable nullable = (value as INullable); - return (null != nullable) && nullable.IsNull; - } - - static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) - { - if ((value == null) || (value == DBNull.Value)) - { - isNull = true; - isSqlType = false; - } - else - { - INullable nullable = (value as INullable); - if (nullable != null) - { - isNull = nullable.IsNull; - // Duplicated from DataStorage.cs - // For back-compat, SqlXml is not in this list - isSqlType = ((value is SqlBinary) || - (value is SqlBoolean) || - (value is SqlByte) || - (value is SqlBytes) || - (value is SqlChars) || - (value is SqlDateTime) || - (value is SqlDecimal) || - (value is SqlDouble) || - (value is SqlGuid) || - (value is SqlInt16) || - (value is SqlInt32) || - (value is SqlInt64) || - (value is SqlMoney) || - (value is SqlSingle) || - (value is SqlString)); - } - else - { - isNull = false; - isSqlType = false; - } - } - } - - private static Version _systemDataVersion; - static internal Version GetAssemblyVersion() - { - // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time - if (_systemDataVersion == null) - { - _systemDataVersion = new Version(ThisAssembly.InformationalVersion); - } - - return _systemDataVersion; - } - - static internal readonly string[] AzureSqlServerEndpoints = {StringsHelper.GetString(Strings.AZURESQL_GenericEndpoint), - StringsHelper.GetString(Strings.AZURESQL_GermanEndpoint), - StringsHelper.GetString(Strings.AZURESQL_UsGovEndpoint), - StringsHelper.GetString(Strings.AZURESQL_ChinaEndpoint)}; - - // This method assumes dataSource parameter is in TCP connection string format. - static internal bool IsAzureSqlServerEndpoint(string dataSource) - { - // remove server port - int i = dataSource.LastIndexOf(','); - if (i >= 0) - { - dataSource = dataSource.Substring(0, i); - } - - // check for the instance name - i = dataSource.LastIndexOf('\\'); - if (i >= 0) - { - dataSource = dataSource.Substring(0, i); - } - - // trim redundant whitespaces - dataSource = dataSource.Trim(); - - // check if servername end with any azure endpoints - for (i = 0; i < AzureSqlServerEndpoints.Length; i++) - { - if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs index 558363d47c..bfcb461602 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs @@ -143,7 +143,7 @@ private Wrapper() { } [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] static internal void ClearErrorInfo() { // MDAC 68199 - SafeNativeMethods.SetErrorInfo(0, ADP.PtrZero); + SafeNativeMethods.SetErrorInfo(0, ADP.s_ptrZero); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs index 30a3bc7b99..3e44134e7f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs @@ -71,7 +71,7 @@ internal string PtrToStringUni(int offset) { offset += BaseOffset; Validate(offset, 2); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); string value = null; bool mustRelease = false; @@ -100,7 +100,7 @@ internal String PtrToStringUni(int offset, int length) { offset += BaseOffset; Validate(offset, 2 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); string value = null; bool mustRelease = false; @@ -158,7 +158,7 @@ internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int le { offset += BaseOffset; Validate(offset, length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); @@ -191,7 +191,7 @@ internal char[] ReadChars(int offset, char[] destination, int startIndex, int le { offset += BaseOffset; Validate(offset, 2 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); @@ -250,7 +250,7 @@ internal void ReadInt16Array(int offset, short[] destination, int startIndex, in { offset += BaseOffset; Validate(offset, 2 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); @@ -302,7 +302,7 @@ internal void ReadInt32Array(int offset, int[] destination, int startIndex, int { offset += BaseOffset; Validate(offset, 4 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); @@ -354,7 +354,7 @@ internal IntPtr ReadIntPtr(int offset) { offset += BaseOffset; ValidateCheck(offset, IntPtr.Size); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); IntPtr value; bool mustRelease = false; @@ -399,7 +399,7 @@ private void StructureToPtr(int offset, object structure) Debug.Assert(null != structure, "null structure"); offset += BaseOffset; ValidateCheck(offset, Marshal.SizeOf(structure.GetType())); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -447,7 +447,7 @@ internal void WriteBytes(int offset, byte[] source, int startIndex, int length) { offset += BaseOffset; Validate(offset, length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); @@ -473,7 +473,7 @@ internal void WriteCharArray(int offset, char[] source, int startIndex, int leng { offset += BaseOffset; Validate(offset, 2 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); @@ -528,7 +528,7 @@ internal void WriteInt16Array(int offset, short[] source, int startIndex, int le { offset += BaseOffset; Validate(offset, 2 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); @@ -578,7 +578,7 @@ internal void WriteInt32Array(int offset, int[] source, int startIndex, int leng { offset += BaseOffset; Validate(offset, 4 * length); - Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); + Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 28d2a9679f..701719796a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -449,7 +449,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D } // We don't support connection pooling on Win9x; it lacks too many of the APIs we require. - if ((null == poolOptions) && ADP.IsWindowsNT) + if ((null == poolOptions) && ADP.s_isWindowsNT) { if (null != connectionPoolGroup) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 8d04056add..f39be43eee 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -485,7 +485,7 @@ internal DbConnectionPool( DbConnectionPoolIdentity identity, DbConnectionPoolProviderInfo connectionPoolProviderInfo) { - Debug.Assert(ADP.IsWindowsNT, "Attempting to construct a connection pool on Win9x?"); + Debug.Assert(ADP.s_isWindowsNT, "Attempting to construct a connection pool on Win9x?"); Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); if ((null != identity) && identity.IsRestricted) @@ -516,7 +516,7 @@ internal DbConnectionPool( _pooledDbAuthenticationContexts = new ConcurrentDictionary(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/, capacity: 2); - if (ADP.IsPlatformNT5) + if (ADP.s_isPlatformNT5) { _transactedConnectionPool = new TransactedConnectionPool(this); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs index f502d1b2a4..9ebe2b48f1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs @@ -95,7 +95,7 @@ sealed internal class Counter internal Counter(string categoryName, string instanceName, string counterName, PerformanceCounterType counterType) { - if (ADP.IsPlatformNT5) + if (ADP.s_isPlatformNT5) { try { @@ -184,7 +184,7 @@ protected DbConnectionPoolCounters(string categoryName, string categoryHelp) if (!ADP.IsEmpty(categoryName)) { - if (ADP.IsPlatformNT5) + if (ADP.s_isPlatformNT5) { instanceName = GetInstanceName(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 6aa0847667..cd7c387202 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -51,7 +51,7 @@ sealed internal class DbConnectionPoolGroup internal DbConnectionPoolGroup(DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions) { Debug.Assert(null != connectionOptions, "null connection options"); - Debug.Assert(null == poolGroupOptions || ADP.IsWindowsNT, "should not have pooling options on Win9x"); + Debug.Assert(null == poolGroupOptions || ADP.s_isWindowsNT, "should not have pooling options on Win9x"); _connectionOptions = connectionOptions; _poolKey = key; @@ -189,7 +189,7 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor DbConnectionPool pool = null; if (null != _poolGroupOptions) { - Debug.Assert(ADP.IsWindowsNT, "should not be pooling on Win9x"); + Debug.Assert(ADP.s_isWindowsNT, "should not be pooling on Win9x"); DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity; if (_poolGroupOptions.PoolByIdentity) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs index 341569145d..2bbf57eb76 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs @@ -24,7 +24,7 @@ sealed internal class DbConnectionPoolIdentity private const int Win32_CreateWellKnownSid = 5; static public readonly DbConnectionPoolIdentity NoIdentity = new DbConnectionPoolIdentity(String.Empty, false, true); - static private readonly byte[] NetworkSid = (ADP.IsWindowsNT ? CreateWellKnownSid(WellKnownSidType.NetworkSid) : null); + static private readonly byte[] NetworkSid = (ADP.s_isWindowsNT ? CreateWellKnownSid(WellKnownSidType.NetworkSid) : null); static private DbConnectionPoolIdentity _lastIdentity = null; private readonly string _sidString; @@ -100,7 +100,7 @@ static internal DbConnectionPoolIdentity GetCurrent() // to validate the user on 9x, so simply don't. It is a known issue in // native, and we will handle this the same way. - if (!ADP.IsWindowsNT) + if (!ADP.s_isWindowsNT) { return NoIdentity; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs index 222015dfde..2d8b080be7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs @@ -57,7 +57,7 @@ internal SqlClientPermission(SqlConnectionString constr) : base(PermissionState. } if ((null == constr) || constr.IsEmpty) { - base.Add(ADP.StrEmpty, ADP.StrEmpty, KeyRestrictionBehavior.AllowOnly); + base.Add("", "", KeyRestrictionBehavior.AllowOnly); } } @@ -376,7 +376,7 @@ override public SecurityElement ToXml() tmp = value.Restrictions; tmp = EncodeXmlValue(tmp); if (null == tmp) - { tmp = ADP.StrEmpty; } + { tmp = ""; } valueElement.AddAttribute(XmlStr._KeyRestrictions, tmp); tmp = value.Behavior.ToString(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index dffc3404c4..75200e6916 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -754,11 +754,7 @@ protected override DbTransaction DbTransaction ] public override string CommandText { - get - { - string value = _commandText; - return ((null != value) ? value : ADP.StrEmpty); - } + get => _commandText ?? ""; set { SqlClientEventSource.Log.TryTraceEvent(" {0}, String Value = '{1}'", ObjectID, value); @@ -796,7 +792,7 @@ public override int CommandTimeout SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); if (value < 0) { - throw ADP.InvalidCommandTimeout(value); + throw ADP.InvalidCommandTimeout(value, nameof(CommandTimeout)); } if (value != _commandTimeout) @@ -1057,7 +1053,7 @@ public override void Prepare() else { // Validate the command outside of the try\catch to avoid putting the _stateObj on error - ValidateCommand(ADP.Prepare, false /*not async*/); + ValidateCommand(nameof(Prepare), false /*not async*/); bool processFinallyBlock = true; TdsParser bestEffortCleanupTarget = null; @@ -1383,8 +1379,8 @@ public override object ExecuteScalar() WriteBeginExecuteEvent(); SqlDataReader ds; ds = IsProviderRetriable ? - RunExecuteReaderWithRetry(0, RunBehavior.ReturnImmediately, true, ADP.ExecuteScalar) : - RunExecuteReader(0, RunBehavior.ReturnImmediately, true, ADP.ExecuteScalar); + RunExecuteReaderWithRetry(0, RunBehavior.ReturnImmediately, true, nameof(ExecuteScalar)) : + RunExecuteReader(0, RunBehavior.ReturnImmediately, true, nameof(ExecuteScalar)); object result = CompleteExecuteScalar(ds, false); success = true; return result; @@ -1464,11 +1460,11 @@ public override int ExecuteNonQuery() bool usedCache; if (IsProviderRetriable) { - InternalExecuteNonQueryWithRetry(ADP.ExecuteNonQuery, sendToPipe: false, CommandTimeout, out usedCache, asyncWrite: false, inRetry: false); + InternalExecuteNonQueryWithRetry(nameof(ExecuteNonQuery), sendToPipe: false, CommandTimeout, out usedCache, asyncWrite: false, inRetry: false); } else { - InternalExecuteNonQuery(null, ADP.ExecuteNonQuery, sendToPipe: false, CommandTimeout, out usedCache); + InternalExecuteNonQuery(null, nameof(ExecuteNonQuery), sendToPipe: false, CommandTimeout, out usedCache); } success = true; return _rowsAffected; @@ -1504,7 +1500,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) { statistics = SqlStatistics.StartTimer(Statistics); bool usedCache; - InternalExecuteNonQuery(null, ADP.ExecuteNonQuery, true, CommandTimeout, out usedCache); + InternalExecuteNonQuery(null, nameof(ExecuteNonQuery), true, CommandTimeout, out usedCache); } finally { @@ -1562,7 +1558,7 @@ private IAsyncResult BeginExecuteNonQueryInternal(CommandBehavior behavior, Asyn bool usedCache; try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool. - Task execNQ = InternalExecuteNonQuery(localCompletion, ADP.BeginExecuteNonQuery, false, timeout, out usedCache, asyncWrite, inRetry: inRetry); + Task execNQ = InternalExecuteNonQuery(localCompletion, nameof(BeginExecuteNonQuery), false, timeout, out usedCache, asyncWrite, inRetry: inRetry); if (execNQ != null) { AsyncHelper.ContinueTaskWithState(execNQ, localCompletion, this, (object state) => ((SqlCommand)state).BeginExecuteNonQueryInternalReadStage(localCompletion)); @@ -1587,7 +1583,7 @@ private IAsyncResult BeginExecuteNonQueryInternal(CommandBehavior behavior, Asyn // When we use query caching for parameter encryption we need to retry on specific errors. // In these cases finalize the call internally and trigger a retry when needed. - if (!TriggerInternalEndAndRetryIfNecessary(behavior, stateObject, timeout, ADP.EndExecuteNonQuery, usedCache, inRetry, asyncWrite, globalCompletion, localCompletion, InternalEndExecuteNonQuery, BeginExecuteNonQueryInternal)) + if (!TriggerInternalEndAndRetryIfNecessary(behavior, stateObject, timeout, nameof(EndExecuteNonQuery), usedCache, inRetry, asyncWrite, globalCompletion, localCompletion, InternalEndExecuteNonQuery, BeginExecuteNonQueryInternal)) { globalCompletion = localCompletion; } @@ -1625,7 +1621,7 @@ private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection); // must finish caching information before ReadSni which can activate the callback before returning - cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteNonQuery, _activeConnection); + cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteNonQuery), _activeConnection); _stateObj.ReadSni(completion); } #if DEBUG @@ -1801,7 +1797,7 @@ private int EndExecuteNonQueryInternal(IAsyncResult asyncResult) try { statistics = SqlStatistics.StartTimer(Statistics); - int result = (int)InternalEndExecuteNonQuery(asyncResult, ADP.EndExecuteNonQuery, isInternal: false); + int result = (int)InternalEndExecuteNonQuery(asyncResult, nameof(EndExecuteNonQuery), isInternal: false); success = true; return result; } @@ -2093,8 +2089,8 @@ public XmlReader ExecuteXmlReader() // use the reader to consume metadata SqlDataReader ds; ds = IsProviderRetriable ? - RunExecuteReaderWithRetry(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, ADP.ExecuteXmlReader) : - RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, ADP.ExecuteXmlReader); + RunExecuteReaderWithRetry(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, nameof(ExecuteXmlReader)) : + RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, nameof(ExecuteXmlReader)); XmlReader result = CompleteXmlReader(ds); success = true; return result; @@ -2162,7 +2158,7 @@ private IAsyncResult BeginExecuteXmlReaderInternal(CommandBehavior behavior, Asy Task writeTask; try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool. - RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, ADP.BeginExecuteXmlReader, localCompletion, timeout, out writeTask, out usedCache, asyncWrite, inRetry); + RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, nameof(BeginExecuteXmlReader), localCompletion, timeout, out writeTask, out usedCache, asyncWrite, inRetry); } catch (Exception e) { @@ -2188,7 +2184,7 @@ private IAsyncResult BeginExecuteXmlReaderInternal(CommandBehavior behavior, Asy // When we use query caching for parameter encryption we need to retry on specific errors. // In these cases finalize the call internally and trigger a retry when needed. - if (!TriggerInternalEndAndRetryIfNecessary(behavior, stateObject, timeout, ADP.EndExecuteXmlReader, usedCache, inRetry, asyncWrite, globalCompletion, localCompletion, InternalEndExecuteReader, BeginExecuteXmlReaderInternal)) + if (!TriggerInternalEndAndRetryIfNecessary(behavior, stateObject, timeout, nameof(EndExecuteXmlReader), usedCache, inRetry, asyncWrite, globalCompletion, localCompletion, InternalEndExecuteReader, BeginExecuteXmlReaderInternal)) { globalCompletion = localCompletion; } @@ -2226,7 +2222,7 @@ private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection); // must finish caching information before ReadSni which can activate the callback before returning - cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteXmlReader, _activeConnection); + cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteXmlReader), _activeConnection); _stateObj.ReadSni(completion); } #if DEBUG @@ -2314,7 +2310,7 @@ private XmlReader EndExecuteXmlReaderInternal(IAsyncResult asyncResult) int? sqlExceptionNumber = null; try { - XmlReader result = CompleteXmlReader(InternalEndExecuteReader(asyncResult, ADP.EndExecuteXmlReader, isInternal: false), true); + XmlReader result = CompleteXmlReader(InternalEndExecuteReader(asyncResult, nameof(EndExecuteXmlReader), isInternal: false), true); success = true; return result; } @@ -2399,7 +2395,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); - return ExecuteReader(behavior, ADP.ExecuteReader); + return ExecuteReader(behavior, nameof(ExecuteReader)); } private SqlDataReader ExecuteReaderWithRetry(CommandBehavior behavior, string method) @@ -2416,8 +2412,8 @@ private SqlDataReader ExecuteReaderWithRetry(CommandBehavior behavior, string me { statistics = SqlStatistics.StartTimer(Statistics); return IsProviderRetriable ? - ExecuteReaderWithRetry(CommandBehavior.Default, ADP.ExecuteReader) : - ExecuteReader(CommandBehavior.Default, ADP.ExecuteReader); + ExecuteReaderWithRetry(CommandBehavior.Default, nameof(ExecuteReader)) : + ExecuteReader(CommandBehavior.Default, nameof(ExecuteReader)); } finally { @@ -2434,8 +2430,8 @@ private SqlDataReader ExecuteReaderWithRetry(CommandBehavior behavior, string me SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); return IsProviderRetriable ? - ExecuteReaderWithRetry(behavior, ADP.ExecuteReader) : - ExecuteReader(behavior, ADP.ExecuteReader); + ExecuteReaderWithRetry(behavior, nameof(ExecuteReader)) : + ExecuteReader(behavior, nameof(ExecuteReader)); } } @@ -2574,7 +2570,7 @@ private SqlDataReader EndExecuteReaderInternal(IAsyncResult asyncResult) try { statistics = SqlStatistics.StartTimer(Statistics); - SqlDataReader result = InternalEndExecuteReader(asyncResult, ADP.EndExecuteReader, isInternal: false); + SqlDataReader result = InternalEndExecuteReader(asyncResult, nameof(EndExecuteReader), isInternal: false); success = true; return result; } @@ -2643,7 +2639,7 @@ private IAsyncResult BeginExecuteReaderInternal(CommandBehavior behavior, AsyncC try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool. - RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, ADP.BeginExecuteReader, localCompletion, timeout, out writeTask, out usedCache, asyncWrite, inRetry); + RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, nameof(BeginExecuteReader), localCompletion, timeout, out writeTask, out usedCache, asyncWrite, inRetry); } catch (Exception e) { @@ -2669,7 +2665,7 @@ private IAsyncResult BeginExecuteReaderInternal(CommandBehavior behavior, AsyncC // When we use query caching for parameter encryption we need to retry on specific errors. // In these cases finalize the call internally and trigger a retry when needed. - if (!TriggerInternalEndAndRetryIfNecessary(behavior, stateObject, timeout, ADP.EndExecuteReader, usedCache, inRetry, asyncWrite, globalCompletion, localCompletion, InternalEndExecuteReader, BeginExecuteReaderInternal)) + if (!TriggerInternalEndAndRetryIfNecessary(behavior, stateObject, timeout, nameof(EndExecuteReader), usedCache, inRetry, asyncWrite, globalCompletion, localCompletion, InternalEndExecuteReader, BeginExecuteReaderInternal)) { globalCompletion = localCompletion; } @@ -2837,7 +2833,7 @@ private void BeginExecuteReaderInternalReadStage(TaskCompletionSource co #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection); // must finish caching information before ReadSni which can activate the callback before returning - cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteReader, _activeConnection); + cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteReader), _activeConnection); _stateObj.ReadSni(completion); } #if DEBUG @@ -3432,7 +3428,7 @@ internal void DeriveParameters() } // validate that we have a valid connection - ValidateCommand(ADP.DeriveParameters, false /*not async*/); + ValidateCommand(nameof(DeriveParameters), false /*not async*/); // Use common parser for SqlClient and OleDb - parse into 4 parts - Server, Catalog, Schema, ProcedureName string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(CommandText, "[\"", "]\"", Strings.SQL_SqlCommandCommandText, false); @@ -3569,8 +3565,7 @@ internal void DeriveParameters() else { p.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short)r[colNames[(int)ProcParamsColIndex.DataType]], - ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ? - ADP.StrEmpty : + ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ? "" : (string)r[colNames[(int)ProcParamsColIndex.TypeName]]); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 919f8f2c4d..b651022ded 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -2505,7 +2505,7 @@ private void CheckSQLDebugOnConnect() string mapFileName; // If Win2k or later, prepend "Global\\" to enable this to work through TerminalServices. - if (ADP.IsPlatformNT5) + if (ADP.s_isPlatformNT5) { mapFileName = "Global\\" + TdsEnums.SDCI_MAPFILENAME; } @@ -2518,10 +2518,10 @@ private void CheckSQLDebugOnConnect() hFileMap = NativeMethods.OpenFileMappingA(0x4/*FILE_MAP_READ*/, false, mapFileName); - if (ADP.PtrZero != hFileMap) + if (ADP.s_ptrZero != hFileMap) { IntPtr pMemMap = NativeMethods.MapViewOfFile(hFileMap, 0x4/*FILE_MAP_READ*/, 0, 0, IntPtr.Zero); - if (ADP.PtrZero != pMemMap) + if (ADP.s_ptrZero != pMemMap) { SqlDebugContext sdc = new SqlDebugContext(); sdc.hMemMap = hFileMap; @@ -2812,7 +2812,7 @@ internal void RegisterForConnectionCloseNotification(ref Task outerTask, o // updates our context with any changes made to the memory-mapped data by an external process static private void RefreshMemoryMappedData(SqlDebugContext sdc) { - Debug.Assert(ADP.PtrZero != sdc.pMemMap, "SQL Debug: invalid null value for pMemMap!"); + Debug.Assert(ADP.s_ptrZero != sdc.pMemMap, "SQL Debug: invalid null value for pMemMap!"); // copy memory mapped file contents into managed types MEMMAP memMap = (MEMMAP)Marshal.PtrToStructure(sdc.pMemMap, typeof(MEMMAP)); sdc.dbgpid = memMap.dbgpid; @@ -3178,7 +3178,7 @@ bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(Unmanag string mapFileName; // If Win2k or later, prepend "Global\\" to enable this to work through TerminalServices. - if (ADP.IsPlatformNT5) + if (ADP.s_isPlatformNT5) { mapFileName = "Global\\" + TdsEnums.SDCI_MAPFILENAME; } @@ -3199,7 +3199,7 @@ bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(Unmanag Marshal.WriteIntPtr(pSecurityAttributes, 4, pSecurityDescriptor); // lpSecurityDescriptor = pSecurityDescriptor Marshal.WriteInt32(pSecurityAttributes, 8, 0); // bInheritHandle = FALSE hFileMap = NativeMethods.CreateFileMappingA( - ADP.InvalidPtr/*INVALID_HANDLE_VALUE*/, + ADP.s_invalidPtr/*INVALID_HANDLE_VALUE*/, pSecurityAttributes, 0x4/*PAGE_READWRITE*/, 0, @@ -3290,8 +3290,8 @@ sealed class SqlDebugContext : IDisposable internal uint tid = 0; internal bool active = false; // memory-mapped data - internal IntPtr pMemMap = ADP.PtrZero; - internal IntPtr hMemMap = ADP.PtrZero; + internal IntPtr pMemMap = ADP.s_ptrZero; + internal IntPtr hMemMap = ADP.s_ptrZero; internal uint dbgpid = 0; internal bool fOption = false; internal string machineName = null; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs index ace3935643..eb41758480 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs @@ -128,7 +128,7 @@ private void ConnectionString_Set(DbConnectionPoolKey key) } if (!flag) { - throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State); + throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State); } if (SqlClientEventSource.Log.IsTraceEnabled()) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs index d62177ec09..52131cb1c0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs @@ -294,7 +294,7 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G _connectionReset = ConvertValueToBoolean(KEY.Connection_Reset, DEFAULT.Connection_Reset); _contextConnection = ConvertValueToBoolean(KEY.Context_Connection, DEFAULT.Context_Connection); _encrypt = ConvertValueToEncrypt(); - _enlist = ConvertValueToBoolean(KEY.Enlist, ADP.IsWindowsNT); + _enlist = ConvertValueToBoolean(KEY.Enlist, ADP.s_isWindowsNT); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 0c2200321e..4063f78fd7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -1932,7 +1932,7 @@ private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int buffe if (dataIndex < _columnDataBytesRead) { - throw ADP.NonSeqByteAccess(dataIndex, _columnDataBytesRead, ADP.GetBytes); + throw ADP.NonSeqByteAccess(dataIndex, _columnDataBytesRead, nameof(GetBytes)); } // if the dataIndex is not equal to bytes read, then we have to skip bytes @@ -2419,7 +2419,7 @@ override public long GetChars(int i, long dataIndex, char[] buffer, int bufferIn if ((_sharedState._nextColumnDataToRead == (i + 1)) && (_sharedState._nextColumnHeaderToRead == (i + 1)) && (_columnDataChars != null) && (IsCommandBehavior(CommandBehavior.SequentialAccess)) && (dataIndex < _columnDataCharsRead)) { // Don't allow re-read of same chars in sequential access mode - throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, ADP.GetChars); + throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, nameof(GetChars)); } if (_columnDataCharsIndex != i) @@ -2538,7 +2538,7 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe if (dataIndex < _columnDataCharsRead) { // Don't allow re-read of same chars in sequential access mode - throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, ADP.GetChars); + throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, nameof(GetChars)); } // If we start reading the new column, either dataIndex is 0 or diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnums.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnums.cs index 288eead39f..222c25611b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnums.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnums.cs @@ -912,7 +912,7 @@ internal static String GetStringFromXml(XmlReader xmlreader) // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user! private static readonly MetaType MetaSmallVarBinary = new MetaType - (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); + (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, "", typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialStream.cs index 7c9c745c48..e2d0876d7f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialStream.cs @@ -320,15 +320,15 @@ internal static void ValidateReadParameters(byte[] buffer, int offset, int count { if (buffer == null) { - throw ADP.ArgumentNull(ADP.ParameterBuffer); + throw ADP.ArgumentNull(nameof(buffer)); } if (offset < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterOffset); + throw ADP.ArgumentOutOfRange(nameof(offset)); } if (count < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterCount); + throw ADP.ArgumentOutOfRange(nameof(count)); } try { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialTextReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialTextReader.cs index 861bea5dd0..b1b4a4fed2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialTextReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSequentialTextReader.cs @@ -461,15 +461,15 @@ internal static void ValidateReadParameters(char[] buffer, int index, int count) { if (buffer == null) { - throw ADP.ArgumentNull(ADP.ParameterBuffer); + throw ADP.ArgumentNull(nameof(buffer)); } if (index < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterIndex); + throw ADP.ArgumentOutOfRange(nameof(index)); } if (count < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterCount); + throw ADP.ArgumentOutOfRange(nameof(count)); } try { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlStream.cs index 3cac637cf6..4e0f723361 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlStream.cs @@ -111,19 +111,19 @@ override public int Read(byte[] buffer, int offset, int count) if ((null == _reader)) { - throw ADP.StreamClosed(ADP.Read); + throw ADP.StreamClosed(nameof(Read)); } if (null == buffer) { - throw ADP.ArgumentNull(ADP.ParameterBuffer); + throw ADP.ArgumentNull(nameof(buffer)); } if ((offset < 0) || (count < 0)) { - throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? ADP.ParameterOffset : ADP.ParameterCount)); + throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0 ? nameof(offset) : nameof(count))); } if (buffer.Length - offset < count) { - throw ADP.ArgumentOutOfRange(ADP.ParameterCount); + throw ADP.ArgumentOutOfRange(nameof(count)); } // Need to find out if we should add byte order mark or not. @@ -412,22 +412,22 @@ override public int Read(byte[] buffer, int offset, int count) if (null == _cachedBytes) { - throw ADP.StreamClosed(ADP.Read); + throw ADP.StreamClosed(nameof(Read)); } if (null == buffer) { - throw ADP.ArgumentNull(ADP.ParameterBuffer); + throw ADP.ArgumentNull(nameof(buffer)); } if ((offset < 0) || (count < 0)) { - throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? ADP.ParameterOffset : ADP.ParameterCount)); + throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0 ? nameof(offset) : nameof(count))); } if (buffer.Length - offset < count) { - throw ADP.ArgumentOutOfRange(ADP.ParameterCount); + throw ADP.ArgumentOutOfRange(nameof(count)); } if (_cachedBytes.Count <= _currentArrayIndex) @@ -469,27 +469,27 @@ override public long Seek(long offset, SeekOrigin origin) if (null == _cachedBytes) { - throw ADP.StreamClosed(ADP.Read); + throw ADP.StreamClosed(nameof(Read)); } switch (origin) { case SeekOrigin.Begin: - SetInternalPosition(offset, ADP.ParameterOffset); + SetInternalPosition(offset, nameof(offset)); break; case SeekOrigin.Current: pos = offset + Position; - SetInternalPosition(pos, ADP.ParameterOffset); + SetInternalPosition(pos, nameof(offset)); break; case SeekOrigin.End: pos = TotalLength + offset; - SetInternalPosition(pos, ADP.ParameterOffset); + SetInternalPosition(pos, nameof(offset)); break; default: - throw ADP.InvalidSeekOrigin(ADP.ParameterOffset); + throw ADP.InvalidSeekOrigin(nameof(offset)); } return pos; } @@ -598,7 +598,7 @@ public long GetChars(long dataIndex, char[] buffer, int bufferIndex, int length) int cnt = 0; if (dataIndex < _charsRemoved) { - throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, ADP.GetChars); + throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, nameof(GetChars)); } else if (dataIndex > _charsRemoved) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 8b513008de..0513060494 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -6403,11 +6403,11 @@ private bool TryReadSqlStringValue(SqlBuffer value, byte type, int length, Encod } if (length > 0) { - s = new String(cc, 0, length); + s = new string(cc, 0, length); } else { - s = ADP.StrEmpty; + s = ""; } } else @@ -8241,7 +8241,7 @@ internal int GetEncodingCharLength(string value, int numChars, int charOffset, E { // UNDONE: (PERF) this is an expensive way to get the length. Also, aren't we // UNDONE: (PERF) going through these steps twice when we write out a value? - if (value == null || value == ADP.StrEmpty) + if (string.IsNullOrEmpty(value)) { return 0; } @@ -10337,13 +10337,13 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo if (_isYukon && (mt.SqlDbType == SqlDbType.Xml)) { - if (((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != ADP.StrEmpty)) || - ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != ADP.StrEmpty)) || - ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != ADP.StrEmpty))) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionDatabase) || + !string.IsNullOrEmpty(param.XmlSchemaCollectionOwningSchema) || + !string.IsNullOrEmpty(param.XmlSchemaCollectionName)) { stateObj.WriteByte(1); //Schema present flag - if ((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != ADP.StrEmpty)) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionDatabase)) { tempLen = (param.XmlSchemaCollectionDatabase).Length; stateObj.WriteByte((byte)(tempLen)); @@ -10354,7 +10354,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.WriteByte(0); // No dbname } - if ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != ADP.StrEmpty)) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionOwningSchema)) { tempLen = (param.XmlSchemaCollectionOwningSchema).Length; stateObj.WriteByte((byte)(tempLen)); @@ -10364,7 +10364,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo { stateObj.WriteByte(0); // no xml schema name } - if ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != ADP.StrEmpty)) + if (!string.IsNullOrEmpty(param.XmlSchemaCollectionName)) { tempLen = (param.XmlSchemaCollectionName).Length; WriteShort((short)(tempLen), stateObj); @@ -12365,15 +12365,15 @@ internal static void ValidateWriteParameters(byte[] buffer, int offset, int coun { if (buffer == null) { - throw ADP.ArgumentNull(ADP.ParameterBuffer); + throw ADP.ArgumentNull(nameof(buffer)); } if (offset < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterOffset); + throw ADP.ArgumentOutOfRange(nameof(offset)); } if (count < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterCount); + throw ADP.ArgumentOutOfRange(nameof(count)); } try { @@ -12493,15 +12493,15 @@ internal static void ValidateWriteParameters(char[] buffer, int offset, int coun { if (buffer == null) { - throw ADP.ArgumentNull(ADP.ParameterBuffer); + throw ADP.ArgumentNull(nameof(buffer)); } if (offset < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterOffset); + throw ADP.ArgumentOutOfRange(nameof(offset)); } if (count < 0) { - throw ADP.ArgumentOutOfRange(ADP.ParameterCount); + throw ADP.ArgumentOutOfRange(nameof(count)); } try { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 1d96d61281..43fc15b6d9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -2269,7 +2269,7 @@ internal void ReadSniSyncOverAsync() if (TdsEnums.SNI_SUCCESS == error) { // Success - process results! - Debug.Assert(ADP.PtrZero != readPacket, "ReadNetworkPacket cannot be null in synchronous operation!"); + Debug.Assert(ADP.s_ptrZero != readPacket, "ReadNetworkPacket cannot be null in synchronous operation!"); ProcessSniPacket(readPacket, 0); #if DEBUG if (_forcePendingReadsToWaitForUser) @@ -2589,8 +2589,8 @@ internal void ReadSni(TaskCompletionSource completion) if (TdsEnums.SNI_SUCCESS == error) { // Success - process results! - Debug.Assert(ADP.PtrZero != readPacket, "ReadNetworkPacket should not have been null on this async operation!"); - ReadAsyncCallback(ADP.PtrZero, readPacket, 0); + Debug.Assert(ADP.s_ptrZero != readPacket, "ReadNetworkPacket should not have been null on this async operation!"); + ReadAsyncCallback(ADP.s_ptrZero, readPacket, 0); } else if (TdsEnums.SNI_SUCCESS_IO_PENDING != error) { // FAILURE! diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index c0d4b9c6f7..f1f929da7b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -394,7 +394,7 @@ private int GetServerTransactionLevel() // UNDONE: use a singleton select here // UNDONE: execute without SqlClientPermission.Demand() - transactionLevelCommand.RunExecuteReader(0, RunBehavior.UntilDone, false /* returnDataStream */, ADP.GetServerTransactionLevel); + transactionLevelCommand.RunExecuteReader(0, RunBehavior.UntilDone, false /* returnDataStream */, nameof(GetServerTransactionLevel)); return (int)parameter.Value; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs new file mode 100644 index 0000000000..f7e3715ccc --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs @@ -0,0 +1,1526 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections; +using System.Data; +using System.Data.Common; +using System.Data.SqlTypes; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Transactions; +using Microsoft.Data.SqlClient; +using Microsoft.Data.SqlClient.Server; +using Microsoft.Win32; +using IsolationLevel = System.Data.IsolationLevel; + +namespace Microsoft.Data.Common +{ + /// + /// The class ADP defines the exceptions that are specific to the Adapters. + /// The class contains functions that take the proper informational variables and then construct + /// the appropriate exception with an error string obtained from the resource framework. + /// The exception is then returned to the caller, so that the caller may then throw from its + /// location so that the catcher of the exception will have the appropriate call stack. + /// This class is used so that there will be compile time checking of error messages. + /// The resource Framework.txt will ensure proper string text based on the appropriate locale. + /// + internal static class ADP + { + // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx) + // Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features + private static Task s_trueTask; + internal static Task TrueTask => s_trueTask ??= Task.FromResult(true); + + private static Task s_falseTask; + internal static Task FalseTask => s_falseTask ??= Task.FromResult(false); + + internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; + internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; + /// + /// Infinite connection timeout identifier in seconds + /// + internal const int InfiniteConnectionTimeout = 0; + /// + /// Max duration for buffer in seconds + /// + internal const int MaxBufferAccessTokenExpiry = 600; + + static private void TraceException(string trace, Exception e) + { + Debug.Assert(null != e, "TraceException: null Exception"); + if (e is not null) + { + SqlClientEventSource.Log.TryTraceEvent(trace, e); + } + } + + internal static void TraceExceptionAsReturnValue(Exception e) + { + TraceException(" '{0}'", e); + } + + internal static void TraceExceptionWithoutRethrow(Exception e) + { + Debug.Assert(IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); + TraceException(" '{0}'", e); + } + + internal static bool IsEmptyArray(string[] array) => (array is null) || (array.Length == 0); + + internal static bool IsNull(object value) + { + if ((value is null) || (DBNull.Value == value)) + { + return true; + } + INullable nullable = (value as INullable); + return ((nullable is not null) && nullable.IsNull); + } + + internal static Exception ExceptionWithStackTrace(Exception e) + { + try + { + throw e; + } + catch (Exception caught) + { + return caught; + } + } + + #region COM+ exceptions + internal static ArgumentException Argument(string error) + { + ArgumentException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentException Argument(string error, Exception inner) + { + ArgumentException e = new(error, inner); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentException Argument(string error, string parameter) + { + ArgumentException e = new(error, parameter); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentNullException ArgumentNull(string parameter) + { + ArgumentNullException e = new(parameter); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentNullException ArgumentNull(string parameter, string error) + { + ArgumentNullException e = new(parameter, error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) + { + ArgumentOutOfRangeException e = new(parameterName); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) + { + ArgumentOutOfRangeException e = new(parameterName, message); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static IndexOutOfRangeException IndexOutOfRange(string error) + { + IndexOutOfRangeException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static IndexOutOfRangeException IndexOutOfRange(int value) + { + IndexOutOfRangeException e = new(value.ToString(CultureInfo.InvariantCulture)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static IndexOutOfRangeException IndexOutOfRange() + { + IndexOutOfRangeException e = new(); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static InvalidOperationException InvalidOperation(string error, Exception inner) + { + InvalidOperationException e = new(error, inner); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static OverflowException Overflow(string error) => Overflow(error, null); + + internal static OverflowException Overflow(string error, Exception inner) + { + OverflowException e = new(error, inner); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static TimeoutException TimeoutException(string error) + { + TimeoutException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static TypeLoadException TypeLoad(string error) + { + TypeLoadException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static InvalidCastException InvalidCast() + { + InvalidCastException e = new(); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static InvalidCastException InvalidCast(string error) + { + return InvalidCast(error, null); + } + + internal static InvalidCastException InvalidCast(string error, Exception inner) + { + InvalidCastException e = new(error, inner); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static InvalidOperationException InvalidOperation(string error) + { + InvalidOperationException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static IOException IO(string error) + { + IOException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + internal static IOException IO(string error, Exception inner) + { + IOException e = new(error, inner); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static NotSupportedException NotSupported() + { + NotSupportedException e = new(); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static NotSupportedException NotSupported(string error) + { + NotSupportedException e = new(error); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static InvalidOperationException DataAdapter(string error) => InvalidOperation(error); + + private static InvalidOperationException Provider(string error) => InvalidOperation(error); + + internal static ArgumentException InvalidMultipartName(string property, string value) + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_InvalidMultipartName, StringsHelper.GetString(property), value)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_InvalidMultipartNameQuoteUsage, StringsHelper.GetString(property), value)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_InvalidMultipartNameToManyParts, StringsHelper.GetString(property), value, limit)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ObjectDisposedException ObjectDisposed(object instance) + { + ObjectDisposedException e = new(instance.GetType().Name); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static InvalidOperationException MethodCalledTwice(string method) + { + InvalidOperationException e = new(StringsHelper.GetString(Strings.ADP_CalledTwice, method)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) + { + ArgumentOutOfRangeException e = new(parameterName, value, message); + TraceExceptionAsReturnValue(e); + return e; + } + #endregion + + #region Helper Functions + internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) + => ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name); + + internal static void CheckArgumentNull(object value, string parameterName) + { + if (value is null) + { + throw ArgumentNull(parameterName); + } + } + + internal static bool IsCatchableExceptionType(Exception e) + { + // only StackOverflowException & ThreadAbortException are sealed classes + // a 'catchable' exception is defined by what it is not. + Debug.Assert(e != null, "Unexpected null exception!"); + Type type = e.GetType(); + + return ((type != typeof(StackOverflowException)) && + (type != typeof(OutOfMemoryException)) && + (type != typeof(ThreadAbortException)) && + (type != typeof(NullReferenceException)) && + (type != typeof(AccessViolationException)) && + !typeof(SecurityException).IsAssignableFrom(type)); + } + + internal static bool IsCatchableOrSecurityExceptionType(Exception e) + { + // a 'catchable' exception is defined by what it is not. + // since IsCatchableExceptionType defined SecurityException as not 'catchable' + // this method will return true for SecurityException has being catchable. + + // the other way to write this method is, but then SecurityException is checked twice + // return ((e is SecurityException) || IsCatchableExceptionType(e)); + + // only StackOverflowException & ThreadAbortException are sealed classes + Debug.Assert(e != null, "Unexpected null exception!"); + Type type = e.GetType(); + + return ((type != typeof(StackOverflowException)) && + (type != typeof(OutOfMemoryException)) && + (type != typeof(ThreadAbortException)) && + (type != typeof(NullReferenceException)) && + (type != typeof(AccessViolationException))); + } + + // Invalid Enumeration + internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) + => ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name); + + internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) + { + Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString()); + + return InvalidEnumerationValue(typeof(CommandBehavior), (int)value); + } + + internal static void ValidateCommandBehavior(CommandBehavior value) + { + if (((int)value < 0) || (0x3F < (int)value)) + { + throw InvalidCommandBehavior(value); + } + } + + internal static ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Format value) + { +#if DEBUG + switch (value) + { + case Format.Unknown: + case Format.Native: + case Format.UserDefined: + Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(Format), (int)value); + } + + internal static ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Format value, string method) + => NotSupportedEnumerationValue(typeof(Format), value.ToString(), method); + + internal static ArgumentException InvalidArgumentLength(string argumentName, int limit) + => Argument(StringsHelper.GetString(Strings.ADP_InvalidArgumentLength, argumentName, limit)); + + internal static ArgumentException MustBeReadOnly(string argumentName) => Argument(StringsHelper.GetString(Strings.ADP_MustBeReadOnly, argumentName)); + #endregion + + #region CommandBuilder, Command, BulkCopy + /// + /// This allows the caller to determine if it is an error or not for the quotedString to not be quoted + /// + /// The return value is true if the string was quoted and false if it was not + internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) + { + int prefixLength = quotePrefix is null ? 0 : quotePrefix.Length; + int suffixLength = quoteSuffix is null ? 0 : quoteSuffix.Length; + + if ((suffixLength + prefixLength) == 0) + { + unquotedString = quotedString; + return true; + } + + if (quotedString is null) + { + unquotedString = quotedString; + return false; + } + + int quotedStringLength = quotedString.Length; + + // is the source string too short to be quoted + if (quotedStringLength < prefixLength + suffixLength) + { + unquotedString = quotedString; + return false; + } + + // is the prefix present? + if (prefixLength > 0) + { + if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal)) + { + unquotedString = quotedString; + return false; + } + } + + // is the suffix present? + if (suffixLength > 0) + { + if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal)) + { + unquotedString = quotedString; + return false; + } + unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)) + .Replace(quoteSuffix + quoteSuffix, quoteSuffix); + } + else + { + unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength); + } + return true; + } + + internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) + { + var resultString = new StringBuilder(unQuotedString.Length + quoteSuffix.Length + quoteSuffix.Length); + AppendQuotedString(resultString, quotePrefix, quoteSuffix, unQuotedString); + return resultString.ToString(); + } + + internal static string AppendQuotedString(StringBuilder buffer, string quotePrefix, string quoteSuffix, string unQuotedString) + { + Debug.Assert(buffer is not null, "buffer parameter must be initialized!"); + + if (!string.IsNullOrEmpty(quotePrefix)) + { + buffer.Append(quotePrefix); + } + + // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar". + if (!string.IsNullOrEmpty(quoteSuffix)) + { + int start = buffer.Length; + buffer.Append(unQuotedString); + buffer.Replace(quoteSuffix, quoteSuffix + quoteSuffix, start, unQuotedString.Length); + buffer.Append(quoteSuffix); + } + else + { + buffer.Append(unQuotedString); + } + + return buffer.ToString(); + } + + internal static string BuildMultiPartName(string[] strings) + { + StringBuilder bld = new(); + // Assume we want to build a full multi-part name with all parts except trimming separators for + // leading empty names (null or empty strings, but not whitespace). Separators in the middle + // should be added, even if the name part is null/empty, to maintain proper location of the parts. + for (int i = 0; i < strings.Length; i++) + { + if (0 < bld.Length) + { + bld.Append('.'); + } + if (strings[i] is not null && 0 != strings[i].Length) + { + bld.Append(BuildQuotedString("[", "]", strings[i])); + } + } + return bld.ToString(); + } + + // global constant strings + internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_"; + internal const string Command = "Command"; + internal const string Connection = "Connection"; + internal const string Parameter = "Parameter"; + internal const string ParameterName = "ParameterName"; + internal const string ParameterSetPosition = "set_Position"; + + internal const int DefaultCommandTimeout = 30; + internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections + + internal const int CharSize = UnicodeEncoding.CharSize; + + internal static Delegate FindBuilder(MulticastDelegate mcd) + { + foreach (Delegate del in mcd?.GetInvocationList()) + { + if (del.Target is DbCommandBuilder) + return del; + } + + return null; + } + + internal static long TimerCurrent() => DateTime.UtcNow.ToFileTimeUtc(); + + internal static long TimerFromSeconds(int seconds) + { + long result = checked((long)seconds * TimeSpan.TicksPerSecond); + return result; + } + + internal static long TimerFromMilliseconds(long milliseconds) + { + long result = checked(milliseconds * TimeSpan.TicksPerMillisecond); + return result; + } + + internal static bool TimerHasExpired(long timerExpire) + { + bool result = TimerCurrent() > timerExpire; + return result; + } + + internal static long TimerRemaining(long timerExpire) + { + long timerNow = TimerCurrent(); + long result = checked(timerExpire - timerNow); + return result; + } + + internal static long TimerRemainingMilliseconds(long timerExpire) + { + long result = TimerToMilliseconds(TimerRemaining(timerExpire)); + return result; + } + + internal static long TimerRemainingSeconds(long timerExpire) + { + long result = TimerToSeconds(TimerRemaining(timerExpire)); + return result; + } + + internal static long TimerToMilliseconds(long timerValue) + { + long result = timerValue / TimeSpan.TicksPerMillisecond; + return result; + } + + private static long TimerToSeconds(long timerValue) + { + long result = timerValue / TimeSpan.TicksPerSecond; + return result; + } + + /// + /// Note: In Longhorn you'll be able to rename a machine without + /// rebooting. Therefore, don't cache this machine name. + /// + [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")] + internal static string MachineName() => Environment.MachineName; + + internal static Transaction GetCurrentTransaction() + { + Transaction transaction = Transaction.Current; + return transaction; + } + + internal static bool IsDirection(DbParameter value, ParameterDirection condition) + { +#if DEBUG + switch (condition) + { // @perfnote: Enum.IsDefined + case ParameterDirection.Input: + case ParameterDirection.Output: + case ParameterDirection.InputOutput: + case ParameterDirection.ReturnValue: + break; + default: + throw ADP.InvalidParameterDirection(condition); + } +#endif + return (condition == (condition & value.Direction)); + } + + internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) + { + if ((value is null) || (value == DBNull.Value)) + { + isNull = true; + isSqlType = false; + } + else + { + if (value is INullable nullable) + { + isNull = nullable.IsNull; + // Duplicated from DataStorage.cs + // For back-compat, SqlXml is not in this list + isSqlType = ((value is SqlBinary) || + (value is SqlBoolean) || + (value is SqlByte) || + (value is SqlBytes) || + (value is SqlChars) || + (value is SqlDateTime) || + (value is SqlDecimal) || + (value is SqlDouble) || + (value is SqlGuid) || + (value is SqlInt16) || + (value is SqlInt32) || + (value is SqlInt64) || + (value is SqlMoney) || + (value is SqlSingle) || + (value is SqlString)); + } + else + { + isNull = false; + isSqlType = false; + } + } + } + + private static Version s_systemDataVersion; + + internal static Version GetAssemblyVersion() + { + // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time + if (s_systemDataVersion is null) + { + s_systemDataVersion = new Version(ThisAssembly.InformationalVersion); + } + + return s_systemDataVersion; + } + + + internal static readonly string[] s_azureSqlServerEndpoints = { StringsHelper.GetString(Strings.AZURESQL_GenericEndpoint), + StringsHelper.GetString(Strings.AZURESQL_GermanEndpoint), + StringsHelper.GetString(Strings.AZURESQL_UsGovEndpoint), + StringsHelper.GetString(Strings.AZURESQL_ChinaEndpoint)}; + + // This method assumes dataSource parameter is in TCP connection string format. + internal static bool IsAzureSqlServerEndpoint(string dataSource) + { + int length = dataSource.Length; + // remove server port + int foundIndex = dataSource.LastIndexOf(','); + if (foundIndex >= 0) + { + length = foundIndex; + } + + // check for the instance name + foundIndex = dataSource.LastIndexOf('\\', length - 1, length - 1); + if (foundIndex > 0) + { + length = foundIndex; + } + + // trim trailing whitespace + while (length > 0 && char.IsWhiteSpace(dataSource[length - 1])) + { + length -= 1; + } + + // check if servername end with any azure endpoints + for (int index = 0; index < s_azureSqlServerEndpoints.Length; index++) + { + string endpoint = s_azureSqlServerEndpoints[index]; + if (length > endpoint.Length) + { + if (string.Compare(dataSource, length - endpoint.Length, endpoint, 0, endpoint.Length, StringComparison.OrdinalIgnoreCase) == 0) + { + return true; + } + } + } + + return false; + } + + internal static ArgumentException SingleValuedProperty(string propertyName, string value) + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_SingleValuedProperty, propertyName, value)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_DoubleValuedProperty, propertyName, value1, value2)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static ArgumentException InvalidPrefixSuffix() + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_InvalidPrefixSuffix)); + TraceExceptionAsReturnValue(e); + return e; + } + #endregion + + #region DbConnectionOptions, DataAccess + internal static ArgumentException ConnectionStringSyntax(int index) => Argument(StringsHelper.GetString(Strings.ADP_ConnectionStringSyntax, index)); + + internal static ArgumentException KeywordNotSupported(string keyword) => Argument(StringsHelper.GetString(Strings.ADP_KeywordNotSupported, keyword)); + + internal static Exception InvalidConnectionOptionValue(string key) => InvalidConnectionOptionValue(key, null); + + internal static Exception InvalidConnectionOptionValue(string key, Exception inner) + => Argument(StringsHelper.GetString(Strings.ADP_InvalidConnectionOptionValue, key), inner); + + internal static Exception InvalidConnectionOptionValueLength(string key, int limit) + => Argument(StringsHelper.GetString(Strings.ADP_InvalidConnectionOptionValueLength, key, limit)); + + internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) + => Argument(StringsHelper.GetString(Strings.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); + + internal static InvalidOperationException InvalidDataDirectory() => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidDataDirectory)); + + internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) + => Argument(StringsHelper.GetString(Strings.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); // MDAC 68201 + + internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) + => ArgumentNull(parameter, StringsHelper.GetString(Strings.ADP_CollectionNullValue, collection.Name, itemType.Name)); + + internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) + => IndexOutOfRange(StringsHelper.GetString(Strings.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); + + internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) + => IndexOutOfRange(StringsHelper.GetString(Strings.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); + + internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) + => InvalidCast(StringsHelper.GetString(Strings.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); + + internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) + => ADP.Argument(StringsHelper.GetString(Strings.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); + + internal static ArgumentException InvalidMinMaxPoolSizeValues() + => ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMinMaxPoolSizeValues)); + #endregion + + #region DbConnection + private static string ConnectionStateMsg(ConnectionState state) + { // MDAC 82165, if the ConnectionState enum to msg the localization looks weird + return state switch + { + (ConnectionState.Closed) or (ConnectionState.Connecting | ConnectionState.Broken) => StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_Closed), + (ConnectionState.Connecting) => StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_Connecting), + (ConnectionState.Open) => StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_Open), + (ConnectionState.Open | ConnectionState.Executing) => StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_OpenExecuting), + (ConnectionState.Open | ConnectionState.Fetching) => StringsHelper.GetString(Strings.ADP_ConnectionStateMsg_OpenFetching), + _ => StringsHelper.GetString(Strings.ADP_ConnectionStateMsg, state.ToString()), + }; + } + + internal static InvalidOperationException NoConnectionString() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_NoConnectionString)); + + internal static NotImplementedException MethodNotImplemented([CallerMemberName] string methodName = "") + { + NotImplementedException e = new(methodName); + TraceExceptionAsReturnValue(e); + return e; + } + #endregion + + #region Stream + internal static Exception StreamClosed([CallerMemberName] string method = "") => InvalidOperation(StringsHelper.GetString(Strings.ADP_StreamClosed, method)); + + static internal Exception InvalidSeekOrigin(string parameterName) => ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidSeekOrigin), parameterName); + + internal static IOException ErrorReadingFromStream(Exception internalException) => IO(StringsHelper.GetString(Strings.SqlMisc_StreamErrorMessage), internalException); + #endregion + + #region Generic Data Provider Collection + internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) + => Argument(StringsHelper.GetString(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); + + internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection) + => Argument(StringsHelper.GetString(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); + #endregion + + #region ConnectionUtil + internal enum InternalErrorCode + { + UnpooledObjectHasOwner = 0, + UnpooledObjectHasWrongOwner = 1, + PushingObjectSecondTime = 2, + PooledObjectHasOwner = 3, + PooledObjectInPoolMoreThanOnce = 4, + CreateObjectReturnedNull = 5, + NewObjectCannotBePooled = 6, + NonPooledObjectUsedMoreThanOnce = 7, + AttemptingToPoolOnRestrictedToken = 8, + // ConnectionOptionsInUse = 9, + ConvertSidToStringSidWReturnedNull = 10, + // UnexpectedTransactedObject = 11, + AttemptingToConstructReferenceCollectionOnStaticObject = 12, + AttemptingToEnlistTwice = 13, + CreateReferenceCollectionReturnedNull = 14, + PooledObjectWithoutPool = 15, + UnexpectedWaitAnyResult = 16, + SynchronousConnectReturnedPending = 17, + CompletedConnectReturnedPending = 18, + + NameValuePairNext = 20, + InvalidParserState1 = 21, + InvalidParserState2 = 22, + InvalidParserState3 = 23, + + InvalidBuffer = 30, + + UnimplementedSMIMethod = 40, + InvalidSmiCall = 41, + + SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50, + SqlDependencyProcessDispatcherFailureCreateInstance = 51, + SqlDependencyProcessDispatcherFailureAppDomain = 52, + SqlDependencyCommandHashIsNotAssociatedWithNotification = 53, + + UnknownTransactionFailure = 60, + } + + internal static Exception InternalError(InternalErrorCode internalError) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InternalProviderError, (int)internalError)); + + internal static Exception ClosedConnectionError() => InvalidOperation(StringsHelper.GetString(Strings.ADP_ClosedConnectionError)); + internal static Exception ConnectionAlreadyOpen(ConnectionState state) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); + + internal static Exception TransactionPresent() => InvalidOperation(StringsHelper.GetString(Strings.ADP_TransactionPresent)); + + internal static Exception LocalTransactionPresent() => InvalidOperation(StringsHelper.GetString(Strings.ADP_LocalTransactionPresent)); + + internal static Exception OpenConnectionPropertySet(string property, ConnectionState state) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); + + internal static Exception EmptyDatabaseName() => Argument(StringsHelper.GetString(Strings.ADP_EmptyDatabaseName)); + + internal enum ConnectionError + { + BeginGetConnectionReturnsNull, + GetConnectionReturnsNull, + ConnectionOptionsMissing, + CouldNotSwitchToClosedPreviouslyOpenedState, + } + + internal static Exception InternalConnectionError(ConnectionError internalError) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InternalConnectionError, (int)internalError)); + + internal static Exception InvalidConnectRetryCountValue() => Argument(StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryCountValue)); + + internal static Exception InvalidConnectRetryIntervalValue() => Argument(StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryIntervalValue)); + #endregion + + #region DbDataReader + internal static Exception DataReaderClosed([CallerMemberName] string method = "") + => InvalidOperation(StringsHelper.GetString(Strings.ADP_DataReaderClosed, method)); + + internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) + => ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidSourceBufferIndex, + maxLen.ToString(CultureInfo.InvariantCulture), + srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); + + internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) + => ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_InvalidDestinationBufferIndex, + maxLen.ToString(CultureInfo.InvariantCulture), + dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); + + internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) + => IndexOutOfRange(StringsHelper.GetString(Strings.SQL_InvalidBufferSizeOrIndex, + numBytes.ToString(CultureInfo.InvariantCulture), + bufferIndex.ToString(CultureInfo.InvariantCulture))); + + internal static Exception InvalidDataLength(long length) + => IndexOutOfRange(StringsHelper.GetString(Strings.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); + + internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) + => 0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase); + + internal static int DstCompare(string strA, string strB) // this is null safe + => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions); + + internal static void SetCurrentTransaction(Transaction transaction) => Transaction.Current = transaction; + + internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_NonSeqByteAccess, + badIndex.ToString(CultureInfo.InvariantCulture), + currIndex.ToString(CultureInfo.InvariantCulture), + method)); + + internal static Exception NegativeParameter(string parameterName) => InvalidOperation(StringsHelper.GetString(Strings.ADP_NegativeParameter, parameterName)); + + internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName) + => Argument(StringsHelper.GetString(Strings.MDF_InvalidXmlMissingColumn, collectionName, columnName)); + + internal static InvalidOperationException AsyncOperationPending() => InvalidOperation(StringsHelper.GetString(Strings.ADP_PendingAsyncOperation)); + #endregion + + #region IDbCommand + // IDbCommand.CommandType + static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) + { +#if DEBUG + switch (value) + { + case CommandType.Text: + case CommandType.StoredProcedure: + case CommandType.TableDirect: + Debug.Assert(false, "valid CommandType " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(CommandType), (int)value); + } + + internal static Exception TooManyRestrictions(string collectionName) + => Argument(StringsHelper.GetString(Strings.MDF_TooManyRestrictions, collectionName)); + + internal static Exception CommandTextRequired(string method) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_CommandTextRequired, method)); + + internal static Exception UninitializedParameterSize(int index, Type dataType) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); + + internal static Exception PrepareParameterType(DbCommand cmd) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterType, cmd.GetType().Name)); + + internal static Exception PrepareParameterSize(DbCommand cmd) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterSize, cmd.GetType().Name)); + + internal static Exception PrepareParameterScale(DbCommand cmd, string type) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_PrepareParameterScale, cmd.GetType().Name, type)); + + internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); + + // IDataParameter.SourceVersion + internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) + { +#if DEBUG + switch (value) + { + case DataRowVersion.Default: + case DataRowVersion.Current: + case DataRowVersion.Original: + case DataRowVersion.Proposed: + Debug.Fail($"Invalid DataRowVersion {value}"); + break; + } +#endif + return InvalidEnumerationValue(typeof(DataRowVersion), (int)value); + } + + internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) + => NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method); + + internal static ArgumentException BadParameterName(string parameterName) + { + ArgumentException e = new(StringsHelper.GetString(Strings.ADP_BadParameterName, parameterName)); + TraceExceptionAsReturnValue(e); + return e; + } + + internal static Exception DeriveParametersNotSupported(IDbCommand value) + => DataAdapter(StringsHelper.GetString(Strings.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); + + internal static Exception NoStoredProcedureExists(string sproc) => InvalidOperation(StringsHelper.GetString(Strings.ADP_NoStoredProcedureExists, sproc)); + #endregion + + #region DbMetaDataFactory + internal static Exception DataTableDoesNotExist(string collectionName) + => Argument(StringsHelper.GetString(Strings.MDF_DataTableDoesNotExist, collectionName)); + + // IDbCommand.UpdateRowSource + internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) + { +#if DEBUG + switch (value) + { + case UpdateRowSource.None: + case UpdateRowSource.OutputParameters: + case UpdateRowSource.FirstReturnedRecord: + case UpdateRowSource.Both: + Debug.Fail("valid UpdateRowSource " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); + } + + internal static Exception QueryFailed(string collectionName, Exception e) + => InvalidOperation(StringsHelper.GetString(Strings.MDF_QueryFailed, collectionName), e); + + internal static Exception NoColumns() => Argument(StringsHelper.GetString(Strings.MDF_NoColumns)); + + internal static InvalidOperationException ConnectionRequired(string method) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_ConnectionRequired, method)); + + internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); + + internal static Exception OpenReaderExists(bool marsOn) => OpenReaderExists(null, marsOn); + + internal static Exception OpenReaderExists(Exception e, bool marsOn) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_OpenReaderExists, marsOn ? ADP.Command : ADP.Connection), e); + + internal static Exception InvalidXml() => Argument(StringsHelper.GetString(Strings.MDF_InvalidXml)); + + internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName) + => Argument(StringsHelper.GetString(Strings.MDF_InvalidXmlInvalidValue, collectionName, columnName)); + + internal static Exception CollectionNameIsNotUnique(string collectionName) + => Argument(StringsHelper.GetString(Strings.MDF_CollectionNameISNotUnique, collectionName)); + + internal static Exception UnableToBuildCollection(string collectionName) + => Argument(StringsHelper.GetString(Strings.MDF_UnableToBuildCollection, collectionName)); + + internal static Exception UndefinedCollection(string collectionName) + => Argument(StringsHelper.GetString(Strings.MDF_UndefinedCollection, collectionName)); + + internal static Exception UnsupportedVersion(string collectionName) => Argument(StringsHelper.GetString(Strings.MDF_UnsupportedVersion, collectionName)); + + internal static Exception AmbiguousCollectionName(string collectionName) + => Argument(StringsHelper.GetString(Strings.MDF_AmbiguousCollectionName, collectionName)); + + internal static Exception MissingDataSourceInformationColumn() => Argument(StringsHelper.GetString(Strings.MDF_MissingDataSourceInformationColumn)); + + internal static Exception IncorrectNumberOfDataSourceInformationRows() + => Argument(StringsHelper.GetString(Strings.MDF_IncorrectNumberOfDataSourceInformationRows)); + + internal static Exception MissingRestrictionColumn() => Argument(StringsHelper.GetString(Strings.MDF_MissingRestrictionColumn)); + + internal static Exception MissingRestrictionRow() => Argument(StringsHelper.GetString(Strings.MDF_MissingRestrictionRow)); + + internal static Exception UndefinedPopulationMechanism(string populationMechanism) +#if NETFRAMEWORK + => Argument(StringsHelper.GetString(Strings.MDF_UndefinedPopulationMechanism, populationMechanism)); +#else + => throw new NotImplementedException(); +#endif + #endregion + + #region DbConnectionPool and related + internal static Exception PooledOpenTimeout() + => ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_PooledOpenTimeout)); + + internal static Exception NonPooledOpenTimeout() + => ADP.TimeoutException(StringsHelper.GetString(Strings.ADP_NonPooledOpenTimeout)); + #endregion + + #region DbProviderException + internal static InvalidOperationException TransactionConnectionMismatch() + => Provider(StringsHelper.GetString(Strings.ADP_TransactionConnectionMismatch)); + + internal static InvalidOperationException TransactionRequired(string method) + => Provider(StringsHelper.GetString(Strings.ADP_TransactionRequired, method)); + + internal static InvalidOperationException TransactionCompletedButNotDisposed() => Provider(StringsHelper.GetString(Strings.ADP_TransactionCompletedButNotDisposed)); + + #endregion + + #region SqlMetaData, SqlTypes + internal static Exception InvalidMetaDataValue() => ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMetaDataValue)); + + internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_NonSequentialColumnAccess, + badCol.ToString(CultureInfo.InvariantCulture), + currCol.ToString(CultureInfo.InvariantCulture))); + #endregion + + #region IDataParameter + internal static ArgumentException InvalidDataType(TypeCode typecode) => Argument(StringsHelper.GetString(Strings.ADP_InvalidDataType, typecode.ToString())); + + internal static ArgumentException UnknownDataType(Type dataType) => Argument(StringsHelper.GetString(Strings.ADP_UnknownDataType, dataType.FullName)); + + internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype) + => Argument(StringsHelper.GetString(Strings.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); + + internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) + => Argument(StringsHelper.GetString(Strings.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); + + internal static ArgumentException InvalidOffsetValue(int value) + => Argument(StringsHelper.GetString(Strings.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); + + internal static ArgumentException InvalidSizeValue(int value) + => Argument(StringsHelper.GetString(Strings.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); + + internal static ArgumentException ParameterValueOutOfRange(decimal value) + => ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); + + internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value) => ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString())); + + internal static ArgumentException ParameterValueOutOfRange(string value) => ADP.Argument(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value)); + + internal static ArgumentException VersionDoesNotSupportDataType(string typeName) => Argument(StringsHelper.GetString(Strings.ADP_VersionDoesNotSupportDataType, typeName)); + + internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) + { + Debug.Assert(null != value, "null value on conversion failure"); + Debug.Assert(null != inner, "null inner on conversion failure"); + + Exception e; + string message = StringsHelper.GetString(Strings.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); + if (inner is ArgumentException) + { + e = new ArgumentException(message, inner); + } + else if (inner is FormatException) + { + e = new FormatException(message, inner); + } + else if (inner is InvalidCastException) + { + e = new InvalidCastException(message, inner); + } + else if (inner is OverflowException) + { + e = new OverflowException(message, inner); + } + else + { + e = inner; + } + TraceExceptionAsReturnValue(e); + return e; + } + #endregion + + #region IDataParameterCollection + internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection) => CollectionIndexInt32(index, collection.GetType(), collection.Count); + + internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType) + => CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType()); + + internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType) + => CollectionNullValue(parameter, collection.GetType(), parameterType); + + internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue) + => CollectionInvalidType(collection.GetType(), parameterType, invalidValue); + #endregion + + #region IDbTransaction + internal static Exception ParallelTransactionsNotSupported(DbConnection obj) + => InvalidOperation(StringsHelper.GetString(Strings.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); + + internal static Exception TransactionZombied(DbTransaction obj) => InvalidOperation(StringsHelper.GetString(Strings.ADP_TransactionZombied, obj.GetType().Name)); + #endregion + + #region DbProviderConfigurationHandler + internal static InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); + + internal static ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() + => Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); + + internal static InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); + + internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() + => Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); + + internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity)); + + static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword)); + + static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndAuthentication() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication)); + + static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() + => InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfCredentialAndAccessToken)); + #endregion + +#if NETFRAMEWORK + #region netfx project only + internal static Task CreatedTaskWithException(Exception ex) + { + TaskCompletionSource completion = new(); + completion.SetException(ex); + return completion.Task; + } + + internal static Task CreatedTaskWithCancellation() + { + TaskCompletionSource completion = new(); + completion.SetCanceled(); + return completion.Task; + } + + internal static void TraceExceptionForCapture(Exception e) + { + Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); + TraceException(" '{0}'", e); + } + + // + // Helper Functions + // + internal static void CheckArgumentLength(string value, string parameterName) + { + CheckArgumentNull(value, parameterName); + if (0 == value.Length) + { + throw Argument(StringsHelper.GetString(Strings.ADP_EmptyString, parameterName)); // MDAC 94859 + } + } + + // IDbConnection.BeginTransaction, OleDbTransaction.Begin + internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) + { +#if DEBUG + switch (value) + { + case IsolationLevel.Unspecified: + case IsolationLevel.Chaos: + case IsolationLevel.ReadUncommitted: + case IsolationLevel.ReadCommitted: + case IsolationLevel.RepeatableRead: + case IsolationLevel.Serializable: + case IsolationLevel.Snapshot: + Debug.Assert(false, "valid IsolationLevel " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); + } + + // DBDataPermissionAttribute.KeyRestrictionBehavior + internal static ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) + { +#if DEBUG + switch (value) + { + case KeyRestrictionBehavior.PreventUsage: + case KeyRestrictionBehavior.AllowOnly: + Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int)value); + } + + // IDataParameter.Direction + internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) + { +#if DEBUG + switch (value) + { + case ParameterDirection.Input: + case ParameterDirection.Output: + case ParameterDirection.InputOutput: + case ParameterDirection.ReturnValue: + Debug.Assert(false, "valid ParameterDirection " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); + } + + // + // DbConnectionOptions, DataAccess + // + internal static ArgumentException InvalidKeyname(string parameterName) + { + return Argument(StringsHelper.GetString(Strings.ADP_InvalidKey), parameterName); + } + internal static ArgumentException InvalidValue(string parameterName) + { + return Argument(StringsHelper.GetString(Strings.ADP_InvalidValue), parameterName); + } + internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndContextConnection() + { + return ADP.Argument(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection)); + } + internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndContextConnection() + { + return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndContextConnection)); + } + internal static Exception InvalidMixedUsageOfAccessTokenAndCredential() + { + return ADP.InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndCredential)); + } + + // + // DBDataPermission, DataAccess, Odbc + // + internal static Exception InvalidXMLBadVersion() + { + return Argument(StringsHelper.GetString(Strings.ADP_InvalidXMLBadVersion)); + } + internal static Exception NotAPermissionElement() + { + return Argument(StringsHelper.GetString(Strings.ADP_NotAPermissionElement)); + } + internal static Exception PermissionTypeMismatch() + { + return Argument(StringsHelper.GetString(Strings.ADP_PermissionTypeMismatch)); + } + + // + // DbDataReader + // + internal static Exception NumericToDecimalOverflow() + { + return InvalidCast(StringsHelper.GetString(Strings.ADP_NumericToDecimalOverflow)); + } + + // + // : IDbCommand + // + internal static Exception InvalidCommandTimeout(int value, string name) + { + return Argument(StringsHelper.GetString(Strings.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), name); + } + + // + // : DbDataAdapter + // + internal static InvalidOperationException ComputerNameEx(int lastError) + { + return InvalidOperation(StringsHelper.GetString(Strings.ADP_ComputerNameEx, lastError)); + } + + // global constant strings + internal const float FailoverTimeoutStepForTnir = 0.125F; // Fraction of timeout to use in case of Transparent Network IP resolution. + internal const int MinimumTimeoutForTnirMs = 500; // The first login attempt in Transparent network IP Resolution + + internal static readonly IntPtr s_ptrZero = IntPtr.Zero; // IntPtr.Zero + internal static readonly int s_ptrSize = IntPtr.Size; + internal static readonly IntPtr s_invalidPtr = new(-1); // use for INVALID_HANDLE + + internal static readonly bool s_isWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform); + internal static readonly bool s_isPlatformNT5 = (ADP.s_isWindowsNT && (Environment.OSVersion.Version.Major >= 5)); + + [FileIOPermission(SecurityAction.Assert, AllFiles = FileIOPermissionAccess.PathDiscovery)] + [ResourceExposure(ResourceScope.Machine)] + [ResourceConsumption(ResourceScope.Machine)] + internal static string GetFullPath(string filename) + { // MDAC 77686 + return Path.GetFullPath(filename); + } + + // TODO: cache machine name and listen to longhorn event to reset it + internal static string GetComputerNameDnsFullyQualified() + { + const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT + const int ERROR_MORE_DATA = 234; // winerror.h + + string value; + if (s_isPlatformNT5) + { + int length = 0; // length parameter must be zero if buffer is null + // query for the required length + // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive + int getComputerNameExError = 0; + if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) + { + getComputerNameExError = Marshal.GetLastWin32Error(); + } + if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) + { + throw ADP.ComputerNameEx(getComputerNameExError); + } + + StringBuilder buffer = new(length); + length = buffer.Capacity; + if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) + { + throw ADP.ComputerNameEx(Marshal.GetLastWin32Error()); + } + + // Note: In Longhorn you'll be able to rename a machine without + // rebooting. Therefore, don't cache this machine name. + value = buffer.ToString(); + } + else + { + value = ADP.MachineName(); + } + return value; + } + + [ResourceExposure(ResourceScope.Machine)] + [ResourceConsumption(ResourceScope.Machine)] + internal static object LocalMachineRegistryValue(string subkey, string queryvalue) + { // MDAC 77697 + (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028 + try + { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) + { + return key?.GetValue(queryvalue); + } + } + catch (SecurityException e) + { + // Even though we assert permission - it's possible there are + // ACL's on registry that cause SecurityException to be thrown. + ADP.TraceExceptionWithoutRethrow(e); + return null; + } + finally + { + RegistryPermission.RevertAssert(); + } + } + + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + internal static IntPtr IntPtrOffset(IntPtr pbase, int offset) + { + if (4 == ADP.s_ptrSize) + { + return (IntPtr)checked(pbase.ToInt32() + offset); + } + Debug.Assert(8 == ADP.s_ptrSize, "8 != IntPtr.Size"); // MDAC 73747 + return (IntPtr)checked(pbase.ToInt64() + offset); + } + + internal static bool IsEmpty(string str) => string.IsNullOrEmpty(str); + #endregion +#else + #region netcore project only + internal static Timer UnsafeCreateTimer(TimerCallback callback, object state, int dueTime, int period) + { + // Don't capture the current ExecutionContext and its AsyncLocals onto + // a global timer causing them to live forever + bool restoreFlow = false; + try + { + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + return new Timer(callback, state, dueTime, period); + } + finally + { + // Restore the current ExecutionContext + if (restoreFlow) + ExecutionContext.RestoreFlow(); + } + } + + // + // COM+ exceptions + // + internal static PlatformNotSupportedException DbTypeNotSupported(string dbType) => new(StringsHelper.GetString(Strings.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); + + // IDbConnection.BeginTransaction, OleDbTransaction.Begin + internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) + { +#if DEBUG + switch (value) + { + case IsolationLevel.Unspecified: + case IsolationLevel.Chaos: + case IsolationLevel.ReadUncommitted: + case IsolationLevel.ReadCommitted: + case IsolationLevel.RepeatableRead: + case IsolationLevel.Serializable: + case IsolationLevel.Snapshot: + Debug.Fail("valid IsolationLevel " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); + } + + // IDataParameter.Direction + internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) + { +#if DEBUG + switch (value) + { + case ParameterDirection.Input: + case ParameterDirection.Output: + case ParameterDirection.InputOutput: + case ParameterDirection.ReturnValue: + Debug.Fail("valid ParameterDirection " + value.ToString()); + break; + } +#endif + return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); + } + + // + // : IDbCommand + // + internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "") + => Argument(StringsHelper.GetString(Strings.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); + #endregion +#endif + } +} diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index ce7119d4b1..adeb6cbb0b 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -289,7 +289,7 @@ internal int ExecuteNonQuery() { throw SQL.BatchedUpdatesNotAvailableOnContextConnection(); } - ValidateCommandBehavior(ADP.ExecuteNonQuery, CommandBehavior.Default); + ValidateCommandBehavior(nameof(ExecuteNonQuery), CommandBehavior.Default); #endif BatchCommand.BatchRPCMode = true; BatchCommand.ClearBatchCommand(); @@ -328,4 +328,3 @@ private void ValidateCommandBehavior(string method, CommandBehavior behavior) } } } - diff --git a/src/Microsoft.Data.SqlClient/src/Resources/StringsHelper.cs b/src/Microsoft.Data.SqlClient/src/Resources/StringsHelper.cs index 23d563942c..cfdd2b8b97 100644 --- a/src/Microsoft.Data.SqlClient/src/Resources/StringsHelper.cs +++ b/src/Microsoft.Data.SqlClient/src/Resources/StringsHelper.cs @@ -54,7 +54,11 @@ public static string GetString(string res, params object[] args) args[i] = value.Substring(0, 1024 - 3) + "..."; } } + #if NETFRAMEWORK return string.Format(CultureInfo.CurrentCulture, res, args); + #else + return Format(res, args); + #endif } else {