From ea96ee3d86366ba21a5919101f64cc093a762fce Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 27 Jul 2020 12:09:50 +0300 Subject: [PATCH] Annotate System.Data.{Odbc,OleDb} for nullability (#39597) * Annotate System.Data.Odbc for nullability * Annotate System.Data.OleDb for nullability * Suppress nullable warnings on netcoreapp < 3.0 * Mark System.Data.DataSetExtensions as null-annotated * Fix null-check bug in System.Data.OleDb --- src/libraries/Common/src/Interop/Interop.Odbc.cs | 20 +- .../src/System/Data/Common/AdapterUtil.Drivers.cs | 2 +- .../Common/src/System/Data/Common/AdapterUtil.cs | 37 ++- .../src/System/Data/Common/BasicFieldNameLookup.cs | 10 +- .../Data/Common/DbConnectionOptions.Common.cs | 7 +- .../src/System/Data/Common/DbConnectionPoolKey.cs | 9 +- .../src/System/Data/Common/FieldNameLookup.cs | 2 +- .../src/System/Data/Common/MultipartIdentifier.cs | 2 - .../Common/src/System/Data/Common/NameValuePair.cs | 3 - .../System/Data/ProviderBase/DbConnectionClosed.cs | 12 +- .../Data/ProviderBase/DbConnectionFactory.cs | 69 ++--- .../Data/ProviderBase/DbConnectionInternal.cs | 34 +-- .../Data/ProviderBase/DbConnectionPoolGroup.cs | 20 +- .../System/Data/ProviderBase/DbMetaDataFactory.cs | 101 ++++---- .../Data/ProviderBase/DbReferenceCollection.cs | 11 +- src/libraries/Directory.Build.targets | 2 +- .../System.Data.Common/ref/System.Data.Common.cs | 10 +- .../src/System/Data/Common/DBCommandBuilder.cs | 10 +- .../src/System/Data/Common/DbDataAdapter.cs | 16 +- .../src/System/Data/Common/RowUpdatedEventArgs.cs | 6 +- .../src/System/Data/ConstraintCollection.cs | 2 +- .../System.Data.Common/src/System/Data/DataRow.cs | 2 +- .../src/System/Data/DataTable.cs | 12 +- .../src/System/Data/ProviderBase/SchemaMapping.cs | 2 +- .../src/System/Data/RecordManager.cs | 2 +- .../System.Data.Common/src/System/Data/Select.cs | 2 +- .../ref/System.Data.DataSetExtensions.csproj | 1 + .../src/System.Data.DataSetExtensions.csproj | 1 + .../System.Data.Odbc/ref/System.Data.Odbc.cs | 108 ++++---- .../System.Data.Odbc/ref/System.Data.Odbc.csproj | 3 +- .../Common/System/Data/Common/AdapterUtil.Odbc.cs | 20 +- .../System/Data/Common/DBConnectionString.cs | 66 ++--- .../System/Data/Common/DbConnectionOptions.cs | 42 +-- .../System/Data/Common/DbConnectionStringCommon.cs | 4 +- .../System/Data/Common/NameValuePermission.cs | 46 ++-- .../Common/System/Data/ProviderBase/DbBuffer.cs | 6 +- .../Data/ProviderBase/DbConnectionFactory.cs | 15 +- .../Data/ProviderBase/DbConnectionInternal.cs | 4 +- .../System/Data/ProviderBase/DbConnectionPool.cs | 72 +++--- .../DbConnectionPoolGroupProviderInfo.cs | 4 +- .../Data/ProviderBase/DbConnectionPoolIdentity.cs | 2 +- .../System.Data.Odbc/src/System.Data.Odbc.csproj | 1 + .../src/System/Data/Odbc/DbDataRecord.cs | 31 +-- .../src/System/Data/Odbc/Odbc32.cs | 6 +- .../src/System/Data/Odbc/OdbcCommand.cs | 176 ++++++------- .../src/System/Data/Odbc/OdbcCommandBuilder.cs | 20 +- .../src/System/Data/Odbc/OdbcConnection.cs | 81 +++--- .../src/System/Data/Odbc/OdbcConnectionFactory.cs | 36 +-- .../src/System/Data/Odbc/OdbcConnectionHelper.cs | 33 ++- .../src/System/Data/Odbc/OdbcConnectionOpen.cs | 6 +- .../Data/Odbc/OdbcConnectionPoolProviderInfo.cs | 12 +- .../src/System/Data/Odbc/OdbcConnectionString.cs | 4 +- .../Data/Odbc/OdbcConnectionStringbuilder.cs | 12 +- .../src/System/Data/Odbc/OdbcDataAdapter.cs | 50 ++-- .../src/System/Data/Odbc/OdbcDataReader.cs | 288 +++++++++++---------- .../src/System/Data/Odbc/OdbcEnvironment.cs | 8 +- .../src/System/Data/Odbc/OdbcError.cs | 4 +- .../src/System/Data/Odbc/OdbcErrorCollection.cs | 2 +- .../src/System/Data/Odbc/OdbcException.cs | 2 +- .../src/System/Data/Odbc/OdbcHandle.cs | 8 +- .../src/System/Data/Odbc/OdbcMetaDataFactory.cs | 145 ++++++----- .../src/System/Data/Odbc/OdbcParameter.cs | 98 +++---- .../System/Data/Odbc/OdbcParameterCollection.cs | 14 +- .../Data/Odbc/OdbcParameterCollectionHelper.cs | 6 +- .../src/System/Data/Odbc/OdbcParameterHelper.cs | 53 ++-- .../src/System/Data/Odbc/OdbcRowUpdatingEvent.cs | 12 +- .../src/System/Data/Odbc/OdbcStatementHandle.cs | 16 +- .../src/System/Data/Odbc/OdbcTransaction.cs | 22 +- .../System.Data.OleDb/ref/System.Data.OleDb.cs | 106 ++++---- .../System.Data.OleDb/ref/System.Data.OleDb.csproj | 1 + .../System.Data.OleDb/src/AdapterSwitches.cs | 4 +- .../System.Data.OleDb/src/ColumnBinding.cs | 41 +-- src/libraries/System.Data.OleDb/src/DbBindings.cs | 30 +-- .../System.Data.OleDb/src/DbConnectionOptions.cs | 73 +++--- .../src/DbConnectionStringCommon.cs | 5 +- .../System.Data.OleDb/src/DbParameterHelper.cs | 32 +-- src/libraries/System.Data.OleDb/src/DbPropSet.cs | 12 +- .../System.Data.OleDb/src/NativeMethods.cs | 2 +- .../System.Data.OleDb/src/OleDbCommand.cs | 176 ++++++------- .../System.Data.OleDb/src/OleDbCommandBuilder.cs | 48 ++-- .../System.Data.OleDb/src/OleDbConnection.cs | 88 +++---- .../src/OleDbConnectionFactory.cs | 35 +-- .../src/OleDbConnectionInternal.cs | 107 ++++---- .../src/OleDbConnectionPoolGroupProviderInfo.cs | 6 +- .../System.Data.OleDb/src/OleDbConnectionString.cs | 62 ++--- .../src/OleDbConnectionStringBuilder.cs | 57 ++-- .../System.Data.OleDb/src/OleDbDataAdapter.cs | 76 +++--- .../System.Data.OleDb/src/OleDbDataReader.cs | 284 ++++++++++---------- .../System.Data.OleDb/src/OleDbEnumerator.cs | 12 +- src/libraries/System.Data.OleDb/src/OleDbError.cs | 14 +- .../System.Data.OleDb/src/OleDbErrorCollection.cs | 6 +- .../System.Data.OleDb/src/OleDbException.cs | 12 +- .../System.Data.OleDb/src/OleDbInfoMessageEvent.cs | 2 +- .../System.Data.OleDb/src/OleDbMetaDataFactory.cs | 80 +++--- .../System.Data.OleDb/src/OleDbParameter.cs | 80 +++--- .../src/OleDbParameterCollection.cs | 10 +- .../src/OleDbParameterCollectionHelper.cs | 6 +- .../System.Data.OleDb/src/OleDbRowUpdatedEvent.cs | 6 +- .../System.Data.OleDb/src/OleDbRowUpdatingEvent.cs | 6 +- src/libraries/System.Data.OleDb/src/OleDbStruct.cs | 38 +-- .../System.Data.OleDb/src/OleDbTransaction.cs | 24 +- .../System.Data.OleDb/src/OleDbWrapper.cs | 54 ++-- src/libraries/System.Data.OleDb/src/OleDb_Enum.cs | 6 +- src/libraries/System.Data.OleDb/src/OleDb_Util.cs | 14 +- .../System.Data.OleDb/src/PropertyInfoSet.cs | 18 +- src/libraries/System.Data.OleDb/src/RowBinding.cs | 18 +- src/libraries/System.Data.OleDb/src/SafeHandles.cs | 12 +- .../System.Data.OleDb/src/System.Data.OleDb.csproj | 1 + .../src/System/Data/Common/AdapterUtil.cs | 65 ++--- .../src/System/Data/Common/DbConnectionPoolKey.cs | 10 +- .../src/System/Data/Common/FieldNameLookup.cs | 12 +- .../src/System/Data/Common/NameValuePair.cs | 10 +- .../System.Data.OleDb/src/System/Data/Common/SR.cs | 2 +- .../src/System/Data/ProviderBase/DbBuffer.cs | 2 +- .../System/Data/ProviderBase/DbConnectionClosed.cs | 12 +- .../Data/ProviderBase/DbConnectionFactory.cs | 64 ++--- .../System/Data/ProviderBase/DbConnectionHelper.cs | 38 +-- .../ProviderBase/DbConnectionInternal.Shared.cs | 66 ++--- .../Data/ProviderBase/DbConnectionInternal.cs | 12 +- .../System/Data/ProviderBase/DbConnectionPool.cs | 90 +++---- .../Data/ProviderBase/DbConnectionPoolCounters.cs | 38 +-- .../Data/ProviderBase/DbConnectionPoolGroup.cs | 20 +- .../DbConnectionPoolGroupProviderInfo.cs | 4 +- .../Data/ProviderBase/DbConnectionPoolIdentity.cs | 2 +- .../System/Data/ProviderBase/DbMetaDataFactory.cs | 104 ++++---- .../Data/ProviderBase/DbReferenceCollection.cs | 10 +- .../System/Data/ProviderBase/WrappedIUnknown.cs | 4 +- .../System.Data.OleDb/src/UnsafeNativeMethods.cs | 16 +- 128 files changed, 2104 insertions(+), 2086 deletions(-) diff --git a/src/libraries/Common/src/Interop/Interop.Odbc.cs b/src/libraries/Common/src/Interop/Interop.Odbc.cs index 591ce1c..4113c59 100644 --- a/src/libraries/Common/src/Interop/Interop.Odbc.cs +++ b/src/libraries/Common/src/Interop/Interop.Odbc.cs @@ -250,9 +250,9 @@ internal static partial class Interop [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLPrimaryKeysW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, - /*SQLCHAR* */string CatalogName, + /*SQLCHAR* */string? CatalogName, /*SQLSMALLINT*/short NameLen1, - /*SQLCHAR* */ string SchemaName, + /*SQLCHAR* */ string? SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */string TableName, /*SQLSMALLINT*/short NameLen3); @@ -260,13 +260,13 @@ internal static partial class Interop [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLProcedureColumnsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, - /*SQLCHAR* */ string CatalogName, + /*SQLCHAR* */ string? CatalogName, /*SQLSMALLINT*/short NameLen1, - /*SQLCHAR* */ string SchemaName, + /*SQLCHAR* */ string? SchemaName, /*SQLSMALLINT*/short NameLen2, - /*SQLCHAR* */ string ProcName, + /*SQLCHAR* */ string? ProcName, /*SQLSMALLINT*/short NameLen3, - /*SQLCHAR* */ string ColumnName, + /*SQLCHAR* */ string? ColumnName, /*SQLSMALLINT*/short NameLen4); [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] @@ -347,9 +347,9 @@ internal static partial class Interop internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSpecialColumnsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, /*SQLUSMALLINT*/ODBC32.SQL_SPECIALCOLS IdentifierType, - /*SQLCHAR* */string CatalogName, + /*SQLCHAR* */string? CatalogName, /*SQLSMALLINT*/short NameLen1, - /*SQLCHAR* */string SchemaName, + /*SQLCHAR* */string? SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */string TableName, /*SQLSMALLINT*/short NameLen3, @@ -359,9 +359,9 @@ internal static partial class Interop [DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)] internal static extern /*SQLRETURN*/ODBC32.RetCode SQLStatisticsW( /*SQLHSTMT*/OdbcStatementHandle StatementHandle, - /*SQLCHAR* */string CatalogName, + /*SQLCHAR* */string? CatalogName, /*SQLSMALLINT*/short NameLen1, - /*SQLCHAR* */string SchemaName, + /*SQLCHAR* */string? SchemaName, /*SQLSMALLINT*/short NameLen2, /*SQLCHAR* */IntPtr TableName, // IntPtr instead of string because callee may mutate contents /*SQLSMALLINT*/short NameLen3, diff --git a/src/libraries/Common/src/System/Data/Common/AdapterUtil.Drivers.cs b/src/libraries/Common/src/System/Data/Common/AdapterUtil.Drivers.cs index 509aa98..4ee63ad 100644 --- a/src/libraries/Common/src/System/Data/Common/AdapterUtil.Drivers.cs +++ b/src/libraries/Common/src/System/Data/Common/AdapterUtil.Drivers.cs @@ -8,7 +8,7 @@ namespace System.Data.Common internal static partial class ADP { - internal static Timer UnsafeCreateTimer(TimerCallback callback, object state, int dueTime, int period) + 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 diff --git a/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs b/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs index c61589b..3675641 100644 --- a/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs +++ b/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs @@ -1,13 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable nullability as part of annotation System.Data.{Odbc,OleDb} -#nullable disable -#pragma warning disable CS8632 - using System.Collections; using System.Data.SqlTypes; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; using System.Security; @@ -22,11 +19,11 @@ namespace System.Data.Common { // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (https://docs.microsoft.com/en-us/dotnet/framework/performance/sql-server-programming-and-host-protection-attributes) // 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? _trueTask; + internal static Task TrueTask => _trueTask ??= Task.FromResult(true); - private static Task _falseTask; - internal static Task FalseTask => _falseTask ?? (_falseTask = Task.FromResult(false)); + private static Task? _falseTask; + internal static Task FalseTask => _falseTask ??= Task.FromResult(false); internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; @@ -51,14 +48,14 @@ namespace System.Data.Common return e; } - internal static ArgumentException Argument(string error, Exception inner) + 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) + internal static ArgumentException Argument(string error, string? parameter) { ArgumentException e = new ArgumentException(error, parameter); TraceExceptionAsReturnValue(e); @@ -105,7 +102,7 @@ namespace System.Data.Common return InvalidCast(error, null); } - internal static InvalidCastException InvalidCast(string error, Exception inner) + internal static InvalidCastException InvalidCast(string error, Exception? inner) { InvalidCastException e = new InvalidCastException(error, inner); TraceExceptionAsReturnValue(e); @@ -135,7 +132,7 @@ namespace System.Data.Common // 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) + 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; @@ -164,7 +161,7 @@ namespace System.Data.Common // is the prefix present? if (prefixLength > 0) { - if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal)) + if (!quotedString.StartsWith(quotePrefix!, StringComparison.Ordinal)) { unquotedString = quotedString; return false; @@ -174,7 +171,7 @@ namespace System.Data.Common // is the suffix present? if (suffixLength > 0) { - if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal)) + if (!quotedString.EndsWith(quoteSuffix!, StringComparison.Ordinal)) { unquotedString = quotedString; return false; @@ -224,7 +221,7 @@ namespace System.Data.Common return e; } - internal static void CheckArgumentNull(object value, string parameterName) + internal static void CheckArgumentNull([NotNull] object? value, string parameterName) { if (null == value) { @@ -290,7 +287,7 @@ namespace System.Data.Common { return Argument(SR.Format(SR.ADP_KeywordNotSupported, keyword)); } - internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) + internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception? innerException) { return ADP.Argument(SR.Format(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); } @@ -302,7 +299,7 @@ namespace System.Data.Common { return InvalidConnectionOptionValue(key, null); } - internal static Exception InvalidConnectionOptionValue(string key, Exception inner) + internal static Exception InvalidConnectionOptionValue(string key, Exception? inner) { return Argument(SR.Format(SR.ADP_InvalidConnectionOptionValue, key), inner); } @@ -480,15 +477,15 @@ namespace System.Data.Common 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 IsEmptyArray([NotNullWhen(false)] string?[]? array) => (null == array) || (0 == array.Length); - internal static bool IsNull(object value) + internal static bool IsNull(object? value) { if ((null == value) || (DBNull.Value == value)) { return true; } - INullable nullable = (value as INullable); + INullable? nullable = (value as INullable); return ((null != nullable) && nullable.IsNull); } diff --git a/src/libraries/Common/src/System/Data/Common/BasicFieldNameLookup.cs b/src/libraries/Common/src/System/Data/Common/BasicFieldNameLookup.cs index 4415ef3..fbe4a2c 100644 --- a/src/libraries/Common/src/System/Data/Common/BasicFieldNameLookup.cs +++ b/src/libraries/Common/src/System/Data/Common/BasicFieldNameLookup.cs @@ -11,13 +11,13 @@ namespace System.Data.ProviderBase internal class BasicFieldNameLookup { // Dictionary stores the index into the _fieldNames, match via case-sensitive - private Dictionary _fieldNameLookup; + private Dictionary? _fieldNameLookup; // original names for linear searches when exact matches fail private readonly string[] _fieldNames; // By default _compareInfo is set to InvariantCulture CompareInfo - private CompareInfo _compareInfo; + private CompareInfo? _compareInfo; public BasicFieldNameLookup(string[] fieldNames) { @@ -74,7 +74,7 @@ namespace System.Data.ProviderBase int value; // via case sensitive search, first match with lowest ordinal matches - return _fieldNameLookup.TryGetValue(fieldName, out value) ? value : -1; + return _fieldNameLookup!.TryGetValue(fieldName, out value) ? value : -1; } public int IndexOf(string fieldName) @@ -85,7 +85,7 @@ namespace System.Data.ProviderBase } int index; // via case sensitive search, first match with lowest ordinal matches - if (!_fieldNameLookup.TryGetValue(fieldName, out index)) + if (!_fieldNameLookup!.TryGetValue(fieldName, out index)) { // via case insensitive search, first match with lowest ordinal matches index = LinearIndexOf(fieldName, CompareOptions.IgnoreCase); @@ -116,7 +116,7 @@ namespace System.Data.ProviderBase { if (0 == _compareInfo.Compare(fieldName, _fieldNames[i], compareOptions)) { - _fieldNameLookup[fieldName] = i; // add an exact match for the future + _fieldNameLookup![fieldName] = i; // add an exact match for the future return i; } } diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs index 83f6b89..fda8cc8 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated -#nullable disable -#pragma warning disable CS8632 - using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -416,8 +412,7 @@ namespace System.Data.Common return true; } - // TODO: Annotate with [NotNullWhen(true)] when annotating System.Data.{Odbc,OleDb} - private static bool IsKeyNameValid(string? keyname) + private static bool IsKeyNameValid([NotNullWhen(true)] string? keyname) { if (null != keyname) { diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs index a2cd466..6c5a567 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs @@ -1,18 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated -#pragma warning disable CS8632 - namespace System.Data.Common { // DbConnectionPoolKey: Base class implementation of a key to connection pool groups // Only connection string is used as a key internal class DbConnectionPoolKey : ICloneable { - private string _connectionString; + private string? _connectionString; - internal DbConnectionPoolKey(string connectionString) + internal DbConnectionPoolKey(string? connectionString) { _connectionString = connectionString; } @@ -27,7 +24,7 @@ namespace System.Data.Common return new DbConnectionPoolKey(this); } - internal virtual string ConnectionString + internal virtual string? ConnectionString { get { diff --git a/src/libraries/Common/src/System/Data/Common/FieldNameLookup.cs b/src/libraries/Common/src/System/Data/Common/FieldNameLookup.cs index 8e66d67..7f5ab2c 100644 --- a/src/libraries/Common/src/System/Data/Common/FieldNameLookup.cs +++ b/src/libraries/Common/src/System/Data/Common/FieldNameLookup.cs @@ -33,7 +33,7 @@ namespace System.Data.ProviderBase //The compare info is specified by the server by specifying the default LocaleId. protected override CompareInfo GetCompareInfo() { - CompareInfo compareInfo = null; + CompareInfo? compareInfo = null; if (-1 != _defaultLocaleID) { compareInfo = CompareInfo.GetCompareInfo(_defaultLocaleID); diff --git a/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs b/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs index 3338928..0aaca59 100644 --- a/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs +++ b/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated -#pragma warning disable CS8632 //------------------------------------------------------------------------------ using System.Text; diff --git a/src/libraries/Common/src/System/Data/Common/NameValuePair.cs b/src/libraries/Common/src/System/Data/Common/NameValuePair.cs index 435b998..09ec226 100644 --- a/src/libraries/Common/src/System/Data/Common/NameValuePair.cs +++ b/src/libraries/Common/src/System/Data/Common/NameValuePair.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated -#pragma warning disable CS8632 - using System.Diagnostics; namespace System.Data.Common diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionClosed.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionClosed.cs index 11cc515..3a78447 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionClosed.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionClosed.cs @@ -27,12 +27,12 @@ namespace System.Data.ProviderBase protected override void Deactivate() => ADP.ClosedConnectionError(); - protected internal override DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) + protected internal override DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string?[]? restrictions) => throw ADP.ClosedConnectionError(); protected override DbReferenceCollection CreateReferenceCollection() => throw ADP.ClosedConnectionError(); - internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) => base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions); } @@ -42,7 +42,7 @@ namespace System.Data.ProviderBase { } - internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) => throw ADP.ConnectionAlreadyOpen(State); } @@ -81,10 +81,10 @@ namespace System.Data.ProviderBase connectionFactory.SetInnerConnectionTo(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance); } - internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) => TryOpenConnection(outerConnection, connectionFactory, retry, userOptions); - internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { if (retry == null || !retry.Task.IsCompleted) { @@ -131,7 +131,7 @@ namespace System.Data.ProviderBase { } - internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) => TryOpenConnection(outerConnection, connectionFactory, retry, userOptions); } } diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs index 832006da..5418b4f 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Data.Common; +using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -22,8 +23,8 @@ namespace System.Data.ProviderBase // s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to // a maximum of Environment.ProcessorCount at a time. private static uint s_pendingOpenNonPooledNext; - private static readonly Task[] s_pendingOpenNonPooled = new Task[Environment.ProcessorCount]; - private static Task s_completedTask; + private static readonly Task[] s_pendingOpenNonPooled = new Task[Environment.ProcessorCount]; + private static Task? s_completedTask; protected DbConnectionFactory() { @@ -57,7 +58,7 @@ namespace System.Data.ProviderBase { ADP.CheckArgumentNull(connection, nameof(connection)); - DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); + DbConnectionPoolGroup? poolGroup = GetConnectionPoolGroup(connection); if (null != poolGroup) { poolGroup.Clear(); @@ -69,7 +70,7 @@ namespace System.Data.ProviderBase Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString)); - DbConnectionPoolGroup poolGroup; + DbConnectionPoolGroup? poolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; if (connectionPoolGroups.TryGetValue(key, out poolGroup)) { @@ -77,22 +78,22 @@ namespace System.Data.ProviderBase } } - internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions) + internal virtual DbConnectionPoolProviderInfo? CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions) { return null; } - internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) + internal DbConnectionInternal? CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions? userOptions) { Debug.Assert(null != owningConnection, "null owningConnection?"); Debug.Assert(null != poolGroup, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; - DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo; + DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo!; DbConnectionPoolKey poolKey = poolGroup.PoolKey; - DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); + DbConnectionInternal? newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); if (null != newConnection) { newConnection.MakeNonPooledObject(owningConnection); @@ -100,12 +101,12 @@ namespace System.Data.ProviderBase return newConnection; } - internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) + internal DbConnectionInternal? CreatePooledConnection(DbConnectionPool pool, DbConnection? owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions? userOptions) { Debug.Assert(null != pool, "null pool?"); - DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; + DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo!; - DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); + DbConnectionInternal? newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); if (null != newConnection) { newConnection.MakePooledConnection(pool); @@ -113,7 +114,7 @@ namespace System.Data.ProviderBase return newConnection; } - internal virtual DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) + internal virtual DbConnectionPoolGroupProviderInfo? CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) { return null; } @@ -125,12 +126,12 @@ namespace System.Data.ProviderBase PruningDueTime, PruningPeriod); - protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key) + protected DbConnectionOptions? FindConnectionOptions(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); if (!string.IsNullOrEmpty(key.ConnectionString)) { - DbConnectionPoolGroup connectionPoolGroup; + DbConnectionPoolGroup? connectionPoolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { @@ -140,13 +141,13 @@ namespace System.Data.ProviderBase return null; } - private static Task GetCompletedTask() + private static Task GetCompletedTask() { Debug.Assert(Monitor.IsEntered(s_pendingOpenNonPooled), $"Expected {nameof(s_pendingOpenNonPooled)} lock to be held."); - return s_completedTask ?? (s_completedTask = Task.FromResult(null)); + return s_completedTask ?? (s_completedTask = Task.FromResult(null)); } - private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) + private DbConnectionPool? GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) { // if poolgroup is disabled, it will be replaced with a new entry @@ -165,28 +166,28 @@ namespace System.Data.ProviderBase if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { // reusing existing pool option in case user originally used SetConnectionPoolOptions - DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; + DbConnectionPoolGroupOptions? poolOptions = connectionPoolGroup.PoolGroupOptions; // get the string to hash on again - DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions; + DbConnectionOptions? connectionOptions = connectionPoolGroup.ConnectionOptions; Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); - connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions); + connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions)!; Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } - DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this); + DbConnectionPool? connectionPool = connectionPoolGroup.GetConnectionPool(this); return connectionPool; } - internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions) + internal DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions? poolOptions, ref DbConnectionOptions? userConnectionOptions) { if (string.IsNullOrEmpty(key.ConnectionString)) { - return (DbConnectionPoolGroup)null; + return null; } - DbConnectionPoolGroup connectionPoolGroup; + DbConnectionPoolGroup? connectionPoolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) { @@ -194,7 +195,7 @@ namespace System.Data.ProviderBase // our collection of pool entries, then we need to create a // new pool entry and add it to our collection. - DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); + DbConnectionOptions? connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); if (null == connectionOptions) { throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); @@ -225,7 +226,7 @@ namespace System.Data.ProviderBase connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { - DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions); + DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions!); newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions); // build new dictionary with space for new connection string @@ -256,7 +257,7 @@ namespace System.Data.ProviderBase } - private void PruneConnectionPoolGroups(object state) + private void PruneConnectionPoolGroups(object? state) { // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the @@ -368,7 +369,7 @@ namespace System.Data.ProviderBase } } - protected virtual DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) + protected virtual DbConnectionInternal? CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningConnection, DbConnectionOptions? userOptions) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection); } @@ -379,7 +380,7 @@ namespace System.Data.ProviderBase // get the matadatafactory from the pool entry. If it does not already have one // create one and save it on the pool entry - DbMetaDataFactory metaDataFactory = connectionPoolGroup.MetaDataFactory; + DbMetaDataFactory? metaDataFactory = connectionPoolGroup.MetaDataFactory; // consider serializing this so we don't construct multiple metadata factories // if two threads happen to hit this at the same time. One will be GC'd @@ -403,15 +404,15 @@ namespace System.Data.ProviderBase throw ADP.NotSupported(); } - protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection); + protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningConnection); - protected abstract DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous); + protected abstract DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions? previous); - protected abstract DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options); + protected abstract DbConnectionPoolGroupOptions? CreateConnectionPoolGroupOptions(DbConnectionOptions options); - internal abstract DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection); + internal abstract DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnection connection); - internal abstract DbConnectionInternal GetInnerConnection(DbConnection connection); + internal abstract DbConnectionInternal? GetInnerConnection(DbConnection connection); internal abstract void PermissionDemand(DbConnection outerConnection); diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs index 4afa5d3..5c1c4c0 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs @@ -21,8 +21,8 @@ namespace System.Data.ProviderBase private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections) - private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only) - private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated + private DbConnectionPool? _connectionPool; // the pooler that the connection came from (Pooled connections only) + private DbReferenceCollection? _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool) private bool _connectionIsDoomed; // true when the connection should no longer be used. @@ -113,17 +113,17 @@ namespace System.Data.ProviderBase } - protected internal object Owner + protected internal object? Owner { // We use a weak reference to the owning object so we can identify when - // it has been garbage collected without thowing exceptions. + // it has been garbage collected without throwing exceptions. get { return _owningObject.Target; } } - internal DbConnectionPool Pool + internal DbConnectionPool? Pool { get { @@ -131,7 +131,7 @@ namespace System.Data.ProviderBase } } - protected internal DbReferenceCollection ReferenceCollection + protected internal DbReferenceCollection? ReferenceCollection { get { @@ -199,12 +199,12 @@ namespace System.Data.ProviderBase // By default, there is no preparation required } - protected virtual object ObtainAdditionalLocksForClose() + protected virtual object? ObtainAdditionalLocksForClose() { return null; // no additional locks in default implementation } - protected virtual void ReleaseAdditionalLocksForClose(object lockToken) + protected virtual void ReleaseAdditionalLocksForClose(object? lockToken) { // no additional locks in default implementation } @@ -218,6 +218,8 @@ namespace System.Data.ProviderBase internal void DeactivateConnection() { + Debug.Assert(Pool != null); + // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. @@ -251,7 +253,7 @@ namespace System.Data.ProviderBase _connectionIsDoomed = true; } - protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) + protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string?[]? restrictions) { Debug.Assert(outerConnection != null, "outerConnection may not be null."); @@ -282,7 +284,7 @@ namespace System.Data.ProviderBase internal void NotifyWeakReference(int message) { - DbReferenceCollection referenceCollection = ReferenceCollection; + DbReferenceCollection? referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Notify(message); @@ -302,22 +304,22 @@ namespace System.Data.ProviderBase /// override this and do the correct thing. // User code should either override DbConnectionInternal.Activate when it comes out of the pool // or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections - internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { throw ADP.ConnectionAlreadyOpen(State); } - internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { throw ADP.MethodNotImplemented(); } - protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { // ?->Connecting: prevent set_ConnectionString during Open if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) { - DbConnectionInternal openConnection = null; + DbConnectionInternal? openConnection = null; try { connectionFactory.PermissionDemand(outerConnection); @@ -343,7 +345,7 @@ namespace System.Data.ProviderBase return true; } - internal void PrePush(object expectedOwner) + internal void PrePush(object? expectedOwner) { // Called by DbConnectionPool when we're about to be put into it's pool, we // take this opportunity to ensure ownership and pool counts are legit. @@ -412,7 +414,7 @@ namespace System.Data.ProviderBase internal void RemoveWeakReference(object value) { - DbReferenceCollection referenceCollection = ReferenceCollection; + DbReferenceCollection? referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Remove(value); diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs index eb0f8ed..26ee3b6 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -34,8 +34,8 @@ namespace System.Data.ProviderBase private int _state; // see PoolGroupState* below - private DbConnectionPoolGroupProviderInfo _providerInfo; - private DbMetaDataFactory _metaDataFactory; + private DbConnectionPoolGroupProviderInfo? _providerInfo; + private DbMetaDataFactory? _metaDataFactory; // always lock this before changing _state, we don't want to move out of the 'Disabled' state // PoolGroupStateUninitialized = 0; @@ -63,7 +63,7 @@ namespace System.Data.ProviderBase internal DbConnectionPoolKey PoolKey => _poolKey; - internal DbConnectionPoolGroupProviderInfo ProviderInfo + internal DbConnectionPoolGroupProviderInfo? ProviderInfo { get { @@ -74,7 +74,7 @@ namespace System.Data.ProviderBase _providerInfo = value; if (null != value) { - _providerInfo.PoolGroup = this; + _providerInfo!.PoolGroup = this; } } } @@ -83,7 +83,7 @@ namespace System.Data.ProviderBase internal DbConnectionPoolGroupOptions PoolGroupOptions => _poolGroupOptions; - internal DbMetaDataFactory MetaDataFactory + internal DbMetaDataFactory? MetaDataFactory { get { @@ -102,7 +102,7 @@ namespace System.Data.ProviderBase // will return the number of connections in the group after clearing has finished // First, note the old collection and create a new collection to be used - ConcurrentDictionary oldPoolCollection = null; + ConcurrentDictionary? oldPoolCollection = null; lock (this) { if (_poolCollection.Count > 0) @@ -130,7 +130,7 @@ namespace System.Data.ProviderBase return _poolCollection.Count; } - internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory) + internal DbConnectionPool? GetConnectionPool(DbConnectionFactory connectionFactory) { // When this method returns null it indicates that the connection // factory should not use pooling. @@ -138,10 +138,10 @@ namespace System.Data.ProviderBase // We don't support connection pooling on Win9x; // PoolGroupOptions will only be null when we're not supposed to pool // connections. - DbConnectionPool pool = null; + DbConnectionPool? pool = null; if (null != _poolGroupOptions) { - DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity; + DbConnectionPoolIdentity? currentIdentity = DbConnectionPoolIdentity.NoIdentity; if (_poolGroupOptions.PoolByIdentity) { @@ -168,7 +168,7 @@ namespace System.Data.ProviderBase // Did someone already add it to the list? if (!_poolCollection.TryGetValue(currentIdentity, out pool)) { - DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions); + DbConnectionPoolProviderInfo? connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions); DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo); if (MarkPoolGroupAsActive()) diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 614b11c..3a12fa5 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -37,7 +37,8 @@ namespace System.Data.ProviderBase ADP.CheckArgumentNull(serverVersion, nameof(serverVersion)); ADP.CheckArgumentNull(normalizedServerVersion, nameof(normalizedServerVersion)); - LoadDataSetFromXml(xmlStream); + _metaDataCollectionsDataSet = new DataSet { Locale = CultureInfo.InvariantCulture }; + _metaDataCollectionsDataSet.ReadXml(xmlStream); _serverVersionString = serverVersion; _normalizedServerVersion = normalizedServerVersion; @@ -49,14 +50,14 @@ namespace System.Data.ProviderBase protected string ServerVersionNormalized => _normalizedServerVersion; - protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames) + protected DataTable CloneAndFilterCollection(string collectionName, string[]? hiddenColumnNames) { DataTable destinationTable; DataColumn[] filteredSourceColumns; DataColumnCollection destinationColumns; DataRow newRow; - DataTable sourceTable = _metaDataCollectionsDataSet.Tables[collectionName]; + DataTable? sourceTable = _metaDataCollectionsDataSet.Tables[collectionName]; if ((sourceTable == null) || (collectionName != sourceTable.TableName)) { @@ -94,27 +95,27 @@ namespace System.Data.ProviderBase { if (disposing) { - _normalizedServerVersion = null; - _serverVersionString = null; + _normalizedServerVersion = null!; + _serverVersionString = null!; _metaDataCollectionsDataSet.Dispose(); } } - private DataTable ExecuteCommand(DataRow requestedCollectionRow, string[] restrictions, DbConnection connection) + private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? restrictions, DbConnection connection) { - DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString]; - DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions]; - DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName]; + DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; + DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString]!; + DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions]!; + DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName]!; - DataTable resultTable = null; - DbCommand command = null; - DataTable schemaTable = null; + DataTable? resultTable = null; + DbCommand? command = null; + DataTable? schemaTable = null; Debug.Assert(requestedCollectionRow != null); - string sqlCommand = requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string; + string sqlCommand = (requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string)!; int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn, DataRowVersion.Current]; - string collectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string; + string collectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; if ((restrictions != null) && (restrictions.Length > numberOfRestrictions)) { @@ -145,7 +146,7 @@ namespace System.Data.ProviderBase command.Parameters.Add(restrictionParameter); } - DbDataReader reader = null; + DbDataReader? reader = null; try { try @@ -190,7 +191,7 @@ namespace System.Data.ProviderBase return resultTable; } - private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns) + private DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumnNames, DataColumnCollection destinationColumns) { int columnCount = 0; foreach (DataColumn sourceColumn in sourceTable.Columns) @@ -227,23 +228,23 @@ namespace System.Data.ProviderBase bool versionFailure; bool haveExactMatch; bool haveMultipleInexactMatches; - string candidateCollectionName; + string? candidateCollectionName; - DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; + DataTable? metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; if (metaDataCollectionsTable == null) { throw ADP.InvalidXml(); } - DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; + DataColumn? collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName); } - DataRow requestedCollectionRow = null; - string exactCollectionName = null; + DataRow? requestedCollectionRow = null; + string? exactCollectionName = null; // find the requested collection versionFailure = false; @@ -316,8 +317,8 @@ namespace System.Data.ProviderBase private void FixUpVersion(DataTable dataSourceInfoTable) { Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation); - DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion]; - DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized]; + DataColumn? versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion]; + DataColumn? normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized]; if ((versionColumn == null) || (normalizedVersionColumn == null)) { @@ -340,14 +341,14 @@ namespace System.Data.ProviderBase private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) { - DataTable restrictionsTable = null; - DataColumnCollection restrictionColumns = null; - DataColumn collectionName = null; - DataColumn parameterName = null; - DataColumn restrictionName = null; - DataColumn restrictionNumber = null; + DataTable? restrictionsTable = null; + DataColumnCollection? restrictionColumns = null; + DataColumn? collectionName = null; + DataColumn? parameterName = null; + DataColumn? restrictionName = null; + DataColumn? restrictionNumber = null; - string result = null; + string? result = null; restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; if (restrictionsTable != null) @@ -367,7 +368,7 @@ namespace System.Data.ProviderBase throw ADP.MissingRestrictionColumn(); } - foreach (DataRow restriction in restrictionsTable.Rows) + foreach (DataRow restriction in restrictionsTable!.Rows) { if (((string)restriction[collectionName] == neededCollectionName) && @@ -388,27 +389,27 @@ namespace System.Data.ProviderBase return result; } - public virtual DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions) + public virtual DataTable GetSchema(DbConnection connection, string collectionName, string?[]? restrictions) { Debug.Assert(_metaDataCollectionsDataSet != null); - DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]; - DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; - DataRow requestedCollectionRow = null; - DataTable requestedSchema = null; - string[] hiddenColumns; - string exactCollectionName = null; + DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; + DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]!; + DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]!; + DataRow? requestedCollectionRow = null; + DataTable? requestedSchema = null; + string[]? hiddenColumns; + string? exactCollectionName = null; requestedCollectionRow = FindMetaDataCollectionRow(collectionName); - exactCollectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string; + exactCollectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; if (ADP.IsEmptyArray(restrictions) == false) { for (int i = 0; i < restrictions.Length; i++) { - if ((restrictions[i] != null) && (restrictions[i].Length > 4096)) + if ((restrictions[i]?.Length > 4096)) { // use a non-specific error because no new beta 2 error messages are allowed // TODO: will add a more descriptive error in RTM @@ -417,10 +418,9 @@ namespace System.Data.ProviderBase } } - string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string; + string populationMechanism = (requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string)!; switch (populationMechanism) { - case _dataTable: if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections) { @@ -466,7 +466,7 @@ namespace System.Data.ProviderBase return requestedSchema; } - private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames) + private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames) { bool result = true; @@ -499,14 +499,7 @@ namespace System.Data.ProviderBase return result; } - private void LoadDataSetFromXml(Stream XmlStream) - { - _metaDataCollectionsDataSet = new DataSet(); - _metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture; - _metaDataCollectionsDataSet.ReadXml(XmlStream); - } - - protected virtual DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection) + protected virtual DataTable PrepareCollection(string collectionName, string?[]? restrictions, DbConnection connection) { throw ADP.NotSupported(); } @@ -515,7 +508,7 @@ namespace System.Data.ProviderBase { bool result = true; DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns; - DataColumn versionColumn; + DataColumn? versionColumn; object version; // check the minimum version first diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbReferenceCollection.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbReferenceCollection.cs index b13b20c..1ccde66 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbReferenceCollection.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbReferenceCollection.cs @@ -6,6 +6,7 @@ //------------------------------------------------------------------------------ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Data.ProviderBase @@ -55,7 +56,7 @@ namespace System.Data.ProviderBase } } - public object Target + public object? Target { get { @@ -136,6 +137,7 @@ namespace System.Data.ProviderBase } } + [return: MaybeNull] internal T FindItem(int tag, Func filterMethod) where T : class { bool lockObtained = false; @@ -154,12 +156,11 @@ namespace System.Data.ProviderBase { // NOTE: Check if the returned value is null twice may seem wasteful, but this if for performance // Since checking for null twice is cheaper than calling both HasTarget and Target OR always attempting to typecast - object value = _items[counter].Target; + object? value = _items[counter].Target; if (value != null) { // Make sure the item has the correct type and passes the filtering - T tempItem = value as T; - if ((tempItem != null) && (filterMethod(tempItem))) + if (value is T tempItem && filterMethod(tempItem)) { return tempItem; } @@ -195,7 +196,7 @@ namespace System.Data.ProviderBase { for (int index = 0; index <= _lastItemIndex; ++index) { - object value = _items[index].Target; // checks tag & gets target + object? value = _items[index].Target; // checks tag & gets target if (null != value) { NotifyItem(message, _items[index].Tag, value); diff --git a/src/libraries/Directory.Build.targets b/src/libraries/Directory.Build.targets index 7fdfb48..95dae26 100644 --- a/src/libraries/Directory.Build.targets +++ b/src/libraries/Directory.Build.targets @@ -3,7 +3,7 @@ - $(NoWarn);nullable + $(NoWarn);nullable $(NoWarn);nullable diff --git a/src/libraries/System.Data.Common/ref/System.Data.Common.cs b/src/libraries/System.Data.Common/ref/System.Data.Common.cs index 5d70fda..a2f519c 100644 --- a/src/libraries/System.Data.Common/ref/System.Data.Common.cs +++ b/src/libraries/System.Data.Common/ref/System.Data.Common.cs @@ -2079,8 +2079,8 @@ namespace System.Data.Common public System.Data.Common.DbCommand? UpdateCommand { get { throw null; } set { } } protected virtual int AddToBatch(System.Data.IDbCommand command) { throw null; } protected virtual void ClearBatch() { } - protected virtual System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } - protected virtual System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } + protected virtual System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } + protected virtual System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } protected override void Dispose(bool disposing) { } protected virtual int ExecuteBatch() { throw null; } public override int Fill(System.Data.DataSet dataSet) { throw null; } @@ -2462,8 +2462,8 @@ namespace System.Data.Common } public partial class RowUpdatedEventArgs : System.EventArgs { - public RowUpdatedEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { } - public System.Data.IDbCommand Command { get { throw null; } } + public RowUpdatedEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { } + public System.Data.IDbCommand? Command { get { throw null; } } public System.Exception? Errors { get { throw null; } set { } } public int RecordsAffected { get { throw null; } } public System.Data.DataRow Row { get { throw null; } } @@ -2476,7 +2476,7 @@ namespace System.Data.Common } public partial class RowUpdatingEventArgs : System.EventArgs { - public RowUpdatingEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { } + public RowUpdatingEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { } protected virtual System.Data.IDbCommand? BaseCommand { get { throw null; } set { } } public System.Data.IDbCommand? Command { get { throw null; } set { } } public System.Exception? Errors { get { throw null; } set { } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs index 72a5d8d..3fe1c1a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs @@ -169,15 +169,15 @@ namespace System.Data.Common { for (int i = 0; i < _baseParameterNames.Length; i++) { - if (_baseParameterNames[i] is { } baseParameterName) + if (_baseParameterNames[i] is string baseParameterName) { _baseParameterNames[i] = _dbCommandBuilder.GetParameterName(baseParameterName); } - if (_originalParameterNames[i] is { } originalParameterName) + if (_originalParameterNames[i] is string originalParameterName) { _originalParameterNames[i] = _dbCommandBuilder.GetParameterName(originalParameterName); } - if (_nullParameterNames[i] is { } nullParameterName) + if (_nullParameterNames[i] is string nullParameterName) { _nullParameterNames[i] = _dbCommandBuilder.GetParameterName(nullParameterName); } @@ -228,7 +228,7 @@ namespace System.Data.Common _baseParameterNames[i] = GetNextGenericParameterName(); _originalParameterNames[i] = GetNextGenericParameterName(); // don't bother generating an 'IsNull' name if it's not used - if (schemaRows[i] is { } schemaRow && schemaRow.AllowDBNull) + if (schemaRows[i] is DbSchemaRow schemaRow && schemaRow.AllowDBNull) { _nullParameterNames[i] = GetNextGenericParameterName(); } @@ -633,7 +633,7 @@ namespace System.Data.Common string[] srcColumnNames = new string[schemaRows.Length]; for (int i = 0; i < schemaRows.Length; ++i) { - if (schemaRows[i] is { } schemaRow) + if (schemaRows[i] is DbSchemaRow schemaRow) { srcColumnNames[i] = schemaRow.ColumnName; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs index e86beec..b1e417e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs @@ -254,12 +254,12 @@ namespace System.Data.Common return (IDbCommand?)((command is ICloneable) ? ((ICloneable)command).Clone() : null); } - protected virtual RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + protected virtual RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { return new RowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } - protected virtual RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + protected virtual RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { return new RowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } @@ -1035,7 +1035,7 @@ namespace System.Data.Common // TODO: the event may be raised with a null command, but only if the update, but only if // the update attempt fails (because no command was configured). We should not emit the // event in this case. - RowUpdatingEventArgs? rowUpdatingEvent = CreateRowUpdatingEvent(dataRow, dataCommand!, statementType, tableMapping); + RowUpdatingEventArgs? rowUpdatingEvent = CreateRowUpdatingEvent(dataRow, dataCommand, statementType, tableMapping); // this try/catch for any exceptions during the parameter initialization try @@ -1159,7 +1159,7 @@ namespace System.Data.Common if (null != errors) { // TODO: See above comment on dataCommand being null - rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand!, StatementType.Batch, tableMapping); + rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand, StatementType.Batch, tableMapping); rowUpdatedEvent.Errors = errors; rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; @@ -1182,7 +1182,7 @@ namespace System.Data.Common } // TODO: See above comment on dataCommand being null - rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand!, statementType, tableMapping); + rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand, statementType, tableMapping); // this try/catch for any exceptions during the execution, population, output parameters try @@ -1280,8 +1280,8 @@ namespace System.Data.Common if (1 != maxBatchCommands && 0 < commandCount) { // TODO: See above comment on dataCommand being null - // TODO: DataRow is null because we call AdapterInit below, which populars rows - RowUpdatedEventArgs rowUpdatedEvent = CreateRowUpdatedEvent(null!, dataCommand!, statementType, tableMapping); + // TODO: DataRow is null because we call AdapterInit below, which populates rows + RowUpdatedEventArgs rowUpdatedEvent = CreateRowUpdatedEvent(null!, dataCommand, statementType, tableMapping); try { @@ -1659,7 +1659,7 @@ namespace System.Data.Common DataRow row = batchCommands[i]._row; Debug.Assert(null != row, "null dataRow?"); - if (batchCommands[i]._errors is { } commandErrors) + if (batchCommands[i]._errors is Exception commandErrors) { // will exist if 0 == RecordsAffected string rowMsg = commandErrors.Message; if (string.IsNullOrEmpty(rowMsg)) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs index a2ef4bf..261a68a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs @@ -9,7 +9,7 @@ namespace System.Data.Common public class RowUpdatedEventArgs : EventArgs { - private readonly IDbCommand _command; + private readonly IDbCommand? _command; private StatementType _statementType; private readonly DataTableMapping _tableMapping; private Exception? _errors; @@ -20,7 +20,7 @@ namespace System.Data.Common private UpdateStatus _status; // UpdateStatus.Continue; /*0*/ private int _recordsAffected; - public RowUpdatedEventArgs(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + public RowUpdatedEventArgs(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { switch (statementType) { @@ -39,7 +39,7 @@ namespace System.Data.Common _tableMapping = tableMapping; } - public IDbCommand Command + public IDbCommand? Command { get { diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs index 806bab3..aabcde9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -87,7 +87,7 @@ namespace System.Data } // It is an error if we find an equivalent constraint already in collection - if (FindConstraint(constraint) is { } matchedConstraint) + if (FindConstraint(constraint) is Constraint matchedConstraint) { throw ExceptionBuilder.DuplicateConstraint(matchedConstraint.ConstraintName); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs index 084cbd2..1a1c4d7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs @@ -450,7 +450,7 @@ namespace System.Data for (int i = 0; i < value.Length; ++i) { // Empty means don't change the row. - if (value[i] is { } item) + if (value[i] is object item) { // may throw exception if user removes column from table during event DataColumn column = _columns[i]; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 851ac89..ff8af67 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -2431,8 +2431,8 @@ namespace System.Data { if (foreign.Table == foreign.RelatedTable) { - if (foreign.Clone(clone) is { } clonedConstraint && - clone.Constraints.FindConstraint(clonedConstraint) is { } oldConstraint) + if (foreign.Clone(clone) is ForeignKeyConstraint clonedConstraint && + clone.Constraints.FindConstraint(clonedConstraint) is Constraint oldConstraint) { oldConstraint.ConstraintName = Constraints[j].ConstraintName; } @@ -2440,8 +2440,8 @@ namespace System.Data } else if (unique != null) { - if (unique.Clone(clone) is { } clonedConstraint && - clone.Constraints.FindConstraint(clonedConstraint) is { } oldConstraint) + if (unique.Clone(clone) is UniqueConstraint clonedConstraint && + clone.Constraints.FindConstraint(clonedConstraint) is Constraint oldConstraint) { oldConstraint.ConstraintName = Constraints[j].ConstraintName; foreach (object key in clonedConstraint.ExtendedProperties.Keys) @@ -2462,7 +2462,7 @@ namespace System.Data if (foreign != null) { if (foreign.Table == foreign.RelatedTable && - foreign.Clone(clone) is { } newforeign) + foreign.Clone(clone) is ForeignKeyConstraint newforeign) { // we cant make sure that we recieve a cloned FKC,since it depends if table and relatedtable be the same clone.Constraints.Add(newforeign); @@ -3375,7 +3375,7 @@ namespace System.Data { for (int i = 0; i < value.Length; i++) { - if (value[i] is { } v) + if (value[i] is object v) { _columnCollection[i][record] = v; } diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs index 1fedea0..8499089 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs @@ -217,7 +217,7 @@ namespace System.Data.ProviderBase for (int i = 0; i < mapped.Length; ++i) { - if (mapped[i] is { } m) + if (mapped[i] is object m) { dataRow[i] = m; } diff --git a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs index daa5cc1..dfffcc6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs @@ -168,7 +168,7 @@ namespace System.Data _freeRecordList.Capacity = _freeRecordList.Count + _table.Rows.Count; for (int record = 0; record < _recordCapacity; ++record) { - if (_rows[record] is { } row && row.rowID != -1) + if (_rows[record] is DataRow row && row.rowID != -1) { int tempRecord = record; FreeRecord(ref tempRecord); diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 8dbd298..97fbb80 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -491,7 +491,7 @@ namespace System.Data { if (!_candidateColumns[i].flag) { - if (_candidateColumns[i].expr is { } expr) + if (_candidateColumns[i].expr is BinaryNode expr) { _linearExpression = (_linearExpression == null ? _candidateColumns[i].expr : new BinaryNode(_table, Operators.And, expr, _linearExpression)); } diff --git a/src/libraries/System.Data.DataSetExtensions/ref/System.Data.DataSetExtensions.csproj b/src/libraries/System.Data.DataSetExtensions/ref/System.Data.DataSetExtensions.csproj index 08914f6..d1d4624 100644 --- a/src/libraries/System.Data.DataSetExtensions/ref/System.Data.DataSetExtensions.csproj +++ b/src/libraries/System.Data.DataSetExtensions/ref/System.Data.DataSetExtensions.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Data.DataSetExtensions/src/System.Data.DataSetExtensions.csproj b/src/libraries/System.Data.DataSetExtensions/src/System.Data.DataSetExtensions.csproj index e777c148..3dd6d9f 100644 --- a/src/libraries/System.Data.DataSetExtensions/src/System.Data.DataSetExtensions.csproj +++ b/src/libraries/System.Data.DataSetExtensions/src/System.Data.DataSetExtensions.csproj @@ -2,6 +2,7 @@ $(NetCoreAppCurrent) true + enable diff --git a/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs b/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs index d755e6d..934b48c 100644 --- a/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs +++ b/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs @@ -9,17 +9,18 @@ namespace System.Data.Odbc public sealed partial class OdbcCommand : System.Data.Common.DbCommand, System.ICloneable { public OdbcCommand() { } - public OdbcCommand(string cmdText) { } - public OdbcCommand(string cmdText, System.Data.Odbc.OdbcConnection connection) { } - public OdbcCommand(string cmdText, System.Data.Odbc.OdbcConnection connection, System.Data.Odbc.OdbcTransaction transaction) { } + public OdbcCommand(string? cmdText) { } + public OdbcCommand(string? cmdText, System.Data.Odbc.OdbcConnection? connection) { } + public OdbcCommand(string? cmdText, System.Data.Odbc.OdbcConnection? connection, System.Data.Odbc.OdbcTransaction? transaction) { } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string CommandText { get { throw null; } set { } } public override int CommandTimeout { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.CommandType.Text)] public override System.Data.CommandType CommandType { get { throw null; } set { } } - public new System.Data.Odbc.OdbcConnection Connection { get { throw null; } set { } } - protected override System.Data.Common.DbConnection DbConnection { get { throw null; } set { } } + public new System.Data.Odbc.OdbcConnection? Connection { get { throw null; } set { } } + protected override System.Data.Common.DbConnection? DbConnection { get { throw null; } set { } } protected override System.Data.Common.DbParameterCollection DbParameterCollection { get { throw null; } } - protected override System.Data.Common.DbTransaction DbTransaction { get { throw null; } set { } } + protected override System.Data.Common.DbTransaction? DbTransaction { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(true)] [System.ComponentModel.DesignOnlyAttribute(true)] @@ -29,7 +30,7 @@ namespace System.Data.Odbc public new System.Data.Odbc.OdbcParameterCollection Parameters { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public new System.Data.Odbc.OdbcTransaction Transaction { get { throw null; } set { } } + public new System.Data.Odbc.OdbcTransaction? Transaction { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.UpdateRowSource.Both)] public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } } public override void Cancel() { } @@ -40,7 +41,7 @@ namespace System.Data.Odbc public override int ExecuteNonQuery() { throw null; } public new System.Data.Odbc.OdbcDataReader ExecuteReader() { throw null; } public new System.Data.Odbc.OdbcDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; } - public override object ExecuteScalar() { throw null; } + public override object? ExecuteScalar() { throw null; } public override void Prepare() { } public void ResetCommandTimeout() { } object System.ICloneable.Clone() { throw null; } @@ -48,8 +49,8 @@ namespace System.Data.Odbc public sealed partial class OdbcCommandBuilder : System.Data.Common.DbCommandBuilder { public OdbcCommandBuilder() { } - public OdbcCommandBuilder(System.Data.Odbc.OdbcDataAdapter adapter) { } - public new System.Data.Odbc.OdbcDataAdapter DataAdapter { get { throw null; } set { } } + public OdbcCommandBuilder(System.Data.Odbc.OdbcDataAdapter? adapter) { } + public new System.Data.Odbc.OdbcDataAdapter? DataAdapter { get { throw null; } set { } } protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { } public static void DeriveParameters(System.Data.Odbc.OdbcCommand command) { } public new System.Data.Odbc.OdbcCommand GetDeleteCommand() { throw null; } @@ -70,8 +71,8 @@ namespace System.Data.Odbc public sealed partial class OdbcConnection : System.Data.Common.DbConnection, System.ICloneable { public OdbcConnection() { } - public OdbcConnection(string connectionString) { } - public override string ConnectionString { get { throw null; } set { } } + public OdbcConnection(string? connectionString) { } + public override string? ConnectionString { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(15)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public new int ConnectionTimeout { get { throw null; } set { } } @@ -89,7 +90,7 @@ namespace System.Data.Odbc [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override System.Data.ConnectionState State { get { throw null; } } - public event System.Data.Odbc.OdbcInfoMessageEventHandler InfoMessage { add { } remove { } } + public event System.Data.Odbc.OdbcInfoMessageEventHandler? InfoMessage { add { } remove { } } protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; } public new System.Data.Odbc.OdbcTransaction BeginTransaction() { throw null; } public new System.Data.Odbc.OdbcTransaction BeginTransaction(System.Data.IsolationLevel isolevel) { throw null; } @@ -100,7 +101,7 @@ namespace System.Data.Odbc protected override void Dispose(bool disposing) { } public override System.Data.DataTable GetSchema() { throw null; } public override System.Data.DataTable GetSchema(string collectionName) { throw null; } - public override System.Data.DataTable GetSchema(string collectionName, string[] restrictionValues) { throw null; } + public override System.Data.DataTable GetSchema(string collectionName, string?[]? restrictionValues) { throw null; } public override void Open() { } public static void ReleaseObjectPool() { } object System.ICloneable.Clone() { throw null; } @@ -108,36 +109,37 @@ namespace System.Data.Odbc public sealed partial class OdbcConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder { public OdbcConnectionStringBuilder() { } - public OdbcConnectionStringBuilder(string connectionString) { } + public OdbcConnectionStringBuilder(string? connectionString) { } [System.ComponentModel.DisplayNameAttribute("Driver")] public string Driver { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Dsn")] public string Dsn { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override object this[string keyword] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } public override void Clear() { } public override bool ContainsKey(string keyword) { throw null; } public override bool Remove(string keyword) { throw null; } - public override bool TryGetValue(string keyword, out object value) { throw null; } + public override bool TryGetValue(string keyword, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out object? value) { throw null; } } public sealed partial class OdbcDataAdapter : System.Data.Common.DbDataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable { public OdbcDataAdapter() { } - public OdbcDataAdapter(System.Data.Odbc.OdbcCommand selectCommand) { } - public OdbcDataAdapter(string selectCommandText, System.Data.Odbc.OdbcConnection selectConnection) { } - public OdbcDataAdapter(string selectCommandText, string selectConnectionString) { } - public new System.Data.Odbc.OdbcCommand DeleteCommand { get { throw null; } set { } } - public new System.Data.Odbc.OdbcCommand InsertCommand { get { throw null; } set { } } - public new System.Data.Odbc.OdbcCommand SelectCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } - public new System.Data.Odbc.OdbcCommand UpdateCommand { get { throw null; } set { } } - public event System.Data.Odbc.OdbcRowUpdatedEventHandler RowUpdated { add { } remove { } } - public event System.Data.Odbc.OdbcRowUpdatingEventHandler RowUpdating { add { } remove { } } - protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } - protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } + public OdbcDataAdapter(System.Data.Odbc.OdbcCommand? selectCommand) { } + public OdbcDataAdapter(string? selectCommandText, System.Data.Odbc.OdbcConnection? selectConnection) { } + public OdbcDataAdapter(string? selectCommandText, string? selectConnectionString) { } + public new System.Data.Odbc.OdbcCommand? DeleteCommand { get { throw null; } set { } } + public new System.Data.Odbc.OdbcCommand? InsertCommand { get { throw null; } set { } } + public new System.Data.Odbc.OdbcCommand? SelectCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } + public new System.Data.Odbc.OdbcCommand? UpdateCommand { get { throw null; } set { } } + public event System.Data.Odbc.OdbcRowUpdatedEventHandler? RowUpdated { add { } remove { } } + public event System.Data.Odbc.OdbcRowUpdatingEventHandler? RowUpdating { add { } remove { } } + protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } + protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value) { } protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value) { } object System.ICloneable.Clone() { throw null; } @@ -156,9 +158,9 @@ namespace System.Data.Odbc protected override void Dispose(bool disposing) { } public override bool GetBoolean(int i) { throw null; } public override byte GetByte(int i) { throw null; } - public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; } + public override long GetBytes(int i, long dataIndex, byte[]? buffer, int bufferIndex, int length) { throw null; } public override char GetChar(int i) { throw null; } - public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; } + public override long GetChars(int i, long dataIndex, char[]? buffer, int bufferIndex, int length) { throw null; } public override string GetDataTypeName(int i) { throw null; } public System.DateTime GetDate(int i) { throw null; } public override System.DateTime GetDateTime(int i) { throw null; } @@ -247,28 +249,30 @@ namespace System.Data.Odbc public sealed partial class OdbcParameter : System.Data.Common.DbParameter, System.Data.IDataParameter, System.Data.IDbDataParameter, System.ICloneable { public OdbcParameter() { } - public OdbcParameter(string name, System.Data.Odbc.OdbcType type) { } - public OdbcParameter(string name, System.Data.Odbc.OdbcType type, int size) { } + public OdbcParameter(string? name, System.Data.Odbc.OdbcType type) { } + public OdbcParameter(string? name, System.Data.Odbc.OdbcType type, int size) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public OdbcParameter(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, bool isNullable, byte precision, byte scale, string srcColumn, System.Data.DataRowVersion srcVersion, object value) { } + public OdbcParameter(string? parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, bool isNullable, byte precision, byte scale, string srcColumn, System.Data.DataRowVersion srcVersion, object? value) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public OdbcParameter(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value) { } - public OdbcParameter(string name, System.Data.Odbc.OdbcType type, int size, string sourcecolumn) { } - public OdbcParameter(string name, object value) { } + public OdbcParameter(string? parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, byte precision, byte scale, string? sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object? value) { } + public OdbcParameter(string? name, System.Data.Odbc.OdbcType type, int size, string? sourcecolumn) { } + public OdbcParameter(string? name, object? value) { } public override System.Data.DbType DbType { get { throw null; } set { } } public override System.Data.ParameterDirection Direction { get { throw null; } set { } } public override bool IsNullable { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.Odbc.OdbcType.NChar)] [System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)] public System.Data.Odbc.OdbcType OdbcType { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string ParameterName { get { throw null; } set { } } public new byte Precision { get { throw null; } set { } } public new byte Scale { get { throw null; } set { } } public override int Size { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string SourceColumn { get { throw null; } set { } } public override bool SourceColumnNullMapping { get { throw null; } set { } } public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } } - public override object Value { get { throw null; } set { } } + public override object? Value { get { throw null; } set { } } public override void ResetDbType() { } public void ResetOdbcType() { } object System.ICloneable.Clone() { throw null; } @@ -290,15 +294,15 @@ namespace System.Data.Odbc public override object SyncRoot { get { throw null; } } public System.Data.Odbc.OdbcParameter Add(System.Data.Odbc.OdbcParameter value) { throw null; } public override int Add(object value) { throw null; } - public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType) { throw null; } - public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType, int size) { throw null; } - public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, string sourceColumn) { throw null; } + public System.Data.Odbc.OdbcParameter Add(string? parameterName, System.Data.Odbc.OdbcType odbcType) { throw null; } + public System.Data.Odbc.OdbcParameter Add(string? parameterName, System.Data.Odbc.OdbcType odbcType, int size) { throw null; } + public System.Data.Odbc.OdbcParameter Add(string? parameterName, System.Data.Odbc.OdbcType odbcType, int size, string? sourceColumn) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). https://go.microsoft.com/fwlink/?linkid=14202", false)] - public System.Data.Odbc.OdbcParameter Add(string parameterName, object value) { throw null; } + public System.Data.Odbc.OdbcParameter Add(string? parameterName, object? value) { throw null; } public override void AddRange(System.Array values) { } public void AddRange(System.Data.Odbc.OdbcParameter[] values) { } - public System.Data.Odbc.OdbcParameter AddWithValue(string parameterName, object value) { throw null; } + public System.Data.Odbc.OdbcParameter AddWithValue(string? parameterName, object? value) { throw null; } public override void Clear() { } public bool Contains(System.Data.Odbc.OdbcParameter value) { throw null; } public override bool Contains(object value) { throw null; } @@ -322,22 +326,22 @@ namespace System.Data.Odbc } public sealed partial class OdbcRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs { - public OdbcRowUpdatedEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } - public new System.Data.Odbc.OdbcCommand Command { get { throw null; } } + public OdbcRowUpdatedEventArgs(System.Data.DataRow row, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } + public new System.Data.Odbc.OdbcCommand? Command { get { throw null; } } } public delegate void OdbcRowUpdatedEventHandler(object sender, System.Data.Odbc.OdbcRowUpdatedEventArgs e); public sealed partial class OdbcRowUpdatingEventArgs : System.Data.Common.RowUpdatingEventArgs { - public OdbcRowUpdatingEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } - protected override System.Data.IDbCommand BaseCommand { get { throw null; } set { } } - public new System.Data.Odbc.OdbcCommand Command { get { throw null; } set { } } + public OdbcRowUpdatingEventArgs(System.Data.DataRow row, System.Data.IDbCommand? command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } + protected override System.Data.IDbCommand? BaseCommand { get { throw null; } set { } } + public new System.Data.Odbc.OdbcCommand? Command { get { throw null; } set { } } } public delegate void OdbcRowUpdatingEventHandler(object sender, System.Data.Odbc.OdbcRowUpdatingEventArgs e); public sealed partial class OdbcTransaction : System.Data.Common.DbTransaction { internal OdbcTransaction() { } - public new System.Data.Odbc.OdbcConnection Connection { get { throw null; } } - protected override System.Data.Common.DbConnection DbConnection { get { throw null; } } + public new System.Data.Odbc.OdbcConnection? Connection { get { throw null; } } + protected override System.Data.Common.DbConnection? DbConnection { get { throw null; } } public override System.Data.IsolationLevel IsolationLevel { get { throw null; } } public override void Commit() { } protected override void Dispose(bool disposing) { } diff --git a/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.csproj b/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.csproj index dec34df..a36f4ed 100644 --- a/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.csproj +++ b/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.csproj @@ -1,6 +1,7 @@ netstandard2.0;net461 + enable @@ -9,4 +10,4 @@ - \ No newline at end of file + diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs index de29572..60eda24 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs @@ -18,7 +18,7 @@ namespace System return value; } - internal static string GetString(string format, params object[] args) + internal static string GetString(string format, params object?[] args) { return SR.Format(format, args); } @@ -59,7 +59,7 @@ namespace System.Data.Common TraceExceptionAsReturnValue(e); return e; } - internal static InvalidOperationException InvalidOperation(string error, Exception inner) + internal static InvalidOperationException InvalidOperation(string error, Exception? inner) { InvalidOperationException e = new InvalidOperationException(error, inner); TraceExceptionAsReturnValue(e); @@ -193,7 +193,7 @@ namespace System.Data.Common { return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidDataDirectory)); } - internal static ArgumentException InvalidKeyname(string parameterName) + internal static ArgumentException InvalidKeyname(string? parameterName) { return Argument(SR.GetString(SR.ADP_InvalidKey), parameterName); } @@ -272,7 +272,7 @@ namespace System.Data.Common return OpenReaderExists(null); } - internal static Exception OpenReaderExists(Exception e) + internal static Exception OpenReaderExists(Exception? e) { return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e); } @@ -313,7 +313,7 @@ namespace System.Data.Common // // : ConnectionUtil // - internal static Exception ConnectionIsDisabled(Exception InnerException) + internal static Exception ConnectionIsDisabled(Exception? InnerException) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionIsDisabled), InnerException); } @@ -367,7 +367,7 @@ namespace System.Data.Common } internal static ArgumentException UnknownDataType(Type dataType) { - return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName)); + return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName!)); } internal static ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype) { @@ -375,7 +375,7 @@ namespace System.Data.Common } internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) { - return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); + return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName!)); } internal static ArgumentException InvalidOffsetValue(int value) { @@ -477,7 +477,7 @@ namespace System.Data.Common return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows)); } - internal static ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue) + internal static ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string? restrictionValue) { return ADP.Argument(SR.GetString(SR.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue)); } @@ -572,7 +572,7 @@ namespace System.Data.Common internal static readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero internal static readonly int PtrSize = IntPtr.Size; - internal static Delegate FindBuilder(MulticastDelegate mcd) + internal static Delegate? FindBuilder(MulticastDelegate mcd) { // V1.2.3300 if (null != mcd) { @@ -651,7 +651,7 @@ namespace System.Data.Common return Path.GetFullPath(filename); } - internal static int StringLength(string inputString) + internal static int StringLength(string? inputString) { return ((null != inputString) ? inputString.Length : 0); } diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs index cf901dd..dba3fdb 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs @@ -26,17 +26,17 @@ namespace System.Data.Common private readonly string _encryptedUsersConnectionString; // hash of unique keys to values - private readonly Dictionary _parsetable; + private readonly Dictionary _parsetable; // a linked list of key/value and their length in _encryptedUsersConnectionString - private readonly NameValuePair _keychain; + private readonly NameValuePair? _keychain; // track the existance of "password" or "pwd" in the connection string // not used for anything anymore but must keep it set correct for V1.1 serialization private readonly bool _hasPassword; - private readonly string[] _restrictionValues; - private readonly string _restrictions; + private readonly string[]? _restrictionValues; + private readonly string? _restrictions; private readonly KeyRestrictionBehavior _behavior; @@ -44,7 +44,7 @@ namespace System.Data.Common #pragma warning disable CA1823 // this field is no longer used, hence the warning was disabled // however, it can not be removed or it will break serialization with V1.1 - private readonly string _encryptedActualConnectionString; + private readonly string? _encryptedActualConnectionString; #pragma warning restore CA1823 #pragma warning restore CS0169 @@ -56,13 +56,13 @@ namespace System.Data.Common } internal DBConnectionString(DbConnectionOptions connectionOptions) - : this(connectionOptions, (string)null, KeyRestrictionBehavior.AllowOnly, null, true) + : this(connectionOptions, null, KeyRestrictionBehavior.AllowOnly, null, true) { // used by DBDataPermission to convert from DbConnectionOptions to DBConnectionString // since backward compatability requires Everett level classes } - private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Dictionary synonyms, bool mustCloneDictionary) + private DBConnectionString(DbConnectionOptions connectionOptions, string? restrictions, KeyRestrictionBehavior behavior, Dictionary? synonyms, bool mustCloneDictionary) { // used by DBDataPermission Debug.Assert(null != connectionOptions, "null connectionOptions"); switch (behavior) @@ -89,7 +89,7 @@ namespace System.Data.Common { // clone the hashtable to replace user's password/pwd value with "*" // we only need to clone if coming from DbConnectionOptions and password exists - _parsetable = new Dictionary(_parsetable); + _parsetable = new Dictionary(_parsetable); } // different than Everett in that instead of removing password/pwd from @@ -117,7 +117,7 @@ namespace System.Data.Common } } - private DBConnectionString(DBConnectionString connectionString, string[] restrictionValues, KeyRestrictionBehavior behavior) + private DBConnectionString(DBConnectionString connectionString, string[]? restrictionValues, KeyRestrictionBehavior behavior) { // used by intersect for two equal connection strings with different restrictions _encryptedUsersConnectionString = connectionString._encryptedUsersConnectionString; @@ -147,7 +147,7 @@ namespace System.Data.Common get { return (null == _keychain); } } - internal NameValuePair KeyChain + internal NameValuePair? KeyChain { get { return _keychain; } } @@ -156,10 +156,10 @@ namespace System.Data.Common { get { - string restrictions = _restrictions; + string? restrictions = _restrictions; if (null == restrictions) { - string[] restrictionValues = _restrictionValues; + string[]? restrictionValues = _restrictionValues; if ((null != restrictionValues) && (0 < restrictionValues.Length)) { StringBuilder builder = new StringBuilder(); @@ -184,9 +184,9 @@ namespace System.Data.Common } } - internal string this[string keyword] + internal string? this[string keyword] { - get { return (string)_parsetable[keyword]; } + get { return _parsetable[keyword]; } } internal bool ContainsKey(string keyword) @@ -194,10 +194,10 @@ namespace System.Data.Common return _parsetable.ContainsKey(keyword); } - internal DBConnectionString Intersect(DBConnectionString entry) + internal DBConnectionString Intersect(DBConnectionString? entry) { KeyRestrictionBehavior behavior = _behavior; - string[] restrictionValues = null; + string[]? restrictionValues = null; if (null == entry) { @@ -294,7 +294,7 @@ namespace System.Data.Common } [Conditional("DEBUG")] - private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionString combinedSet) + private void ValidateCombinedSet(DBConnectionString? componentSet, DBConnectionString combinedSet) { Debug.Assert(combinedSet != null, "The combined connection string should not be null"); if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null)) @@ -362,7 +362,7 @@ namespace System.Data.Common case KeyRestrictionBehavior.AllowOnly: // every key must either be in the resticted connection string or in the allowed keywords // keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys - for (NameValuePair current = entry.KeyChain; null != current; current = current.Next) + for (NameValuePair? current = entry.KeyChain; null != current; current = current.Next) { if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name)) { @@ -390,9 +390,9 @@ namespace System.Data.Common return true; } - private static string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage) + private static string[]? NewRestrictionAllowOnly(string[] allowonly, string[] preventusage) { - List newlist = null; + List? newlist = null; for (int i = 0; i < allowonly.Length; ++i) { if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal)) @@ -404,7 +404,7 @@ namespace System.Data.Common newlist.Add(allowonly[i]); } } - string[] restrictionValues = null; + string[]? restrictionValues = null; if (null != newlist) { restrictionValues = newlist.ToArray(); @@ -413,9 +413,9 @@ namespace System.Data.Common return restrictionValues; } - private static string[] NewRestrictionIntersect(string[] a, string[] b) + private static string[]? NewRestrictionIntersect(string[] a, string[] b) { - List newlist = null; + List? newlist = null; for (int i = 0; i < a.Length; ++i) { if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal)) @@ -427,7 +427,7 @@ namespace System.Data.Common newlist.Add(a[i]); } } - string[] restrictionValues = null; + string[]? restrictionValues = null; if (newlist != null) { restrictionValues = newlist.ToArray(); @@ -462,7 +462,7 @@ namespace System.Data.Common return restrictionValues; } - private static string[] ParseRestrictions(string restrictions, Dictionary synonyms) + private static string[]? ParseRestrictions(string restrictions, Dictionary? synonyms) { List restrictionValues = new List(); StringBuilder buffer = new StringBuilder(restrictions.Length); @@ -473,7 +473,7 @@ namespace System.Data.Common { int startPosition = nextStartPosition; - string keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules + string? keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue); if (!string.IsNullOrEmpty(keyname)) { @@ -488,7 +488,7 @@ namespace System.Data.Common return RemoveDuplicates(restrictionValues.ToArray()); } - internal static string[] RemoveDuplicates(string[] restrictions) + internal static string[] RemoveDuplicates(string?[] restrictions) { int count = restrictions.Length; if (0 < count) @@ -497,14 +497,14 @@ namespace System.Data.Common for (int i = 1; i < restrictions.Length; ++i) { - string prev = restrictions[i - 1]; + string prev = restrictions[i - 1]!; if ((0 == prev.Length) || (prev == restrictions[i])) { restrictions[i - 1] = null; count--; } } - if (0 == restrictions[restrictions.Length - 1].Length) + if (0 == restrictions[restrictions.Length - 1]!.Length) { restrictions[restrictions.Length - 1] = null; count--; @@ -515,20 +515,20 @@ namespace System.Data.Common count = 0; for (int i = 0; i < restrictions.Length; ++i) { - if (null != restrictions[i]) + if (restrictions[i] is string restriction) { - tmp[count++] = restrictions[i]; + tmp[count++] = restriction; } } restrictions = tmp; } } Verify(restrictions); - return restrictions; + return restrictions!; } [ConditionalAttribute("DEBUG")] - private static void Verify(string[] restrictionValues) + private static void Verify(string?[]? restrictionValues) { if (null != restrictionValues) { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs index 7131fb2..893a3e2 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs @@ -41,10 +41,10 @@ namespace System.Data.Common // synonyms hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string - public DbConnectionOptions(string connectionString, Dictionary synonyms, bool useOdbcRules) + public DbConnectionOptions(string connectionString, Dictionary? synonyms, bool useOdbcRules) { _useOdbcRules = useOdbcRules; - _parsetable = new Dictionary(); + _parsetable = new Dictionary(); _usersConnectionString = ((null != connectionString) ? connectionString : ""); // first pass on parsing, initial syntax check @@ -79,16 +79,16 @@ namespace System.Data.Common { if (_parsetable.ContainsKey(KEY.Password)) { - return string.IsNullOrEmpty((string)_parsetable[KEY.Password]); + return string.IsNullOrEmpty(_parsetable[KEY.Password]); } else if (_parsetable.ContainsKey(SYNONYM.Pwd)) { - return string.IsNullOrEmpty((string)_parsetable[SYNONYM.Pwd]); // MDAC 83097 + return string.IsNullOrEmpty(_parsetable[SYNONYM.Pwd]); // MDAC 83097 } else { - return ((_parsetable.ContainsKey(KEY.User_ID) && !string.IsNullOrEmpty((string)_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !string.IsNullOrEmpty((string)_parsetable[SYNONYM.UID]))); + return ((_parsetable.ContainsKey(KEY.User_ID) && !string.IsNullOrEmpty(_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !string.IsNullOrEmpty(_parsetable[SYNONYM.UID]))); } } return false; @@ -100,7 +100,7 @@ namespace System.Data.Common get { return (null == _keyChain); } } - internal Dictionary Parsetable + internal Dictionary Parsetable { get { return _parsetable; } } @@ -110,12 +110,12 @@ namespace System.Data.Common get { return _parsetable.Keys; } } - public string this[string keyword] + public string? this[string keyword] { - get { return (string)_parsetable[keyword]; } + get { return _parsetable[keyword]; } } - internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules) + internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string? keyValue, bool useOdbcRules) { ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); @@ -193,7 +193,7 @@ namespace System.Data.Common // same as Boolean, but with SSPI thrown in as valid yes public bool ConvertValueToIntegratedSecurity() { - object value = _parsetable[KEY.Integrated_Security]; + object? value = _parsetable[KEY.Integrated_Security]; if (null == value) { return false; @@ -223,7 +223,7 @@ namespace System.Data.Common public int ConvertValueToInt32(string keyName, int defaultValue) { - object value = _parsetable[keyName]; + object? value = _parsetable[keyName]; if (null == value) { return defaultValue; @@ -249,7 +249,7 @@ namespace System.Data.Common public string ConvertValueToString(string keyName, string defaultValue) { - string value = (string)_parsetable[keyName]; + string? value = _parsetable[keyName]; return ((null != value) ? value : defaultValue); } @@ -262,16 +262,16 @@ namespace System.Data.Common // * this method queries "DataDirectory" value from the current AppDomain. // This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource". // * This method uses GetFullPath to validate that root path is valid, the result is not exposed out. - internal static string ExpandDataDirectory(string keyword, string value, ref string datadir) + internal static string? ExpandDataDirectory(string keyword, string? value, ref string? datadir) { - string fullPath = null; + string? fullPath = null; if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) { - string rootFolderPath = datadir; + string? rootFolderPath = datadir; if (null == rootFolderPath) { // find the replacement path - object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); + object? rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); rootFolderPath = (rootFolderObject as string); if ((null != rootFolderObject) && (null == rootFolderPath)) { @@ -320,16 +320,16 @@ namespace System.Data.Common return fullPath; } - internal string ExpandDataDirectories(ref string filename, ref int position) + internal string? ExpandDataDirectories(ref string? filename, ref int position) { - string value = null; + string? value = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - string datadir = null; + string? datadir = null; int copyPosition = 0; bool expanded = false; - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; null != current; current = current.Next) { value = current.Value; @@ -420,7 +420,7 @@ namespace System.Data.Common int copyPosition = 0; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; null != current; current = current.Next) { if ((current.Name == keyword) && (current.Value == this[keyword])) { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs index d133e16..7c7c324 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionStringCommon.cs @@ -155,7 +155,7 @@ namespace System.Data.Common internal static bool ConvertToBoolean(object value) { Debug.Assert(null != value, "ConvertToBoolean(null)"); - string svalue = (value as string); + string? svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) @@ -194,7 +194,7 @@ namespace System.Data.Common internal static bool ConvertToIntegratedSecurity(object value) { Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)"); - string svalue = (value as string); + string? svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs index c57ae93..004fcd7 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/NameValuePermission.cs @@ -11,23 +11,23 @@ namespace System.Data.Common // reused as both key and value nodes // key nodes link to value nodes // value nodes link to key nodes - private readonly string _value; + private readonly string? _value; // value node with (null != _restrictions) are allowed to match connection strings - private DBConnectionString _entry; + private DBConnectionString? _entry; - private NameValuePermission[] _tree; // with branches + private NameValuePermission[]? _tree; // with branches internal NameValuePermission() { // root node } - private NameValuePermission(string keyword) + private NameValuePermission(string? keyword) { _value = keyword; } - private NameValuePermission(string value, DBConnectionString entry) + private NameValuePermission(string? value, DBConnectionString? entry) { _value = value; _entry = entry; @@ -40,7 +40,7 @@ namespace System.Data.Common _tree = permit._tree; if (null != _tree) { - NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[]); + NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[])!; for (int i = 0; i < tree.Length; ++i) { if (null != tree[i]) @@ -52,9 +52,9 @@ namespace System.Data.Common } } - int IComparable.CompareTo(object a) + int IComparable.CompareTo(object? a) { - return StringComparer.Ordinal.Compare(_value, ((NameValuePermission)a)._value); + return StringComparer.Ordinal.Compare(_value, ((NameValuePermission?)a)?._value); } internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBConnectionString entry) @@ -63,9 +63,9 @@ namespace System.Data.Common if (null != entry.KeyChain) { - for (NameValuePair keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) + for (NameValuePair? keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) { - NameValuePermission kv; + NameValuePermission? kv; kv = kvtree.CheckKeyForValue(keychain.Name); if (null == kv) @@ -78,7 +78,7 @@ namespace System.Data.Common kv = kvtree.CheckKeyForValue(keychain.Value); if (null == kv) { - DBConnectionString insertValue = ((null != keychain.Next) ? null : entry); + DBConnectionString? insertValue = ((null != keychain.Next) ? null : entry); kv = new NameValuePermission(keychain.Value, insertValue); kvtree.Add(kv); // add directly into live tree if (null != insertValue) @@ -105,7 +105,7 @@ namespace System.Data.Common } else { // global restrictions, MDAC 84443 - DBConnectionString kentry = kvtree._entry; + DBConnectionString? kentry = kvtree._entry; if (null != kentry) { Debug.Assert(entries.Contains(kentry), "entries doesn't contain entry"); @@ -146,14 +146,14 @@ namespace System.Data.Common int count = _tree.Length; for (int i = 0; i < _tree.Length; ++i) { - NameValuePermission kvtree = target.CheckKeyForValue(_tree[i]._value); + NameValuePermission? kvtree = target.CheckKeyForValue(_tree[i]._value); if (null != kvtree) { // does target tree contain our value _tree[i].Intersect(entries, kvtree); } else { - _tree[i] = null; + _tree[i] = null!; // Temporary, removed below --count; } } @@ -179,12 +179,12 @@ namespace System.Data.Common private void Add(NameValuePermission permit) { - NameValuePermission[] tree = _tree; + NameValuePermission[]? tree = _tree; int length = ((null != tree) ? tree.Length : 0); NameValuePermission[] newtree = new NameValuePermission[1 + length]; for (int i = 0; i < newtree.Length - 1; ++i) { - newtree[i] = tree[i]; + newtree[i] = tree![i]; } newtree[length] = permit; Array.Sort(newtree); @@ -198,7 +198,7 @@ namespace System.Data.Common return false; } bool hasMatch = false; - NameValuePermission[] keytree = _tree; // _tree won't mutate but Add will replace it + NameValuePermission[]? keytree = _tree; // _tree won't mutate but Add will replace it if (null != keytree) { hasMatch = parsetable.IsEmpty; // MDAC 86773 @@ -210,16 +210,16 @@ namespace System.Data.Common NameValuePermission permitKey = keytree[i]; if (null != permitKey) { - string keyword = permitKey._value; + string keyword = permitKey._value!; #if DEBUG Debug.Assert(null == permitKey._entry, "key member has no restrictions"); #endif if (parsetable.ContainsKey(keyword)) { - string valueInQuestion = (string)parsetable[keyword]; + string? valueInQuestion = parsetable[keyword]; // keyword is restricted to certain values - NameValuePermission permitValue = permitKey.CheckKeyForValue(valueInQuestion); + NameValuePermission? permitValue = permitKey.CheckKeyForValue(valueInQuestion); if (null != permitValue) { //value does match - continue the chain down that branch @@ -248,7 +248,7 @@ namespace System.Data.Common // partial chain match, either leaf-node by shorter chain or fail mid-chain if (null == _restrictions) } - DBConnectionString entry = _entry; + DBConnectionString? entry = _entry; if (null != entry) { // also checking !hasMatch is tempting, but wrong @@ -261,9 +261,9 @@ namespace System.Data.Common return hasMatch; // mid-chain failure } - private NameValuePermission CheckKeyForValue(string keyInQuestion) + private NameValuePermission? CheckKeyForValue(string? keyInQuestion) { - NameValuePermission[] valuetree = _tree; // _tree won't mutate but Add will replace it + NameValuePermission[]? valuetree = _tree; // _tree won't mutate but Add will replace it if (null != valuetree) { for (int i = 0; i < valuetree.Length; ++i) diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs index 61b550a..e885ac9 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs @@ -60,7 +60,7 @@ namespace System.Data.ProviderBase Validate(offset, 2); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - string value = null; + string? value = null; bool mustRelease = false; try @@ -69,7 +69,7 @@ namespace System.Data.ProviderBase IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); value = Marshal.PtrToStringUni(ptr); - Validate(offset, (2 * (value.Length + 1))); + Validate(offset, (2 * (value!.Length + 1))); } finally { @@ -88,7 +88,7 @@ namespace System.Data.ProviderBase Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - string value = null; + string? value = null; bool mustRelease = false; try diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs index 9b05f5b..5e37564 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs @@ -10,12 +10,12 @@ namespace System.Data.ProviderBase { internal abstract partial class DbConnectionFactory { - internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) + internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource? retry, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection, out DbConnectionInternal? connection) { Debug.Assert(null != owningConnection, "null owningConnection?"); DbConnectionPoolGroup poolGroup; - DbConnectionPool connectionPool; + DbConnectionPool? connectionPool; connection = null; // Work around race condition with clearing the pool between GetConnectionPool obtaining pool @@ -32,7 +32,7 @@ namespace System.Data.ProviderBase do { - poolGroup = GetConnectionPoolGroup(owningConnection); + poolGroup = GetConnectionPoolGroup(owningConnection)!; // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); if (null == connectionPool) @@ -40,7 +40,7 @@ namespace System.Data.ProviderBase // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool // or have a disabled pool entry. - poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled + poolGroup = GetConnectionPoolGroup(owningConnection)!; // previous entry have been disabled if (retry != null) { @@ -76,6 +76,7 @@ namespace System.Data.ProviderBase // now that we have an antecedent task, schedule our work when it is completed. // If it is a new slot or a completed task, this continuation will start right away. + // TODO: newTask needs to be over non-nullable DbConnection (see below), there may be a bug here newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) => { var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); @@ -85,10 +86,10 @@ namespace System.Data.ProviderBase oldConnection.Dispose(); } return newConnection; - }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default); + }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default)!; // Place this new task in the slot so any future work will be queued behind it - s_pendingOpenNonPooled[idx] = newTask; + s_pendingOpenNonPooled[idx] = newTask!; } // Set up the timeout (if needed) @@ -108,7 +109,7 @@ namespace System.Data.ProviderBase } else if (task.IsFaulted) { - retry.TrySetException(task.Exception.InnerException); + retry.TrySetException(task.Exception!.InnerException!); } else { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs index 2ab7701..09d49bb 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionInternal.cs @@ -79,12 +79,12 @@ namespace System.Data.ProviderBase // Lock to prevent race condition with cancellation lock (this) { - object lockToken = ObtainAdditionalLocksForClose(); + object? lockToken = ObtainAdditionalLocksForClose(); try { PrepareForCloseConnection(); - DbConnectionPool connectionPool = Pool; + DbConnectionPool? connectionPool = Pool; // The singleton closed classes won't have owners and diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs index 835dcf2..ab2d89b 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs @@ -22,7 +22,7 @@ namespace System.Data.ProviderBase private sealed class PendingGetConnection { - public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions userOptions) + public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions? userOptions) { DueTime = dueTime; Owner = owner; @@ -31,7 +31,7 @@ namespace System.Data.ProviderBase public long DueTime { get; private set; } public DbConnection Owner { get; private set; } public TaskCompletionSource Completion { get; private set; } - public DbConnectionOptions UserOptions { get; private set; } + public DbConnectionOptions? UserOptions { get; private set; } } @@ -97,12 +97,12 @@ namespace System.Data.ProviderBase private static readonly Random s_random = new Random(5101977); // Value obtained from Dave Driver private readonly int _cleanupWait; - private readonly DbConnectionPoolIdentity _identity; + private readonly DbConnectionPoolIdentity? _identity; private readonly DbConnectionFactory _connectionFactory; private readonly DbConnectionPoolGroup _connectionPoolGroup; private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions; - private readonly DbConnectionPoolProviderInfo _connectionPoolProviderInfo; + private readonly DbConnectionPoolProviderInfo? _connectionPoolProviderInfo; private State _state; @@ -117,13 +117,13 @@ namespace System.Data.ProviderBase private int _waitCount; private readonly PoolWaitHandles _waitHandles; - private Exception _resError; + private Exception? _resError; private volatile bool _errorOccurred; private int _errorWait; - private Timer _errorTimer; + private Timer? _errorTimer; - private Timer _cleanupTimer; + private Timer? _cleanupTimer; private readonly List _objectList; @@ -135,7 +135,7 @@ namespace System.Data.ProviderBase DbConnectionFactory connectionFactory, DbConnectionPoolGroup connectionPoolGroup, DbConnectionPoolIdentity identity, - DbConnectionPoolProviderInfo connectionPoolProviderInfo) + DbConnectionPoolProviderInfo? connectionPoolProviderInfo) { Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); @@ -220,7 +220,7 @@ namespace System.Data.ProviderBase } } - internal DbConnectionPoolIdentity Identity + internal DbConnectionPoolIdentity? Identity { get { return _identity; } } @@ -251,7 +251,7 @@ namespace System.Data.ProviderBase get { return _connectionPoolGroupOptions; } } - internal DbConnectionPoolProviderInfo ProviderInfo + internal DbConnectionPoolProviderInfo? ProviderInfo { get { return _connectionPoolProviderInfo; } } @@ -266,7 +266,7 @@ namespace System.Data.ProviderBase get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); } } - private void CleanupCallback(object state) + private void CleanupCallback(object? state) { // Called when the cleanup-timer ticks over. @@ -294,7 +294,7 @@ namespace System.Data.ProviderBase if (_waitHandles.PoolSemaphore.WaitOne(0)) { // We obtained a objects from the semaphore. - DbConnectionInternal obj; + DbConnectionInternal? obj; if (_stackOld.TryPop(out obj)) { @@ -323,7 +323,7 @@ namespace System.Data.ProviderBase { while (true) { - DbConnectionInternal obj; + DbConnectionInternal? obj; if (!_stackNew.TryPop(out obj)) break; @@ -345,7 +345,7 @@ namespace System.Data.ProviderBase internal void Clear() { - DbConnectionInternal obj; + DbConnectionInternal? obj; // First, quickly doom everything. lock (_objectList) @@ -387,9 +387,9 @@ namespace System.Data.ProviderBase _cleanupWait, _cleanupWait); - private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) + private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection) { - DbConnectionInternal newObj = null; + DbConnectionInternal? newObj = null; try { @@ -571,13 +571,13 @@ namespace System.Data.ProviderBase obj.Dispose(); } - private void ErrorCallback(object state) + private void ErrorCallback(object? state) { _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); // the error state is cleaned, destroy the timer to avoid periodic invocation - Timer t = _errorTimer; + Timer? t = _errorTimer; _errorTimer = null; if (t != null) { @@ -588,14 +588,14 @@ namespace System.Data.ProviderBase // TODO: move this to src/Common and integrate with SqlClient // Note: Odbc connections are not passing through this code - private Exception TryCloneCachedException() + private Exception? TryCloneCachedException() { return _resError; } private void WaitForPendingOpen() { - PendingGetConnection next; + PendingGetConnection? next; do { @@ -631,9 +631,9 @@ namespace System.Data.ProviderBase delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0); } - DbConnectionInternal connection = null; + DbConnectionInternal? connection = null; bool timeout = false; - Exception caughtException = null; + Exception? caughtException = null; try { @@ -675,7 +675,7 @@ namespace System.Data.ProviderBase } while (!_pendingOpens.IsEmpty); } - internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource retry, DbConnectionOptions userOptions, out DbConnectionInternal connection) + internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource? retry, DbConnectionOptions? userOptions, out DbConnectionInternal? connection) { uint waitForMultipleObjectsTimeout = 0; bool allowCreate = false; @@ -728,9 +728,9 @@ namespace System.Data.ProviderBase return false; } - private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection) + private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions? userOptions, out DbConnectionInternal? connection) { - DbConnectionInternal obj = null; + DbConnectionInternal? obj = null; if (null == obj) { Interlocked.Increment(ref _waitCount); @@ -764,7 +764,7 @@ namespace System.Data.ProviderBase case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. Interlocked.Decrement(ref _waitCount); - throw TryCloneCachedException(); + throw TryCloneCachedException()!; case CREATION_HANDLE: @@ -892,9 +892,9 @@ namespace System.Data.ProviderBase /// Options used to create the new connection /// Inner connection that will be replaced /// A new inner connection that is attached to the - internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) + internal DbConnectionInternal? ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { - DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); + DbConnectionInternal? newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) { @@ -907,9 +907,9 @@ namespace System.Data.ProviderBase return newConnection; } - private DbConnectionInternal GetFromGeneralPool() + private DbConnectionInternal? GetFromGeneralPool() { - DbConnectionInternal obj = null; + DbConnectionInternal? obj = null; if (!_stackNew.TryPop(out obj)) { @@ -938,7 +938,7 @@ namespace System.Data.ProviderBase return (obj); } - private void PoolCreateRequest(object state) + private void PoolCreateRequest(object? state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained @@ -968,7 +968,7 @@ namespace System.Data.ProviderBase // since either Open will fail or we will open a object for this pool that does // not belong in this pool. The side effect of this is that if using integrated // security min pool size cannot be guaranteed. - if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent())) + if (UsingIntegrateSecurity && !_identity!.Equals(DbConnectionPoolIdentity.GetCurrent())) { return; } @@ -1147,7 +1147,7 @@ namespace System.Data.ProviderBase _state = State.ShuttingDown; // deactivate timer callbacks - Timer t = _cleanupTimer; + Timer? t = _cleanupTimer; _cleanupTimer = null; if (null != t) { @@ -1156,15 +1156,15 @@ namespace System.Data.ProviderBase } - private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null) + private DbConnectionInternal? UserCreateRequest(DbConnection owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection = null) { // called by user when they were not able to obtain a free object but // instead obtained creation mutex - DbConnectionInternal obj = null; + DbConnectionInternal? obj = null; if (ErrorOccurred) { - throw TryCloneCachedException(); + throw TryCloneCachedException()!; } else { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs index 9117202..44c2fd1 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs @@ -5,9 +5,9 @@ namespace System.Data.ProviderBase { internal class DbConnectionPoolGroupProviderInfo { - private DbConnectionPoolGroup _poolGroup; + private DbConnectionPoolGroup? _poolGroup; - internal DbConnectionPoolGroup PoolGroup + internal DbConnectionPoolGroup? PoolGroup { get { diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolIdentity.cs index 7e1e6f9..6211231 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolIdentity.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolIdentity.cs @@ -30,7 +30,7 @@ namespace System.Data.ProviderBase throw new PlatformNotSupportedException(); } - public override bool Equals(object value) + public override bool Equals(object? value) { bool result = ((this == NoIdentity) || (this == value)); if (!result && (null != value)) diff --git a/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj b/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj index 8efc6e4..b9c7252 100644 --- a/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj +++ b/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj @@ -4,6 +4,7 @@ $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-FreeBSD;$(NetCoreAppCurrent)-illumos;$(NetCoreAppCurrent)-Solaris;$(NetCoreAppCurrent)-Linux;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS;$(NetCoreAppCurrent);netcoreapp2.0-FreeBSD;netcoreapp2.0-Linux;netcoreapp2.0-OSX;netcoreapp2.0-Windows_NT;netstandard2.0;net461-Windows_NT true $(NoWarn);CA2249 + enable diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs index 65887bf..7b48878 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs @@ -9,9 +9,9 @@ namespace System.Data.Odbc { } - internal string _name; - internal string _typename; - internal Type _type; + internal string? _name; + internal string? _typename; + internal Type? _type; internal ODBC32.SQL_TYPE? _dbtype; } @@ -19,9 +19,9 @@ namespace System.Data.Odbc // Cache // // This is a on-demand cache, only caching what the user requests. - // The reational is that for ForwardOnly access (the default and LCD of drivers) + // The rationale is that for ForwardOnly access (the default and LCD of drivers) // we cannot obtain the data more than once, and even GetData(0) (to determine is-null) - // still obtains data for fixed lenght types. + // still obtains data for fixed length types. // So simple code like: // if (!rReader.IsDBNull(i)) @@ -39,8 +39,8 @@ namespace System.Data.Odbc //Data private readonly bool[] _isBadValue; - private DbSchemaInfo[] _schema; - private readonly object[] _values; + private DbSchemaInfo?[]? _schema; + private readonly object?[] _values; private readonly OdbcDataReader _record; internal int _count; internal bool _randomaccess = true; @@ -56,13 +56,13 @@ namespace System.Data.Odbc } //Accessor - internal object this[int i] + internal object? this[int i] { get { if (_isBadValue[i]) { - OverflowException innerException = (OverflowException)Values[i]; + OverflowException innerException = (OverflowException)Values[i]!; throw new OverflowException(innerException.Message, innerException); } return Values[i]; @@ -87,7 +87,7 @@ namespace System.Data.Odbc _isBadValue[i] = true; } - internal object[] Values + internal object?[] Values { get { @@ -95,7 +95,7 @@ namespace System.Data.Odbc } } - internal object AccessIndex(int i) + internal object? AccessIndex(int i) { //Note: We could put this directly in this[i], instead of having an explicit overload. //However that means that EVERY access into the cache takes the hit of checking, so @@ -106,7 +106,7 @@ namespace System.Data.Odbc // .... // return cache[i]; - object[] values = this.Values; + object?[] values = this.Values; if (_randomaccess) { //Random @@ -130,11 +130,8 @@ namespace System.Data.Odbc { _schema = new DbSchemaInfo[Count]; } - if (_schema[i] == null) - { - _schema[i] = new DbSchemaInfo(); - } - return _schema[i]; + + return _schema[i] ??= new DbSchemaInfo(); } internal void FlushValues() diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs index 1fed607..6c32692 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs @@ -116,7 +116,7 @@ namespace System.Data.Odbc { } - internal static short ShortStringLength(string inputString) + internal static short ShortStringLength(string? inputString) { return checked((short)ADP.StringLength(inputString)); } @@ -716,14 +716,14 @@ namespace System.Data.Odbc internal const short SQL_RESULT_COL = 3; // Helpers - internal static OdbcErrorCollection GetDiagErrors(string source, OdbcHandle hrHandle, RetCode retcode) + internal static OdbcErrorCollection GetDiagErrors(string? source, OdbcHandle hrHandle, RetCode retcode) { OdbcErrorCollection errors = new OdbcErrorCollection(); GetDiagErrors(errors, source, hrHandle, retcode); return errors; } - internal static void GetDiagErrors(OdbcErrorCollection errors, string source, OdbcHandle hrHandle, RetCode retcode) + internal static void GetDiagErrors(OdbcErrorCollection errors, string? source, OdbcHandle hrHandle, RetCode retcode) { Debug.Assert(retcode != ODBC32.RetCode.INVALID_HANDLE, "retcode must never be ODBC32.RetCode.INVALID_HANDLE"); if (RetCode.SUCCESS != retcode) diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs index be558f4..ad7b21c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs @@ -4,6 +4,7 @@ using System.ComponentModel; //Component using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; // todo: @@ -20,21 +21,21 @@ namespace System.Data.Odbc private static int s_objectTypeCount; // Bid counter internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); - private string _commandText; + private string? _commandText; private CommandType _commandType; private int _commandTimeout = ADP.DefaultCommandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; private bool _isPrepared; // true if the command is prepared - private OdbcConnection _connection; - private OdbcTransaction _transaction; + private OdbcConnection? _connection; + private OdbcTransaction? _transaction; - private WeakReference _weakDataReaderReference; + private WeakReference? _weakDataReaderReference; - private CMDWrapper _cmdWrapper; + private CMDWrapper? _cmdWrapper; - private OdbcParameterCollection _parameterCollection; // Parameter collection + private OdbcParameterCollection? _parameterCollection; // Parameter collection private ConnectionState _cmdState; @@ -43,20 +44,20 @@ namespace System.Data.Odbc GC.SuppressFinalize(this); } - public OdbcCommand(string cmdText) : this() + public OdbcCommand(string? cmdText) : this() { // note: arguments are assigned to properties so we do not have to trace them. // We still need to include them into the argument list of the definition! CommandText = cmdText; } - public OdbcCommand(string cmdText, OdbcConnection connection) : this() + public OdbcCommand(string? cmdText, OdbcConnection? connection) : this() { CommandText = cmdText; Connection = connection; } - public OdbcCommand(string cmdText, OdbcConnection connection, OdbcTransaction transaction) : this() + public OdbcCommand(string? cmdText, OdbcConnection? connection, OdbcTransaction? transaction) : this() { CommandText = cmdText; Connection = connection; @@ -83,7 +84,7 @@ namespace System.Data.Odbc { if (null != _weakDataReaderReference) { - IDisposable reader = (IDisposable)_weakDataReaderReference.Target; + IDisposable? reader = (IDisposable?)_weakDataReaderReference.Target; if ((null != reader) && _weakDataReaderReference.IsAlive) { ((IDisposable)reader).Dispose(); @@ -95,11 +96,11 @@ namespace System.Data.Odbc internal void DisconnectFromDataReaderAndConnection() { // get a reference to the datareader if it is alive - OdbcDataReader liveReader = null; + OdbcDataReader? liveReader = null; if (_weakDataReaderReference != null) { - OdbcDataReader reader; - reader = (OdbcDataReader)_weakDataReaderReference.Target; + OdbcDataReader? reader; + reader = (OdbcDataReader?)_weakDataReaderReference.Target; if (_weakDataReaderReference.IsAlive) { liveReader = reader; @@ -149,15 +150,16 @@ namespace System.Data.Odbc { get { - return _cmdWrapper.Canceling; + return _cmdWrapper!.Canceling; } } + [AllowNull] public override string CommandText { get { - string value = _commandText; + string? value = _commandText; return ((null != value) ? value : string.Empty); } set @@ -231,7 +233,7 @@ namespace System.Data.Odbc } } - public new OdbcConnection Connection + public new OdbcConnection? Connection { get { @@ -250,7 +252,7 @@ namespace System.Data.Odbc } } - protected override DbConnection DbConnection + protected override DbConnection? DbConnection { // V1.2.3300 get { @@ -258,7 +260,7 @@ namespace System.Data.Odbc } set { - Connection = (OdbcConnection)value; + Connection = (OdbcConnection?)value; } } @@ -270,7 +272,7 @@ namespace System.Data.Odbc } } - protected override DbTransaction DbTransaction + protected override DbTransaction? DbTransaction { // V1.2.3300 get { @@ -278,7 +280,7 @@ namespace System.Data.Odbc } set { - Transaction = (OdbcTransaction)value; + Transaction = (OdbcTransaction?)value; } } @@ -332,7 +334,7 @@ namespace System.Data.Odbc Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new OdbcTransaction Transaction + public new OdbcTransaction? Transaction { get { @@ -379,7 +381,7 @@ namespace System.Data.Odbc internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute) { - return _cmdWrapper.GetDescriptorHandle(attribute); + return _cmdWrapper!.GetDescriptorHandle(attribute); } @@ -398,7 +400,7 @@ namespace System.Data.Odbc // if (_cmdWrapper == null) { - _cmdWrapper = new CMDWrapper(_connection); + _cmdWrapper = new CMDWrapper(_connection!); Debug.Assert(null != _connection, "GetStatementHandle without connection?"); _connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag); @@ -431,11 +433,11 @@ namespace System.Data.Odbc public override void Cancel() { - CMDWrapper wrapper = _cmdWrapper; + CMDWrapper? wrapper = _cmdWrapper; if (null != wrapper) { wrapper.Canceling = true; - OdbcStatementHandle stmt = wrapper.StatementHandle; + OdbcStatementHandle? stmt = wrapper.StatementHandle; if (null != stmt) { lock (stmt) @@ -451,7 +453,7 @@ namespace System.Data.Odbc // don't fire info message events on cancel break; default: - throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode); + throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode)!; } } } @@ -488,7 +490,7 @@ namespace System.Data.Odbc private void CloseCommandWrapper() { - CMDWrapper wrapper = _cmdWrapper; + CMDWrapper? wrapper = _cmdWrapper; if (null != wrapper) { try @@ -560,7 +562,7 @@ namespace System.Data.Odbc return ExecuteReaderObject(behavior, ADP.ExecuteReader, true); } - internal OdbcDataReader ExecuteReaderFromSQLMethod(object[] methodArguments, + internal OdbcDataReader ExecuteReaderFromSQLMethod(object?[]? methodArguments, ODBC32.SQL_API method) { return ExecuteReaderObject(CommandBehavior.Default, method.ToString(), true, methodArguments, method); @@ -579,10 +581,10 @@ namespace System.Data.Odbc private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader, - object[] methodArguments, + object?[]? methodArguments, ODBC32.SQL_API odbcApiMethod) { // MDAC 68324 - OdbcDataReader localReader = null; + OdbcDataReader? localReader = null; try { DisposeDeadDataReader(); // this is a no-op if cmdState is not Fetching @@ -596,14 +598,14 @@ namespace System.Data.Odbc ODBC32.RetCode retcode; - OdbcStatementHandle stmt = GetStatementHandle().StatementHandle; - _cmdWrapper.Canceling = false; + OdbcStatementHandle stmt = GetStatementHandle().StatementHandle!; + _cmdWrapper!.Canceling = false; if (null != _weakDataReaderReference) { if (_weakDataReaderReference.IsAlive) { - object target = _weakDataReaderReference.Target; + object? target = _weakDataReaderReference.Target; if (null != target && _weakDataReaderReference.IsAlive) { if (!((OdbcDataReader)target).IsClosed) @@ -617,7 +619,7 @@ namespace System.Data.Odbc //Set command properties //Not all drivers support timeout. So fail silently if error - if (!Connection.ProviderInfo.NoQueryTimeout) + if (!Connection!.ProviderInfo.NoQueryTimeout) { TrySetStatementAttribute(stmt, ODBC32.SQL_ATTR.QUERY_TIMEOUT, @@ -668,12 +670,12 @@ namespace System.Data.Odbc if (ODBC32.RetCode.SUCCESS != retcode) { - _connection.HandleError(stmt, retcode); + _connection!.HandleError(stmt, retcode); } } bool mustRelease = false; - CNativeBuffer parameterBuffer = _cmdWrapper._nativeParameterBuffer; + CNativeBuffer? parameterBuffer = _cmdWrapper._nativeParameterBuffer; try { @@ -727,7 +729,7 @@ namespace System.Data.Odbc else { // any other returncode indicates an error - _connection.HandleError(stmt, retcode); + _connection!.HandleError(stmt, retcode); } } @@ -754,42 +756,42 @@ namespace System.Data.Odbc break; case ODBC32.SQL_API.SQLTABLES: - retcode = stmt.Tables((string)methodArguments[0], //TableCatalog - (string)methodArguments[1], //TableSchema, - (string)methodArguments[2], //TableName - (string)methodArguments[3]); //TableType + retcode = stmt.Tables((string)methodArguments![0]!, //TableCatalog + (string)methodArguments[1]!, //TableSchema, + (string)methodArguments[2]!, //TableName + (string)methodArguments[3]!); //TableType break; case ODBC32.SQL_API.SQLCOLUMNS: - retcode = stmt.Columns((string)methodArguments[0], //TableCatalog - (string)methodArguments[1], //TableSchema - (string)methodArguments[2], //TableName - (string)methodArguments[3]); //ColumnName + retcode = stmt.Columns((string)methodArguments![0]!, //TableCatalog + (string)methodArguments[1]!, //TableSchema + (string)methodArguments[2]!, //TableName + (string)methodArguments[3]!); //ColumnName break; case ODBC32.SQL_API.SQLPROCEDURES: - retcode = stmt.Procedures((string)methodArguments[0], //ProcedureCatalog - (string)methodArguments[1], //ProcedureSchema - (string)methodArguments[2]); //procedureName + retcode = stmt.Procedures((string)methodArguments![0]!, //ProcedureCatalog + (string)methodArguments[1]!, //ProcedureSchema + (string)methodArguments[2]!); //procedureName break; case ODBC32.SQL_API.SQLPROCEDURECOLUMNS: - retcode = stmt.ProcedureColumns((string)methodArguments[0], //ProcedureCatalog - (string)methodArguments[1], //ProcedureSchema - (string)methodArguments[2], //procedureName - (string)methodArguments[3]); //columnName + retcode = stmt.ProcedureColumns((string)methodArguments![0]!, //ProcedureCatalog + (string)methodArguments[1]!, //ProcedureSchema + (string)methodArguments[2]!, //procedureName + (string)methodArguments[3]!); //columnName break; case ODBC32.SQL_API.SQLSTATISTICS: - retcode = stmt.Statistics((string)methodArguments[0], //TableCatalog - (string)methodArguments[1], //TableSchema - (string)methodArguments[2], //TableName - (short)methodArguments[3], //IndexTrpe - (short)methodArguments[4]); //Accuracy + retcode = stmt.Statistics((string)methodArguments![0]!, //TableCatalog + (string)methodArguments[1]!, //TableSchema + (string)methodArguments[2]!, //TableName + (short)methodArguments[3]!, //IndexTrpe + (short)methodArguments[4]!); //Accuracy break; case ODBC32.SQL_API.SQLGETTYPEINFO: - retcode = stmt.GetTypeInfo((short)methodArguments[0]); //SQL Type + retcode = stmt.GetTypeInfo((short)methodArguments![0]!); //SQL Type break; default: @@ -801,7 +803,7 @@ namespace System.Data.Odbc //Note: Execute will return NO_DATA for Update/Delete non-row returning queries if ((ODBC32.RetCode.SUCCESS != retcode) && (ODBC32.RetCode.NO_DATA != retcode)) { - _connection.HandleError(stmt, retcode); + _connection!.HandleError(stmt, retcode); } } // end SchemaOnly } @@ -809,7 +811,7 @@ namespace System.Data.Odbc { if (mustRelease) { - parameterBuffer.DangerousRelease(); + parameterBuffer!.DangerousRelease(); } } @@ -843,12 +845,12 @@ namespace System.Data.Odbc } } } - return localReader; + return localReader!; } - public override object ExecuteScalar() + public override object? ExecuteScalar() { - object value = null; + object? value = null; using (IDataReader reader = ExecuteReaderObject(0, ADP.ExecuteScalar, false)) { if (reader.Read() && (0 < reader.FieldCount)) @@ -862,7 +864,7 @@ namespace System.Data.Odbc internal string GetDiagSqlState() { - return _cmdWrapper.GetDiagSqlState(); + return _cmdWrapper!.GetDiagSqlState(); } private void PropertyChanging() @@ -886,7 +888,7 @@ namespace System.Data.Odbc ValidateOpenConnection(ADP.Prepare); - if (0 != (ConnectionState.Fetching & _connection.InternalState)) + if (0 != (ConnectionState.Fetching & _connection!.InternalState)) { throw ADP.OpenReaderExists(); } @@ -899,7 +901,7 @@ namespace System.Data.Odbc DisposeDeadDataReader(); GetStatementHandle(); - OdbcStatementHandle stmt = _cmdWrapper.StatementHandle; + OdbcStatementHandle stmt = _cmdWrapper!.StatementHandle!; retcode = stmt.Prepare(CommandText); @@ -927,7 +929,7 @@ namespace System.Data.Odbc if ((sqlState == "HYC00") || (sqlState == "HY092")) { - Connection.FlagUnsupportedStmtAttr(stmtAttribute); + Connection!.FlagUnsupportedStmtAttr(stmtAttribute); } else { @@ -939,7 +941,7 @@ namespace System.Data.Odbc private void ValidateOpenConnection(string methodName) { // see if we have a connection - OdbcConnection connection = Connection; + OdbcConnection? connection = Connection; if (null == connection) { @@ -967,15 +969,15 @@ namespace System.Data.Odbc } internal sealed class CMDWrapper { - private OdbcStatementHandle _stmt; // hStmt - private OdbcStatementHandle _keyinfostmt; // hStmt for keyinfo + private OdbcStatementHandle? _stmt; // hStmt + private OdbcStatementHandle? _keyinfostmt; // hStmt for keyinfo - internal OdbcDescriptorHandle _hdesc; // hDesc + internal OdbcDescriptorHandle? _hdesc; // hDesc - internal CNativeBuffer _nativeParameterBuffer; // Native memory for internal memory management + internal CNativeBuffer? _nativeParameterBuffer; // Native memory for internal memory management // (Performance optimization) - internal CNativeBuffer _dataReaderBuf; // Reusable DataReader buffer + internal CNativeBuffer? _dataReaderBuf; // Reusable DataReader buffer private readonly OdbcConnection _connection; // Connection private bool _canceling; // true if the command is canceling @@ -1019,12 +1021,12 @@ namespace System.Data.Odbc } } - internal OdbcStatementHandle StatementHandle + internal OdbcStatementHandle? StatementHandle { get { return _stmt; } } - internal OdbcStatementHandle KeyInfoStatement + internal OdbcStatementHandle? KeyInfoStatement { get { @@ -1053,7 +1055,7 @@ namespace System.Data.Odbc } DisposeStatementHandle(); - CNativeBuffer buffer = _nativeParameterBuffer; + CNativeBuffer? buffer = _nativeParameterBuffer; _nativeParameterBuffer = null; if (null != buffer) { @@ -1065,7 +1067,7 @@ namespace System.Data.Odbc private void DisposeDescriptorHandle() { - OdbcDescriptorHandle handle = _hdesc; + OdbcDescriptorHandle? handle = _hdesc; if (null != handle) { _hdesc = null; @@ -1077,7 +1079,7 @@ namespace System.Data.Odbc DisposeKeyInfoStatementHandle(); DisposeDescriptorHandle(); - OdbcStatementHandle handle = _stmt; + OdbcStatementHandle? handle = _stmt; if (null != handle) { _stmt = null; @@ -1087,7 +1089,7 @@ namespace System.Data.Odbc internal void DisposeKeyInfoStatementHandle() { - OdbcStatementHandle handle = _keyinfostmt; + OdbcStatementHandle? handle = _keyinfostmt; if (null != handle) { _keyinfostmt = null; @@ -1099,7 +1101,7 @@ namespace System.Data.Odbc { DisposeDescriptorHandle(); - OdbcStatementHandle handle = _stmt; + OdbcStatementHandle? handle = _stmt; if (null != handle) { try @@ -1124,7 +1126,7 @@ namespace System.Data.Odbc internal void FreeKeyInfoStatementHandle(ODBC32.STMT stmt) { - OdbcStatementHandle handle = _keyinfostmt; + OdbcStatementHandle? handle = _keyinfostmt; if (null != handle) { try @@ -1149,10 +1151,10 @@ namespace System.Data.Odbc // internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute) { - OdbcDescriptorHandle hdesc = _hdesc; - if (null == _hdesc) + OdbcDescriptorHandle? hdesc = _hdesc; + if (null == hdesc) { - _hdesc = hdesc = new OdbcDescriptorHandle(_stmt, attribute); + _hdesc = hdesc = new OdbcDescriptorHandle(_stmt!, attribute); } return hdesc; } @@ -1160,7 +1162,7 @@ namespace System.Data.Odbc internal string GetDiagSqlState() { string sqlstate; - _stmt.GetDiagnosticField(out sqlstate); + _stmt!.GetDiagnosticField(out sqlstate); return sqlstate; } @@ -1170,10 +1172,10 @@ namespace System.Data.Odbc { case ODBC32.RetCode.SUCCESS: case ODBC32.RetCode.SUCCESS_WITH_INFO: - _connection.HandleErrorNoThrow(_stmt, retcode); + _connection.HandleErrorNoThrow(_stmt!, retcode); break; default: - throw _connection.HandleErrorNoThrow(_stmt, retcode); + throw _connection.HandleErrorNoThrow(_stmt!, retcode)!; } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs index a855418..55a1fd1 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs @@ -14,12 +14,12 @@ namespace System.Data.Odbc GC.SuppressFinalize(this); } - public OdbcCommandBuilder(OdbcDataAdapter adapter) : this() + public OdbcCommandBuilder(OdbcDataAdapter? adapter) : this() { DataAdapter = adapter; } - public new OdbcDataAdapter DataAdapter + public new OdbcDataAdapter? DataAdapter { get { @@ -123,7 +123,7 @@ namespace System.Data.Odbc throw ADP.CommandTextRequired(ADP.DeriveParameters); } - OdbcConnection connection = command.Connection; + OdbcConnection? connection = command.Connection; if (null == connection) { @@ -166,7 +166,7 @@ namespace System.Data.Odbc // following call ensures that the command has a statement handle allocated CMDWrapper cmdWrapper = command.GetStatementHandle(); - OdbcStatementHandle hstmt = cmdWrapper.StatementHandle; + OdbcStatementHandle hstmt = cmdWrapper.StatementHandle!; int cColsAffected; // maps an enforced 4-part qualified string as follows @@ -176,7 +176,7 @@ namespace System.Data.Odbc // parts[3] = ProcedureName // string quote = connection.QuoteChar(ADP.DeriveParameters); - string[] parts = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quote, quote, '.', 4, true, SR.ODBC_ODBCCommandText, false); + string?[] parts = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quote, quote, '.', 4, true, SR.ODBC_ODBCCommandText, false); if (null == parts[3]) { // match Everett behavior, if the commandtext is nothing but whitespace set the command text to the whitespace parts[3] = command.CommandText; @@ -251,7 +251,7 @@ namespace System.Data.Odbc return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } - public string QuoteIdentifier(string unquotedIdentifier, OdbcConnection connection) + public string QuoteIdentifier(string unquotedIdentifier, OdbcConnection? connection) { ADP.CheckArgumentNull(unquotedIdentifier, nameof(unquotedIdentifier)); @@ -306,11 +306,11 @@ namespace System.Data.Odbc return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } - public string UnquoteIdentifier(string quotedIdentifier, OdbcConnection connection) + public string UnquoteIdentifier(string quotedIdentifier, OdbcConnection? connection) { ADP.CheckArgumentNull(quotedIdentifier, nameof(quotedIdentifier)); - // if the user has specificed a prefix use the user specified prefix and suffix + // if the user has specified a prefix use the user specified prefix and suffix // otherwise get them from the provider string quotePrefix = QuotePrefix; string quoteSuffix = QuoteSuffix; @@ -330,7 +330,7 @@ namespace System.Data.Odbc quoteSuffix = quotePrefix; } - string unquotedIdentifier; + string? unquotedIdentifier; // by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned." // So if a blank is returned the string is returned unchanged. Otherwise the returned string is used // to unquote the string @@ -344,7 +344,7 @@ namespace System.Data.Odbc { unquotedIdentifier = quotedIdentifier; } - return unquotedIdentifier; + return unquotedIdentifier!; } } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs index 4b7ec8f..9841dd7 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs @@ -16,12 +16,12 @@ namespace System.Data.Odbc { private int _connectionTimeout = ADP.DefaultConnectionTimeout; - private OdbcInfoMessageEventHandler _infoMessageEventHandler; - private WeakReference _weakTransaction; + private OdbcInfoMessageEventHandler? _infoMessageEventHandler; + private WeakReference? _weakTransaction; - private OdbcConnectionHandle _connectionHandle; + private OdbcConnectionHandle? _connectionHandle; - public OdbcConnection(string connectionString) : this() + public OdbcConnection(string? connectionString) : this() { ConnectionString = connectionString; } @@ -32,7 +32,7 @@ namespace System.Data.Odbc _connectionTimeout = connection._connectionTimeout; } - internal OdbcConnectionHandle ConnectionHandle + internal OdbcConnectionHandle? ConnectionHandle { get { @@ -45,6 +45,7 @@ namespace System.Data.Odbc } } + [AllowNull] public override string ConnectionString { get @@ -110,7 +111,7 @@ namespace System.Data.Odbc // note: This will return an empty string if the driver keyword was used to connect // see ODBC3.0 Programmers Reference, SQLGetInfo // - return GetInfoStringUnhandled(ODBC32.SQL_INFO.SERVER_NAME, true); + return GetInfoStringUnhandled(ODBC32.SQL_INFO.SERVER_NAME, true)!; } return string.Empty; } @@ -145,7 +146,7 @@ namespace System.Data.Odbc get { Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); - return (OdbcConnectionPoolGroupProviderInfo)this.PoolGroup.ProviderInfo; + return (OdbcConnectionPoolGroupProviderInfo)this.PoolGroup.ProviderInfo!; } } @@ -165,14 +166,14 @@ namespace System.Data.Odbc } } - internal OdbcTransaction LocalTransaction + internal OdbcTransaction? LocalTransaction { get { - OdbcTransaction result = null; + OdbcTransaction? result = null; if (null != _weakTransaction) { - result = ((OdbcTransaction)_weakTransaction.Target); + result = ((OdbcTransaction?)_weakTransaction.Target); } return result; } @@ -200,7 +201,7 @@ namespace System.Data.Odbc { if (ProviderInfo.DriverName == null) { - ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); + ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME)!; } return ProviderInfo.DriverName; } @@ -237,7 +238,7 @@ namespace System.Data.Odbc } } - public event OdbcInfoMessageEventHandler InfoMessage + public event OdbcInfoMessageEventHandler? InfoMessage { add { @@ -255,7 +256,7 @@ namespace System.Data.Odbc if (!ProviderInfo.HasEscapeChar) { string escapeCharString; - escapeCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.SEARCH_PATTERN_ESCAPE); + escapeCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.SEARCH_PATTERN_ESCAPE)!; Debug.Assert((escapeCharString.Length <= 1), "Can't handle multichar quotes"); ProviderInfo.EscapeChar = (escapeCharString.Length == 1) ? escapeCharString[0] : QuoteChar(method)[0]; } @@ -268,7 +269,7 @@ namespace System.Data.Odbc if (!ProviderInfo.HasQuoteChar) { string quoteCharString; - quoteCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.IDENTIFIER_QUOTE_CHAR); + quoteCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.IDENTIFIER_QUOTE_CHAR)!; Debug.Assert((quoteCharString.Length <= 1), "Can't handle multichar quotes"); ProviderInfo.QuoteChar = (1 == quoteCharString.Length) ? quoteCharString : "\0"; } @@ -287,11 +288,11 @@ namespace System.Data.Odbc private void RollbackDeadTransaction() { - WeakReference weak = _weakTransaction; + WeakReference? weak = _weakTransaction; if ((null != weak) && !weak.IsAlive) { _weakTransaction = null; - ConnectionHandle.CompleteTransaction(ODBC32.SQL_ROLLBACK); + ConnectionHandle!.CompleteTransaction(ODBC32.SQL_ROLLBACK); } } @@ -315,7 +316,7 @@ namespace System.Data.Odbc return clone; } - internal bool ConnectionIsAlive(Exception innerException) + internal bool ConnectionIsAlive(Exception? innerException) { if (IsOpen) { @@ -348,18 +349,18 @@ namespace System.Data.Odbc { InnerConnection.CloseConnection(this, ConnectionFactory); - OdbcConnectionHandle connectionHandle = _connectionHandle; + OdbcConnectionHandle? connectionHandle = _connectionHandle; if (null != connectionHandle) { _connectionHandle = null; // If there is a pending transaction, automatically rollback. - WeakReference weak = _weakTransaction; + WeakReference? weak = _weakTransaction; if (null != weak) { _weakTransaction = null; - IDisposable transaction = weak.Target as OdbcTransaction; + IDisposable? transaction = weak.Target as OdbcTransaction; if ((null != transaction) && weak.IsAlive) { transaction.Dispose(); @@ -379,7 +380,7 @@ namespace System.Data.Odbc string value = ""; int cbActual = 0; byte[] buffer = new byte[100]; - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); @@ -412,7 +413,7 @@ namespace System.Data.Odbc int retval = -1; int cbActual = 0; byte[] buffer = new byte[4]; - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); @@ -442,7 +443,7 @@ namespace System.Data.Odbc private string GetDiagSqlState() { - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle connectionHandle = ConnectionHandle!; string sqlstate; connectionHandle.GetDiagnosticField(out sqlstate); return sqlstate; @@ -451,7 +452,7 @@ namespace System.Data.Odbc internal ODBC32.RetCode GetInfoInt16Unhandled(ODBC32.SQL_INFO info, out short resultValue) { byte[] buffer = new byte[2]; - ODBC32.RetCode retcode = ConnectionHandle.GetInfo1(info, buffer); + ODBC32.RetCode retcode = ConnectionHandle!.GetInfo1(info, buffer); resultValue = BitConverter.ToInt16(buffer, 0); return retcode; } @@ -459,7 +460,7 @@ namespace System.Data.Odbc internal ODBC32.RetCode GetInfoInt32Unhandled(ODBC32.SQL_INFO info, out int resultValue) { byte[] buffer = new byte[4]; - ODBC32.RetCode retcode = ConnectionHandle.GetInfo1(info, buffer); + ODBC32.RetCode retcode = ConnectionHandle!.GetInfo1(info, buffer); resultValue = BitConverter.ToInt32(buffer, 0); return retcode; } @@ -467,22 +468,22 @@ namespace System.Data.Odbc private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) { byte[] buffer = new byte[4]; - ConnectionHandle.GetInfo1(infotype, buffer); + ConnectionHandle!.GetInfo1(infotype, buffer); return BitConverter.ToInt32(buffer, 0); } - internal string GetInfoStringUnhandled(ODBC32.SQL_INFO info) + internal string? GetInfoStringUnhandled(ODBC32.SQL_INFO info) { return GetInfoStringUnhandled(info, false); } - private string GetInfoStringUnhandled(ODBC32.SQL_INFO info, bool handleError) + private string? GetInfoStringUnhandled(ODBC32.SQL_INFO info, bool handleError) { //SQLGetInfo - string value = null; + string? value = null; short cbActual = 0; byte[] buffer = new byte[100]; - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetInfo2(info, buffer, out cbActual); @@ -499,7 +500,7 @@ namespace System.Data.Odbc } else if (handleError) { - this.HandleError(ConnectionHandle, retcode); + this.HandleError(connectionHandle, retcode); } } else if (handleError) @@ -510,7 +511,7 @@ namespace System.Data.Odbc } // non-throwing HandleError - internal Exception HandleErrorNoThrow(OdbcHandle hrHandle, ODBC32.RetCode retcode) + internal Exception? HandleErrorNoThrow(OdbcHandle hrHandle, ODBC32.RetCode retcode) { Debug.Assert(retcode != ODBC32.RetCode.INVALID_HANDLE, "retcode must never be ODBC32.RetCode.INVALID_HANDLE"); @@ -537,14 +538,14 @@ namespace System.Data.Odbc e.Errors.SetSource(this.Driver); } ConnectionIsAlive(e); // this will close and throw if the connection is dead - return (Exception)e; + return e; } return null; } internal void HandleError(OdbcHandle hrHandle, ODBC32.RetCode retcode) { - Exception e = HandleErrorNoThrow(hrHandle, retcode); + Exception? e = HandleErrorNoThrow(hrHandle, retcode); switch (retcode) { case ODBC32.RetCode.SUCCESS: @@ -601,11 +602,11 @@ namespace System.Data.Odbc OdbcEnvironment.ReleaseObjectPool(); } - internal OdbcTransaction SetStateExecuting(string method, OdbcTransaction transaction) + internal OdbcTransaction? SetStateExecuting(string method, OdbcTransaction? transaction) { // MDAC 69003 if (null != _weakTransaction) { // transaction may exist - OdbcTransaction weak = (_weakTransaction.Target as OdbcTransaction); + OdbcTransaction? weak = (_weakTransaction.Target as OdbcTransaction); if (transaction != weak) { // transaction doesn't exist if (null == transaction) @@ -778,7 +779,7 @@ namespace System.Data.Odbc ODBC32.RetCode retcode; short fExists; Debug.Assert((short)odbcFunction != 0, "SQL_API_ALL_FUNCTIONS is not supported"); - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) { retcode = connectionHandle.GetFunctions(odbcFunction, out fExists); @@ -921,7 +922,7 @@ namespace System.Data.Odbc }; //Start the transaction - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle connectionHandle = ConnectionHandle!; ODBC32.RetCode retcode = connectionHandle.BeginTransaction(ref isolevel); if (retcode == ODBC32.RetCode.ERROR) { @@ -948,7 +949,7 @@ namespace System.Data.Odbc RollbackDeadTransaction(); //Set the database - OdbcConnectionHandle connectionHandle = ConnectionHandle; + OdbcConnectionHandle connectionHandle = ConnectionHandle!; ODBC32.RetCode retcode = connectionHandle.SetConnectionAttribute3(ODBC32.SQL_ATTR.CURRENT_CATALOG, value, checked((int)value.Length * 2)); if (retcode != ODBC32.RetCode.SUCCESS) @@ -957,7 +958,7 @@ namespace System.Data.Odbc } } - internal string Open_GetServerVersion() + internal string? Open_GetServerVersion() { //SQLGetInfo - SQL_DBMS_VER return GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER, true); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs index 0bdd4b4..d9d3595 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs @@ -5,6 +5,7 @@ using System.Collections.Specialized; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; namespace System.Data.Odbc @@ -26,20 +27,21 @@ namespace System.Data.Odbc } } - protected override DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) + protected override DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningObject) { - DbConnectionInternal result = new OdbcConnectionOpen(owningObject as OdbcConnection, options as OdbcConnectionString); + // TODO: owningObject may actually be null (see DbConnectionPool.CreateObject), in which case this will throw... + DbConnectionInternal result = new OdbcConnectionOpen((owningObject as OdbcConnection)!, (options as OdbcConnectionString)!); return result; } - protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) + protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions? previous) { Debug.Assert(!string.IsNullOrEmpty(connectionString), "empty connectionString"); OdbcConnectionString result = new OdbcConnectionString(connectionString, (null != previous)); return result; } - protected override DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions) + protected override DbConnectionPoolGroupOptions? CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions) { // At this time, the ODBC provider only supports native pooling so we // simply return NULL to indicate that. @@ -60,20 +62,20 @@ namespace System.Data.Odbc Debug.Assert(odbcOuterConnection != null, "outer connection may not be null."); // get the DBMS Name - object driverName = null; - string stringValue = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); + object? driverName = null; + string? stringValue = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); if (stringValue != null) { driverName = stringValue; } - Stream XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.Odbc.OdbcMetaData.xml"); + Stream? XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.Odbc.OdbcMetaData.xml"); cacheMetaDataFactory = true; Debug.Assert(XMLStream != null, "XMLstream may not be null."); - string versionString = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER); + string versionString = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER)!; return new OdbcMetaDataFactory(XMLStream, versionString, @@ -81,9 +83,9 @@ namespace System.Data.Odbc odbcOuterConnection); } - internal override DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) + internal override DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnection? connection) { - OdbcConnection c = (connection as OdbcConnection); + OdbcConnection? c = (connection as OdbcConnection); if (null != c) { return c.PoolGroup; @@ -91,9 +93,9 @@ namespace System.Data.Odbc return null; } - internal override DbConnectionInternal GetInnerConnection(DbConnection connection) + internal override DbConnectionInternal? GetInnerConnection(DbConnection connection) { - OdbcConnection c = (connection as OdbcConnection); + OdbcConnection? c = (connection as OdbcConnection); if (null != c) { return c.InnerConnection; @@ -103,7 +105,7 @@ namespace System.Data.Odbc internal override void PermissionDemand(DbConnection outerConnection) { - OdbcConnection c = (outerConnection as OdbcConnection); + OdbcConnection? c = (outerConnection as OdbcConnection); if (null != c) { c.PermissionDemand(); @@ -112,7 +114,7 @@ namespace System.Data.Odbc internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { - OdbcConnection c = (outerConnection as OdbcConnection); + OdbcConnection? c = (outerConnection as OdbcConnection); if (null != c) { c.PoolGroup = poolGroup; @@ -121,7 +123,7 @@ namespace System.Data.Odbc internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { - OdbcConnection c = (owningObject as OdbcConnection); + OdbcConnection? c = (owningObject as OdbcConnection); if (null != c) { c.SetInnerConnectionEvent(to); @@ -130,7 +132,7 @@ namespace System.Data.Odbc internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { - OdbcConnection c = (owningObject as OdbcConnection); + OdbcConnection? c = (owningObject as OdbcConnection); if (null != c) { return c.SetInnerConnectionFrom(to, from); @@ -140,7 +142,7 @@ namespace System.Data.Odbc internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { - OdbcConnection c = (owningObject as OdbcConnection); + OdbcConnection? c = (owningObject as OdbcConnection); if (null != c) { c.SetInnerConnectionTo(to); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs index 90e755e..a84658b 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs @@ -12,8 +12,8 @@ namespace System.Data.Odbc { private static readonly DbConnectionFactory s_connectionFactory = OdbcConnectionFactory.SingletonInstance; - private DbConnectionOptions _userConnectionOptions; - private DbConnectionPoolGroup _poolGroup; + private DbConnectionOptions? _userConnectionOptions; + private DbConnectionPoolGroup? _poolGroup; private DbConnectionInternal _innerConnection; private int _closeCount; @@ -60,11 +60,11 @@ namespace System.Data.Odbc } } - internal DbConnectionOptions ConnectionOptions + internal DbConnectionOptions? ConnectionOptions { get { - System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; + System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); } } @@ -72,11 +72,11 @@ namespace System.Data.Odbc private string ConnectionString_Get() { bool hidePassword = InnerConnection.ShouldHidePassword; - DbConnectionOptions connectionOptions = UserConnectionOptions; + DbConnectionOptions? connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); } - private void ConnectionString_Set(string value) + private void ConnectionString_Set(string? value) { DbConnectionPoolKey key = new DbConnectionPoolKey(value); @@ -85,8 +85,8 @@ namespace System.Data.Odbc private void ConnectionString_Set(DbConnectionPoolKey key) { - DbConnectionOptions connectionOptions = null; - System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions); + DbConnectionOptions? connectionOptions = null; + System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions); DbConnectionInternal connectionInternal = InnerConnection; bool flag = connectionInternal.AllowSetConnectionString; if (flag) @@ -113,7 +113,7 @@ namespace System.Data.Odbc } } - internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup + internal System.Data.ProviderBase.DbConnectionPoolGroup? PoolGroup { get { @@ -127,7 +127,7 @@ namespace System.Data.Odbc } - internal DbConnectionOptions UserConnectionOptions + internal DbConnectionOptions? UserConnectionOptions { get { @@ -152,9 +152,8 @@ namespace System.Data.Odbc protected override DbCommand CreateDbCommand() { - DbCommand command = null; DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; - command = providerFactory.CreateCommand(); + DbCommand command = providerFactory.CreateCommand()!; command.Connection = this; return command; } @@ -184,11 +183,11 @@ namespace System.Data.Odbc return this.GetSchema(collectionName, null); } - public override DataTable GetSchema(string collectionName, string[] restrictionValues) + public override DataTable GetSchema(string collectionName, string?[]? restrictionValues) { // NOTE: This is virtual because not all providers may choose to support // returning schema data - return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues); + return InnerConnection.GetSchema(ConnectionFactory, PoolGroup!, this, collectionName, restrictionValues); } internal void NotifyWeakReference(int message) @@ -199,13 +198,13 @@ namespace System.Data.Odbc internal void PermissionDemand() { Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); - System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; - DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; + DbConnectionOptions? connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); if ((null == connectionOptions) || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } - DbConnectionOptions userConnectionOptions = UserConnectionOptions; + DbConnectionOptions? userConnectionOptions = UserConnectionOptions; Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs index 2c6f7c7..008facb 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.cs @@ -19,7 +19,7 @@ namespace System.Data.Odbc { get { - OdbcConnection outerConnection = (OdbcConnection)Owner; + OdbcConnection? outerConnection = (OdbcConnection?)Owner; if (null == outerConnection) throw ODBC.OpenConnectionNoOwner(); @@ -32,7 +32,9 @@ namespace System.Data.Odbc { get { - return OuterConnection.Open_GetServerVersion(); + // TODO-NULLABLE: This seems like it returns null if the connection is open, whereas the docs say it should throw + // InvalidOperationException + return OuterConnection.Open_GetServerVersion()!; } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs index e498e98..b49f953 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionPoolProviderInfo.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Data.ProviderBase; +using System.Diagnostics; namespace System.Data.Odbc { internal sealed class OdbcConnectionPoolGroupProviderInfo : DbConnectionPoolGroupProviderInfo { - private string _driverName; - private string _driverVersion; - private string _quoteChar; + private string? _driverName; + private string? _driverVersion; + private string? _quoteChar; private char _escapeChar; private bool _hasQuoteChar; @@ -35,7 +36,7 @@ namespace System.Data.Odbc // flags for unsupported Functions private bool _noSqlPrimaryKeys; - internal string DriverName + internal string? DriverName { get { @@ -47,7 +48,7 @@ namespace System.Data.Odbc } } - internal string DriverVersion + internal string? DriverVersion { get { @@ -82,6 +83,7 @@ namespace System.Data.Odbc { get { + Debug.Assert(_quoteChar != null, "QuoteChar getter called but no quote char was set"); return _quoteChar; } set diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs index e17edac..74790e0 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionString.cs @@ -12,13 +12,13 @@ namespace System.Data.Odbc // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution - private readonly string _expandedConnectionString; + private readonly string? _expandedConnectionString; internal OdbcConnectionString(string connectionString, bool validate) : base(connectionString, null, true) { if (!validate) { - string filename = null; + string? filename = null; int position = 0; _expandedConnectionString = ExpandDataDirectories(ref filename, ref position); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs index 877275e..ae68e13 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionStringbuilder.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data.Odbc { @@ -30,16 +31,16 @@ namespace System.Data.Odbc { DbConnectionStringKeywords.Dsn, Keywords.Dsn } }; - private string[] _knownKeywords; + private string[]? _knownKeywords; private string _dsn = DbConnectionStringDefaults.Dsn; private string _driver = DbConnectionStringDefaults.Driver; - public OdbcConnectionStringBuilder() : this((string)null) + public OdbcConnectionStringBuilder() : this(null) { } - public OdbcConnectionStringBuilder(string connectionString) : base(true) + public OdbcConnectionStringBuilder(string? connectionString) : base(true) { if (!string.IsNullOrEmpty(connectionString)) { @@ -47,6 +48,7 @@ namespace System.Data.Odbc } } + [AllowNull] public override object this[string keyword] { get @@ -119,7 +121,7 @@ namespace System.Data.Odbc { get { - string[] knownKeywords = _knownKeywords; + string[]? knownKeywords = _knownKeywords; if (null == knownKeywords) { knownKeywords = s_validKeywords; @@ -245,7 +247,7 @@ namespace System.Data.Odbc base[keyword] = value; } - public override bool TryGetValue(string keyword, out object value) + public override bool TryGetValue(string keyword, [NotNullWhen(true)] out object? value) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs index 2235d13..29b6dcc 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataAdapter.cs @@ -10,24 +10,24 @@ namespace System.Data.Odbc private static readonly object s_eventRowUpdated = new object(); private static readonly object s_eventRowUpdating = new object(); - private OdbcCommand _deleteCommand, _insertCommand, _selectCommand, _updateCommand; + private OdbcCommand? _deleteCommand, _insertCommand, _selectCommand, _updateCommand; public OdbcDataAdapter() : base() { GC.SuppressFinalize(this); } - public OdbcDataAdapter(OdbcCommand selectCommand) : this() + public OdbcDataAdapter(OdbcCommand? selectCommand) : this() { SelectCommand = selectCommand; } - public OdbcDataAdapter(string selectCommandText, OdbcConnection selectConnection) : this() + public OdbcDataAdapter(string? selectCommandText, OdbcConnection? selectConnection) : this() { SelectCommand = new OdbcCommand(selectCommandText, selectConnection); } - public OdbcDataAdapter(string selectCommandText, string selectConnectionString) : this() + public OdbcDataAdapter(string? selectCommandText, string? selectConnectionString) : this() { OdbcConnection connection = new OdbcConnection(selectConnectionString); SelectCommand = new OdbcCommand(selectCommandText, connection); @@ -38,55 +38,55 @@ namespace System.Data.Odbc GC.SuppressFinalize(this); } - public new OdbcCommand DeleteCommand + public new OdbcCommand? DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = value; } } - IDbCommand IDbDataAdapter.DeleteCommand + IDbCommand? IDbDataAdapter.DeleteCommand { get { return _deleteCommand; } - set { _deleteCommand = (OdbcCommand)value; } + set { _deleteCommand = (OdbcCommand?)value; } } - public new OdbcCommand InsertCommand + public new OdbcCommand? InsertCommand { get { return _insertCommand; } set { _insertCommand = value; } } - IDbCommand IDbDataAdapter.InsertCommand + IDbCommand? IDbDataAdapter.InsertCommand { get { return _insertCommand; } - set { _insertCommand = (OdbcCommand)value; } + set { _insertCommand = (OdbcCommand?)value; } } - public new OdbcCommand SelectCommand + public new OdbcCommand? SelectCommand { get { return _selectCommand; } set { _selectCommand = value; } } - IDbCommand IDbDataAdapter.SelectCommand + IDbCommand? IDbDataAdapter.SelectCommand { get { return _selectCommand; } - set { _selectCommand = (OdbcCommand)value; } + set { _selectCommand = (OdbcCommand?)value; } } - public new OdbcCommand UpdateCommand + public new OdbcCommand? UpdateCommand { get { return _updateCommand; } set { _updateCommand = value; } } - IDbCommand IDbDataAdapter.UpdateCommand + IDbCommand? IDbDataAdapter.UpdateCommand { get { return _updateCommand; } - set { _updateCommand = (OdbcCommand)value; } + set { _updateCommand = (OdbcCommand?)value; } } - public event OdbcRowUpdatedEventHandler RowUpdated + public event OdbcRowUpdatedEventHandler? RowUpdated { add { @@ -98,18 +98,18 @@ namespace System.Data.Odbc } } - public event OdbcRowUpdatingEventHandler RowUpdating + public event OdbcRowUpdatingEventHandler? RowUpdating { add { - OdbcRowUpdatingEventHandler handler = (OdbcRowUpdatingEventHandler)Events[s_eventRowUpdating]; + OdbcRowUpdatingEventHandler? handler = (OdbcRowUpdatingEventHandler?)Events[s_eventRowUpdating]; // MDAC 58177, 64513 // prevent someone from registering two different command builders on the adapter by // silently removing the old one - if ((null != handler) && (value.Target is OdbcCommandBuilder)) + if ((null != handler) && (value!.Target is OdbcCommandBuilder)) { - OdbcRowUpdatingEventHandler d = (OdbcRowUpdatingEventHandler)ADP.FindBuilder(handler); + OdbcRowUpdatingEventHandler? d = (OdbcRowUpdatingEventHandler?)ADP.FindBuilder(handler); if (null != d) { Events.RemoveHandler(s_eventRowUpdating, d); @@ -129,19 +129,19 @@ namespace System.Data.Odbc return new OdbcDataAdapter(this); } - protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { return new OdbcRowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } - protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { return new OdbcRowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } protected override void OnRowUpdated(RowUpdatedEventArgs value) { - OdbcRowUpdatedEventHandler handler = (OdbcRowUpdatedEventHandler)Events[s_eventRowUpdated]; + OdbcRowUpdatedEventHandler? handler = (OdbcRowUpdatedEventHandler?)Events[s_eventRowUpdated]; if ((null != handler) && (value is OdbcRowUpdatedEventArgs)) { handler(this, (OdbcRowUpdatedEventArgs)value); @@ -151,7 +151,7 @@ namespace System.Data.Odbc protected override void OnRowUpdating(RowUpdatingEventArgs value) { - OdbcRowUpdatingEventHandler handler = (OdbcRowUpdatingEventHandler)Events[s_eventRowUpdating]; + OdbcRowUpdatingEventHandler? handler = (OdbcRowUpdatingEventHandler?)Events[s_eventRowUpdating]; if ((null != handler) && (value is OdbcRowUpdatingEventArgs)) { handler(this, (OdbcRowUpdatingEventArgs)value); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index d66f5f2..87c0e92 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -15,12 +15,12 @@ namespace System.Data.Odbc { public sealed class OdbcDataReader : DbDataReader { - private OdbcCommand _command; + private OdbcCommand? _command; private int _recordAffected = -1; - private FieldNameLookup _fieldNameLookup; + private FieldNameLookup? _fieldNameLookup; - private DbCache _dataCache; + private DbCache? _dataCache; private enum HasRowsStatus { DontKnow = 0, @@ -51,10 +51,10 @@ namespace System.Data.Odbc // the DataReader must not free the statement handle. this is done by the command // - private MetaData[] _metadata; - private DataTable _schemaTable; // MDAC 68336 + private MetaData[]? _metadata; + private DataTable? _schemaTable; // MDAC 68336 private readonly string _cmdText; // get a copy in case the command text on the command is changed ... - private CMDWrapper _cmdWrapper; + private CMDWrapper? _cmdWrapper; internal OdbcDataReader(OdbcCommand command, CMDWrapper cmdWrapper, CommandBehavior commandbehavior) { @@ -69,7 +69,7 @@ namespace System.Data.Odbc { get { - CNativeBuffer value = _cmdWrapper._dataReaderBuf; + CNativeBuffer? value = _cmdWrapper!._dataReaderBuf; if (null == value) { Debug.Fail("object is disposed"); @@ -79,7 +79,7 @@ namespace System.Data.Odbc } } - private OdbcConnection Connection + private OdbcConnection? Connection { get { @@ -94,7 +94,7 @@ namespace System.Data.Odbc } } - internal OdbcCommand Command + internal OdbcCommand? Command { get { @@ -110,13 +110,13 @@ namespace System.Data.Odbc { get { - return _cmdWrapper.StatementHandle; + return _cmdWrapper!.StatementHandle!; } } private OdbcStatementHandle KeyInfoStatementHandle { - get { return _cmdWrapper.KeyInfoStatement; } + get { return _cmdWrapper!.KeyInfoStatement!; } } internal bool IsBehavior(CommandBehavior behavior) @@ -178,7 +178,7 @@ namespace System.Data.Odbc ODBC32.RetCode retcode = this.FieldCountNoThrow(out cColsAffected); if (retcode != ODBC32.RetCode.SUCCESS) { - Connection.HandleError(StatementHandle, retcode); + Connection!.HandleError(StatementHandle, retcode); } } return ((null != _dataCache) ? _dataCache._count : 0); @@ -224,7 +224,7 @@ namespace System.Data.Odbc { // we need to search for the first hidden column // - if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns) + if (!Connection!.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns) { for (int i = 0; i < cColsAffected; i++) { @@ -317,9 +317,9 @@ namespace System.Data.Odbc private void Close(bool disposing) { - Exception error = null; + Exception? error = null; - CMDWrapper wrapper = _cmdWrapper; + CMDWrapper? wrapper = _cmdWrapper; if (null != wrapper && wrapper.StatementHandle != null) { // disposing @@ -339,7 +339,7 @@ namespace System.Data.Odbc { // Output Parameters are not guareenteed to be returned until all the data // from any restssets are read, so we do this after the above NextResult call(s) - _command.Parameters.GetOutputValues(_cmdWrapper); + _command.Parameters.GetOutputValues(_cmdWrapper!); } wrapper.FreeStatementHandle(ODBC32.STMT.CLOSE); _command.CloseFromDataReader(); @@ -407,7 +407,10 @@ namespace System.Data.Odbc { info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW); } +// TODO-NULLABLE: Behavior change probably needed here - when there's no data type, we mostly probably need to throw instead of returning null. +#nullable disable return info._typename; +#nullable enable } throw ADP.DataReaderNoData(); } @@ -545,7 +548,7 @@ namespace System.Data.Odbc //will work), and then query for a speicial SQLServer specific attribute. if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { int dummy; bool isNotDbNull = QueryFieldInfo(i, ODBC32.SQL_C.BINARY, out dummy); @@ -557,7 +560,7 @@ namespace System.Data.Odbc return GetValue(i, TypeMap.FromSqlType(subtype)); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); @@ -573,11 +576,11 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { _dataCache[i] = GetValue(i, GetSqlType(i)); } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -601,7 +604,7 @@ namespace System.Data.Odbc //Note: Types are always returned (advertised) from ODBC as SQL_TYPEs, and //are always bound by the user as SQL_C types. TypeMap typeMap; - DbSchemaInfo info = _dataCache.GetSchema(i); + DbSchemaInfo info = _dataCache!.GetSchema(i); if (!info._dbtype.HasValue) { info._dbtype = unchecked((ODBC32.SQL_TYPE)(int)GetColAttribute(i, ODBC32.SQL_DESC.CONCISE_TYPE, ODBC32.SQL_COLUMN.TYPE, ODBC32.HANDLER.THROW)); @@ -617,14 +620,14 @@ namespace System.Data.Odbc { typeMap = TypeMap.FromSqlType(info._dbtype.Value); } - Connection.SetSupportedType(info._dbtype.Value); + Connection!.SetSupportedType(info._dbtype.Value); return typeMap; } public override bool IsDBNull(int i) { - // Note: ODBC SQLGetData doesn't allow retriving the column value twice. - // The reational is that for ForwardOnly access (the default and LCD of drivers) + // Note: ODBC SQLGetData doesn't allow retrieving the column value twice. + // The rationale is that for ForwardOnly access (the default and LCD of drivers) // we cannot obtain the data more than once, and even GetData(0) (to determine is-null) // still obtains data for fixed length types. @@ -650,7 +653,7 @@ namespace System.Data.Odbc // But, to minimize regressions, we will continue caching the fixed-size values (case 2), even with SequentialAccess // only in case of SequentialAccess with variable length data types (case 3), we will use GetData with zero length. - object cachedObj = _dataCache[i]; + object? cachedObj = _dataCache![i]; if (cachedObj != null) { // case 4 - if cached object was created before, use it @@ -686,14 +689,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.UTINYINT)) { _dataCache[i] = Buffer.ReadByte(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -706,14 +709,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { _dataCache[i] = Buffer.ReadChar(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -726,14 +729,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.SSHORT)) { _dataCache[i] = Buffer.ReadInt16(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -746,14 +749,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.SLONG)) { _dataCache[i] = Buffer.ReadInt32(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -773,7 +776,7 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { @@ -781,7 +784,7 @@ namespace System.Data.Odbc _dataCache[i] = long.Parse(value, CultureInfo.InvariantCulture); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -794,14 +797,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.BIT)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.BIT, -1); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -814,14 +817,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.REAL)) { _dataCache[i] = Buffer.ReadSingle(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -835,14 +838,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.TYPE_DATE)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_DATE, -1); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -856,14 +859,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.TYPE_TIMESTAMP)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_TIMESTAMP, -1); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -884,11 +887,11 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { - string s = null; + string? s = null; try { s = (string)Buffer.MarshalToManaged(0, ODBC32.SQL_C.WCHAR, ODBC32.SQL_NTS); @@ -901,7 +904,7 @@ namespace System.Data.Odbc } } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -914,14 +917,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.DOUBLE)) { _dataCache[i] = Buffer.ReadDouble(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -935,14 +938,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.GUID)) { _dataCache[i] = Buffer.ReadGuid(0); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -956,7 +959,7 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { // Obtain _ALL_ the characters // Note: We can bind directly as WCHAR in ODBC and the DM will convert to and @@ -1049,7 +1052,7 @@ namespace System.Data.Odbc _dataCache[i] = builder.ToString(); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -1063,14 +1066,14 @@ namespace System.Data.Odbc { if (_isRead) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.TYPE_TIME)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_TIME, -1); } } - return _dataCache[i]; + return _dataCache[i]!; } throw ADP.DataReaderNoData(); } @@ -1087,17 +1090,17 @@ namespace System.Data.Odbc } } - public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) + public override long GetBytes(int i, long dataIndex, byte[]? buffer, int bufferIndex, int length) { return GetBytesOrChars(i, dataIndex, buffer, false /* bytes buffer */, bufferIndex, length); } - public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) + public override long GetChars(int i, long dataIndex, char[]? buffer, int bufferIndex, int length) { return GetBytesOrChars(i, dataIndex, buffer, true /* chars buffer */, bufferIndex, length); } // unify the implementation of GetChars and GetBytes to prevent code duplicate - private long GetBytesOrChars(int i, long dataIndex, Array buffer, bool isCharsBuffer, int bufferIndex, int length) + private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsBuffer, int bufferIndex, int length) { if (IsClosed) { @@ -1133,13 +1136,13 @@ namespace System.Data.Odbc // use the cache - preserve the original behavior to minimize regression risk // 4. sequential access, no cache: (fixed now) user reads the bytes/chars in sequential order (no cache) - object cachedObj = null; // The cached object (if there is one) + object? cachedObj = null; // The cached object (if there is one) // Get cached object, ensure the correct type using explicit cast, to preserve same behavior as before if (isCharsBuffer) - cachedObj = (string)_dataCache[i]; + cachedObj = (string?)_dataCache![i]; else - cachedObj = (byte[])_dataCache[i]; + cachedObj = (byte[]?)_dataCache![i]; bool isRandomAccess = !IsCommandBehavior(CommandBehavior.SequentialAccess); @@ -1354,7 +1357,7 @@ namespace System.Data.Odbc // fill the user's buffer (char[] or byte[], depending on isCharsBuffer) // if buffer is null, just skip the bytesOrCharsLength bytes or chars - private int readBytesOrCharsSequentialAccess(int i, Array buffer, bool isCharsBuffer, int bufferIndex, long bytesOrCharsLength) + private int readBytesOrCharsSequentialAccess(int i, Array? buffer, bool isCharsBuffer, int bufferIndex, long bytesOrCharsLength) { Debug.Assert(bufferIndex >= 0, "Negative buffer index"); Debug.Assert(bytesOrCharsLength >= 0, "Negative number of bytes or chars to read"); @@ -1477,7 +1480,7 @@ namespace System.Data.Odbc private object internalGetBytes(int i) { - if (_dataCache.AccessIndex(i) == null) + if (_dataCache!.AccessIndex(i) == null) { // Obtain _ALL_ the bytes... // The first time GetData returns the true length (so we have to min it). @@ -1536,7 +1539,7 @@ namespace System.Data.Odbc _dataCache[i] = rgBytes; } } - return _dataCache[i]; + return _dataCache[i]!; } // GetColAttribute @@ -1555,7 +1558,7 @@ namespace System.Data.Odbc ODBC32.RetCode retcode; // protect against dead connection, dead or canceling command. - if ((Connection == null) || _cmdWrapper.Canceling) + if ((Connection == null) || _cmdWrapper!.Canceling) { return -1; } @@ -1578,7 +1581,7 @@ namespace System.Data.Odbc { if (retcode == ODBC32.RetCode.ERROR) { - if ("HY091" == Command.GetDiagSqlState()) + if ("HY091" == Command!.GetDiagSqlState()) { Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId); } @@ -1601,7 +1604,7 @@ namespace System.Data.Odbc // returns the stringvalue of the FieldIdentifier field of the column // or null if the string returned was empty or if the FieldIdentifier wasn't supported by the driver // - private string GetColAttributeStr(int i, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler) + private string? GetColAttributeStr(int i, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler) { ODBC32.RetCode retcode; short cchNameLength = 0; @@ -1609,10 +1612,10 @@ namespace System.Data.Odbc CNativeBuffer buffer = Buffer; buffer.WriteInt16(0, 0); - OdbcStatementHandle stmt = StatementHandle; + OdbcStatementHandle? stmt = StatementHandle; // protect against dead connection - if (Connection == null || _cmdWrapper.Canceling || stmt == null) + if (Connection == null || _cmdWrapper!.Canceling || stmt == null) { return ""; } @@ -1633,7 +1636,7 @@ namespace System.Data.Odbc { if (retcode == ODBC32.RetCode.ERROR) { - if ("HY091" == Command.GetDiagSqlState()) + if ("HY091" == Command!.GetDiagSqlState()) { Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId); } @@ -1651,12 +1654,12 @@ namespace System.Data.Odbc // todo: Another 3.0 only attribute that is guaranteed to fail on V2 driver. // need to special case this for V2 drivers. // - private string GetDescFieldStr(int i, ODBC32.SQL_DESC attribute, ODBC32.HANDLER handler) + private string? GetDescFieldStr(int i, ODBC32.SQL_DESC attribute, ODBC32.HANDLER handler) { int numericAttribute = 0; // protect against dead connection, dead or canceling command. - if ((Connection == null) || _cmdWrapper.Canceling) + if ((Connection == null) || _cmdWrapper!.Canceling) { return ""; } @@ -1684,7 +1687,7 @@ namespace System.Data.Odbc { if (retcode == ODBC32.RetCode.ERROR) { - if ("HY091" == Command.GetDiagSqlState()) + if ("HY091" == Command!.GetDiagSqlState()) { Connection.FlagUnsupportedColAttr(attribute, (ODBC32.SQL_COLUMN)0); } @@ -1786,7 +1789,7 @@ namespace System.Data.Odbc // Thus, ignore NO_DATA for variable length data, but raise exception for fixed-size types if (sqlctype != ODBC32.SQL_C.WCHAR && sqlctype != ODBC32.SQL_C.BINARY) { - Connection.HandleError(StatementHandle, retcode); + Connection!.HandleError(StatementHandle, retcode); } if (cbActual == (IntPtr)ODBC32.SQL_NO_TOTAL) @@ -1797,7 +1800,7 @@ namespace System.Data.Odbc break; default: - Connection.HandleError(StatementHandle, retcode); + Connection!.HandleError(StatementHandle, retcode); break; } @@ -1810,7 +1813,7 @@ namespace System.Data.Odbc // Store the DBNull value in cache. Note that if we need to do it, because second call into the SQLGetData returns NO_DATA, which means // we already consumed the value (see above) and the NULL information is lost. By storing the null in cache, we avoid second call into the driver // for the same row/column. - _dataCache[i] = DBNull.Value; + _dataCache![i] = DBNull.Value; // the indicator is never -1 (and it should not actually be used if the data is DBNull) cbLengthOrIndicator = 0; return false; @@ -1864,7 +1867,7 @@ namespace System.Data.Odbc switch (retcode) { case ODBC32.RetCode.SUCCESS_WITH_INFO: - Connection.HandleErrorNoThrow(StatementHandle, retcode); + Connection!.HandleErrorNoThrow(StatementHandle, retcode); _hasRows = HasRowsStatus.HasRows; _isRead = true; break; @@ -1880,11 +1883,11 @@ namespace System.Data.Odbc } break; default: - Connection.HandleError(StatementHandle, retcode); + Connection!.HandleError(StatementHandle, retcode); break; } //Null out previous cached row values. - _dataCache.FlushValues(); + _dataCache!.FlushValues(); // if CommandBehavior == SingleRow we set _noMoreResults to true so that following reads will fail if (IsCommandBehavior(CommandBehavior.SingleRow)) @@ -1961,7 +1964,7 @@ namespace System.Data.Odbc _schemaTable = null; int loop = 0; // infinite loop protection, max out after 2000 consecutive failed results - OdbcErrorCollection errors = null; // SQLBU 342112 + OdbcErrorCollection? errors = null; // SQLBU 342112 do { _isValidResult = false; @@ -1971,7 +1974,7 @@ namespace System.Data.Odbc if (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO) { - Connection.HandleErrorNoThrow(StatementHandle, retcode); + Connection!.HandleErrorNoThrow(StatementHandle, retcode); } else if (!disposing && (retcode != ODBC32.RetCode.NO_DATA) && (ODBC32.RetCode.SUCCESS != retcode)) { @@ -2010,7 +2013,7 @@ namespace System.Data.Odbc if (null != errors) { Debug.Assert(!disposing, "errors while disposing"); - errors.SetSource(Connection.Driver); + errors.SetSource(Connection!.Driver); OdbcException exception = OdbcException.CreateException(errors, firstRetCode); Connection.ConnectionIsAlive(exception); throw exception; @@ -2022,7 +2025,7 @@ namespace System.Data.Odbc { int count = FieldCount; MetaData[] metaInfos = new MetaData[count]; - List qrytables; + List? qrytables; bool needkeyinfo = IsCommandBehavior(CommandBehavior.KeyInfo); bool isKeyColumn; bool isHidden; @@ -2094,7 +2097,7 @@ namespace System.Data.Odbc // Note: Following two attributes are SQL Server specific (hence _SS in the name) // SSS_WARNINGS_OFF - if (!Connection.ProviderInfo.NoSqlCASSColumnKey) + if (!Connection!.ProviderInfo.NoSqlCASSColumnKey) { isKeyColumn = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1; if (isKeyColumn) @@ -2113,22 +2116,22 @@ namespace System.Data.Odbc if (Connection.IsV3Driver) { - if ((metaInfos[i].baseTableName == null) || (metaInfos[i].baseTableName.Length == 0)) + if (string.IsNullOrEmpty(metaInfos[i].baseTableName)) { // Driver didn't return the necessary information from GetColAttributeStr. // Try GetDescField() metaInfos[i].baseTableName = GetDescFieldStr(i, ODBC32.SQL_DESC.BASE_TABLE_NAME, ODBC32.HANDLER.IGNORE); } - if ((metaInfos[i].baseColumnName == null) || (metaInfos[i].baseColumnName.Length == 0)) + if (string.IsNullOrEmpty(metaInfos[i].baseColumnName)) { // Driver didn't return the necessary information from GetColAttributeStr. // Try GetDescField() metaInfos[i].baseColumnName = GetDescFieldStr(i, ODBC32.SQL_DESC.BASE_COLUMN_NAME, ODBC32.HANDLER.IGNORE); } } - if ((metaInfos[i].baseTableName != null) && !(qrytables.Contains(metaInfos[i].baseTableName))) + if ((metaInfos[i].baseTableName is string baseTableName) && !(qrytables!.Contains(baseTableName))) { - qrytables.Add(metaInfos[i].baseTableName); + qrytables.Add(baseTableName); } } @@ -2143,7 +2146,7 @@ namespace System.Data.Odbc // now loop over the hidden columns (if any) // SSS_WARNINGS_OFF - if (!Connection.ProviderInfo.NoSqlCASSColumnKey) + if (!Connection!.ProviderInfo.NoSqlCASSColumnKey) { for (int i = count; i < count + _hiddenColumns; i++) { @@ -2250,7 +2253,10 @@ namespace System.Data.Odbc } if (_noMoreResults) { +// TODO-NULLABLE: Behavior change (https://github.com/dotnet/runtime/issues/509) +#nullable disable return null; // no more results +#nullable enable } if (null != _schemaTable) { @@ -2269,24 +2275,24 @@ namespace System.Data.Odbc BuildMetaDataInfo(); } - DataColumn columnName = schematable.Columns["ColumnName"]; - DataColumn columnOrdinal = schematable.Columns["ColumnOrdinal"]; - DataColumn columnSize = schematable.Columns["ColumnSize"]; - DataColumn numericPrecision = schematable.Columns["NumericPrecision"]; - DataColumn numericScale = schematable.Columns["NumericScale"]; - DataColumn dataType = schematable.Columns["DataType"]; - DataColumn providerType = schematable.Columns["ProviderType"]; - DataColumn isLong = schematable.Columns["IsLong"]; - DataColumn allowDBNull = schematable.Columns["AllowDBNull"]; - DataColumn isReadOnly = schematable.Columns["IsReadOnly"]; - DataColumn isRowVersion = schematable.Columns["IsRowVersion"]; - DataColumn isUnique = schematable.Columns["IsUnique"]; - DataColumn isKey = schematable.Columns["IsKey"]; - DataColumn isAutoIncrement = schematable.Columns["IsAutoIncrement"]; - DataColumn baseSchemaName = schematable.Columns["BaseSchemaName"]; - DataColumn baseCatalogName = schematable.Columns["BaseCatalogName"]; - DataColumn baseTableName = schematable.Columns["BaseTableName"]; - DataColumn baseColumnName = schematable.Columns["BaseColumnName"]; + DataColumn columnName = schematable.Columns["ColumnName"]!; + DataColumn columnOrdinal = schematable.Columns["ColumnOrdinal"]!; + DataColumn columnSize = schematable.Columns["ColumnSize"]!; + DataColumn numericPrecision = schematable.Columns["NumericPrecision"]!; + DataColumn numericScale = schematable.Columns["NumericScale"]!; + DataColumn dataType = schematable.Columns["DataType"]!; + DataColumn providerType = schematable.Columns["ProviderType"]!; + DataColumn isLong = schematable.Columns["IsLong"]!; + DataColumn allowDBNull = schematable.Columns["AllowDBNull"]!; + DataColumn isReadOnly = schematable.Columns["IsReadOnly"]!; + DataColumn isRowVersion = schematable.Columns["IsRowVersion"]!; + DataColumn isUnique = schematable.Columns["IsUnique"]!; + DataColumn isKey = schematable.Columns["IsKey"]!; + DataColumn isAutoIncrement = schematable.Columns["IsAutoIncrement"]!; + DataColumn baseSchemaName = schematable.Columns["BaseSchemaName"]!; + DataColumn baseCatalogName = schematable.Columns["BaseCatalogName"]!; + DataColumn baseTableName = schematable.Columns["BaseTableName"]!; + DataColumn baseColumnName = schematable.Columns["BaseColumnName"]!; //Populate the rows (1 row for each column) @@ -2297,7 +2303,7 @@ namespace System.Data.Odbc row[columnName] = GetName(i); //ColumnName row[columnOrdinal] = i; //ColumnOrdinal - row[columnSize] = unchecked((int)Math.Min(Math.Max(int.MinValue, _metadata[i].size.ToInt64()), int.MaxValue)); + row[columnSize] = unchecked((int)Math.Min(Math.Max(int.MinValue, _metadata![i].size.ToInt64()), int.MaxValue)); row[numericPrecision] = (short)_metadata[i].precision; row[numericScale] = (short)_metadata[i].scale; row[dataType] = _metadata[i].typemap._type; //DataType @@ -2328,6 +2334,8 @@ namespace System.Data.Odbc internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTableName, bool quoted) { + Debug.Assert(_metadata != null); + ODBC32.RetCode retcode; string columnname; int ordinal; @@ -2350,13 +2358,13 @@ namespace System.Data.Odbc if (needkeyinfo) { - if (!Connection.ProviderInfo.NoSqlPrimaryKeys) + if (!Connection!.ProviderInfo.NoSqlPrimaryKeys) { // Get the primary keys retcode = KeyInfoStatementHandle.PrimaryKeys( qualifiedTableName.Catalog, qualifiedTableName.Schema, - qualifiedTableName.GetTable(quoted)); + qualifiedTableName.GetTable(quoted)!); if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { @@ -2419,7 +2427,7 @@ namespace System.Data.Odbc } else { - if ("IM001" == Command.GetDiagSqlState()) + if ("IM001" == Command!.GetDiagSqlState()) { Connection.ProviderInfo.NoSqlPrimaryKeys = true; } @@ -2436,7 +2444,7 @@ namespace System.Data.Odbc } // Get the special columns for version - retcode = KeyInfoStatementHandle.SpecialColumns(qualifiedTableName.GetTable(quoted)); + retcode = KeyInfoStatementHandle.SpecialColumns(qualifiedTableName.GetTable(quoted)!); if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { @@ -2496,6 +2504,8 @@ namespace System.Data.Odbc // Uses SQLStatistics to retrieve key information for a table private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, bool quoted) { + Debug.Assert(_metadata != null); + ODBC32.RetCode retcode; string columnname = string.Empty; string indexname = string.Empty; @@ -2514,7 +2524,7 @@ namespace System.Data.Odbc // devnote: this test is already done by calling method ... // if (IsClosed) return; // protect against dead connection - string tablename1 = qualifiedTableName.GetTable(quoted); + string tablename1 = qualifiedTableName.GetTable(quoted)!; // Select only unique indexes retcode = KeyInfoStatementHandle.Statistics(tablename1); @@ -2670,7 +2680,7 @@ namespace System.Data.Odbc } } // Unbind the columns - _cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.UNBIND); + _cmdWrapper!.FreeKeyInfoStatementHandle(ODBC32.STMT.UNBIND); } finally { @@ -2694,12 +2704,12 @@ namespace System.Data.Odbc return false; } - internal int GetOrdinalFromBaseColName(string columnname) + internal int GetOrdinalFromBaseColName(string? columnname) { return GetOrdinalFromBaseColName(columnname, null); } - internal int GetOrdinalFromBaseColName(string columnname, string tablename) + internal int GetOrdinalFromBaseColName(string? columnname, string? tablename) { if (string.IsNullOrEmpty(columnname)) { @@ -2737,7 +2747,7 @@ namespace System.Data.Odbc // we can't handle multiple tablenames (JOIN) // only the first tablename will be returned - internal string GetTableNameFromCommandText() + internal string? GetTableNameFromCommandText() { if (_command == null) { @@ -2750,7 +2760,7 @@ namespace System.Data.Odbc } string tablename; int idx; - CStringTokenizer tokenstmt = new CStringTokenizer(localcmdtext, Connection.QuoteChar(ADP.GetSchemaTable)[0], Connection.EscapeChar(ADP.GetSchemaTable)); + CStringTokenizer tokenstmt = new CStringTokenizer(localcmdtext, Connection!.QuoteChar(ADP.GetSchemaTable)[0], Connection.EscapeChar(ADP.GetSchemaTable)); if (tokenstmt.StartsWith("select") == true) { @@ -2800,7 +2810,7 @@ namespace System.Data.Odbc for (int i = 0; i < count; i++) { - if (_metadata[i].baseTableName == null) + if (_metadata![i].baseTableName == null) { _metadata[i].baseTableName = qualifiedTableName.Table; _metadata[i].baseSchemaName = qualifiedTableName.Schema; @@ -2812,13 +2822,13 @@ namespace System.Data.Odbc internal sealed class QualifiedTableName { - private readonly string _catalogName; - private readonly string _schemaName; - private string _tableName; - private string _quotedTableName; + private readonly string? _catalogName; + private readonly string? _schemaName; + private string? _tableName; + private string? _quotedTableName; private readonly string _quoteChar; - internal string Catalog + internal string? Catalog { get { @@ -2826,7 +2836,7 @@ namespace System.Data.Odbc } } - internal string Schema + internal string? Schema { get { @@ -2834,7 +2844,7 @@ namespace System.Data.Odbc } } - internal string Table + internal string? Table { get { @@ -2846,14 +2856,14 @@ namespace System.Data.Odbc _tableName = UnQuote(value); } } - internal string QuotedTable + internal string? QuotedTable { get { return _quotedTableName; } } - internal string GetTable(bool flag) + internal string? GetTable(bool flag) { return (flag ? QuotedTable : Table); } @@ -2861,18 +2871,18 @@ namespace System.Data.Odbc { _quoteChar = quoteChar; } - internal QualifiedTableName(string quoteChar, string qualifiedname) + internal QualifiedTableName(string quoteChar, string? qualifiedname) { _quoteChar = quoteChar; - string[] names = ParseProcedureName(qualifiedname, quoteChar, quoteChar); + string?[] names = ParseProcedureName(qualifiedname, quoteChar, quoteChar); _catalogName = UnQuote(names[1]); _schemaName = UnQuote(names[2]); _quotedTableName = names[3]; _tableName = UnQuote(names[3]); } - private string UnQuote(string str) + private string? UnQuote(string? str) { if ((str != null) && (str.Length > 0)) { @@ -2893,7 +2903,7 @@ namespace System.Data.Odbc // Note: copy-and pasted from internal DbCommandBuilder implementation // Note: Per definition (ODBC reference) the CatalogSeparator comes before and after the // catalog name, the SchemaSeparator is undefined. Does it come between Schema and Table? - internal static string[] ParseProcedureName(string name, string quotePrefix, string quoteSuffix) + internal static string?[] ParseProcedureName(string? name, string? quotePrefix, string? quoteSuffix) { // Procedure may consist of up to four parts: // 0) Server @@ -2906,7 +2916,7 @@ namespace System.Data.Odbc // const string Separator = "."; - string[] qualifiers = new string[4]; + string?[] qualifiers = new string[4]; if (!string.IsNullOrEmpty(name)) { bool useQuotes = !string.IsNullOrEmpty(quotePrefix) && !string.IsNullOrEmpty(quoteSuffix); @@ -2917,8 +2927,10 @@ namespace System.Data.Odbc int startPos = currentPos; // does the part begin with a quotePrefix? - if (useQuotes && (name.IndexOf(quotePrefix, currentPos, quotePrefix.Length, StringComparison.Ordinal) == currentPos)) + if (useQuotes && (name.IndexOf(quotePrefix!, currentPos, quotePrefix!.Length, StringComparison.Ordinal) == currentPos)) { + Debug.Assert(quotePrefix != null && quoteSuffix != null); + currentPos += quotePrefix.Length; // move past the quotePrefix // search for the quoteSuffix (or end of string) @@ -2978,7 +2990,7 @@ namespace System.Data.Odbc private sealed class MetaData { internal int ordinal; - internal TypeMap typemap; + internal TypeMap typemap = null!; // Lazy-initialized internal SQLLEN size; internal byte precision; @@ -2992,10 +3004,10 @@ namespace System.Data.Odbc internal bool isLong; internal bool isKeyColumn; - internal string baseSchemaName; - internal string baseCatalogName; - internal string baseTableName; - internal string baseColumnName; + internal string? baseSchemaName; + internal string? baseCatalogName; + internal string? baseTableName; + internal string? baseColumnName; } } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs index 76f363e..f6c0538 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironment.cs @@ -7,14 +7,14 @@ namespace System.Data.Odbc { internal sealed class OdbcEnvironment { - private static object s_globalEnvironmentHandle; + private static object? s_globalEnvironmentHandle; private static readonly object s_globalEnvironmentHandleLock = new object(); private OdbcEnvironment() { } // default const. internal static OdbcEnvironmentHandle GetGlobalEnvironmentHandle() { - OdbcEnvironmentHandle globalEnvironmentHandle = s_globalEnvironmentHandle as OdbcEnvironmentHandle; + OdbcEnvironmentHandle? globalEnvironmentHandle = s_globalEnvironmentHandle as OdbcEnvironmentHandle; if (null == globalEnvironmentHandle) { lock (s_globalEnvironmentHandleLock) @@ -32,10 +32,10 @@ namespace System.Data.Odbc internal static void ReleaseObjectPool() { - object globalEnvironmentHandle = Interlocked.Exchange(ref s_globalEnvironmentHandle, null); + object? globalEnvironmentHandle = Interlocked.Exchange(ref s_globalEnvironmentHandle, null); if (null != globalEnvironmentHandle) { - (globalEnvironmentHandle as OdbcEnvironmentHandle).Dispose(); // internally refcounted so will happen correctly + ((OdbcEnvironmentHandle)globalEnvironmentHandle).Dispose(); // internally refcounted so will happen correctly } } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcError.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcError.cs index 44a0f01..564089c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcError.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcError.cs @@ -11,9 +11,9 @@ namespace System.Data.Odbc internal string _message; internal string _state; internal int _nativeerror; - internal string _source; + internal string? _source; - internal OdbcError(string source, string message, string state, int nativeerror) + internal OdbcError(string? source, string message, string state, int nativeerror) { _source = source; _message = message; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcErrorCollection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcErrorCollection.cs index 60bbf1b..a94643c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcErrorCollection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcErrorCollection.cs @@ -37,7 +37,7 @@ namespace System.Data.Odbc { get { - return (OdbcError)_items[i]; + return (OdbcError)_items[i]!; } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcException.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcException.cs index 4725546..7a2f87e 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcException.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcException.cs @@ -37,7 +37,7 @@ namespace System.Data.Odbc private OdbcException(SerializationInfo si, StreamingContext sc) : base(si, sc) { // Ignoring ODBC32.RETCODE - _odbcErrors = (OdbcErrorCollection)si.GetValue("odbcErrors", typeof(OdbcErrorCollection)); + _odbcErrors = (OdbcErrorCollection)si.GetValue("odbcErrors", typeof(OdbcErrorCollection))!; HResult = HResults.OdbcException; } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs index 4936464..77900ae 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs @@ -12,9 +12,9 @@ namespace System.Data.Odbc internal abstract class OdbcHandle : SafeHandle { private readonly ODBC32.SQL_HANDLE _handleType; - private OdbcHandle _parentHandle; + private OdbcHandle? _parentHandle; - protected OdbcHandle(ODBC32.SQL_HANDLE handleType, OdbcHandle parentHandle) : base(IntPtr.Zero, true) + protected OdbcHandle(ODBC32.SQL_HANDLE handleType, OdbcHandle? parentHandle) : base(IntPtr.Zero, true) { _handleType = handleType; @@ -61,7 +61,7 @@ namespace System.Data.Odbc else { // without a handle, ReleaseHandle may not be called - parentHandle.DangerousRelease(); + parentHandle!.DangerousRelease(); } break; } @@ -164,7 +164,7 @@ namespace System.Data.Odbc // If we ended up getting released, then we have to release // our reference on our parent. - OdbcHandle parentHandle = _parentHandle; + OdbcHandle? parentHandle = _parentHandle; _parentHandle = null; if (null != parentHandle) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs index f56a53c..f8eefe7 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs @@ -49,7 +49,7 @@ namespace System.Data.Odbc new SchemaFunctionName(OdbcMetaDataCollectionNames.Views, ODBC32.SQL_API.SQLTABLES)}; // verify the existance of the table in the data set - DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; + DataTable? metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; if (metaDataCollectionsTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.MetaDataCollections); @@ -59,7 +59,7 @@ namespace System.Data.Odbc metaDataCollectionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.MetaDataCollections, null); // verify the existance of the table in the data set - DataTable restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; + DataTable? restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; if (restrictionsTable != null) { // copy the table filtering out any rows that don't apply to the current version of the provider @@ -72,13 +72,14 @@ namespace System.Data.Odbc // 3) the provider does not support the necessary odbc function - DataColumn populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]; - DataColumn collectionName = metaDataCollectionsTable.Columns[_collectionName]; - DataColumn restrictionCollectionName = null; + DataColumn populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]!; + DataColumn collectionName = metaDataCollectionsTable.Columns[_collectionName]!; + DataColumn? restrictionCollectionName = null; if (restrictionsTable != null) { restrictionCollectionName = restrictionsTable.Columns[_collectionName]; } + Debug.Assert(restrictionCollectionName != null); foreach (DataRow collection in metaDataCollectionsTable.Rows) { @@ -123,12 +124,12 @@ namespace System.Data.Odbc // replace the original table with the updated one metaDataCollectionsTable.AcceptChanges(); - CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]); + CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!); CollectionDataSet.Tables.Add(metaDataCollectionsTable); if (restrictionsTable != null) { - CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]); + CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]!); CollectionDataSet.Tables.Add(restrictionsTable); } } @@ -180,7 +181,7 @@ namespace System.Data.Odbc private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcDataReader dataReader, OdbcConnection connection) { - DataTable schemaTable = null; + DataTable? schemaTable = null; // // Build a DataTable from the reader @@ -195,25 +196,25 @@ namespace System.Data.Odbc object[] getTypeInfoValues = new object[schemaTable.Rows.Count]; DataRow dataTypesRow; - DataColumn typeNameColumn = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName]; - DataColumn providerDbTypeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType]; - DataColumn columnSizeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize]; - DataColumn createParametersColumn = dataTypesTable.Columns[DbMetaDataColumnNames.CreateParameters]; - DataColumn dataTypeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.DataType]; - DataColumn isAutoIncermentableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsAutoIncrementable]; - DataColumn isCaseSensitiveColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsCaseSensitive]; - DataColumn isFixedLengthColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength]; - DataColumn isFixedPrecisionScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedPrecisionScale]; - DataColumn isLongColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsLong]; - DataColumn isNullableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable]; - DataColumn isSearchableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable]; - DataColumn isSearchableWithLikeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchableWithLike]; - DataColumn isUnsignedColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsUnsigned]; - DataColumn maximumScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.MaximumScale]; - DataColumn minimumScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.MinimumScale]; - DataColumn literalPrefixColumn = dataTypesTable.Columns[DbMetaDataColumnNames.LiteralPrefix]; - DataColumn literalSuffixColumn = dataTypesTable.Columns[DbMetaDataColumnNames.LiteralSuffix]; - DataColumn SQLTypeNameColumn = dataTypesTable.Columns[OdbcMetaDataColumnNames.SQLType]; + DataColumn typeNameColumn = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName]!; + DataColumn providerDbTypeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType]!; + DataColumn columnSizeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize]!; + DataColumn createParametersColumn = dataTypesTable.Columns[DbMetaDataColumnNames.CreateParameters]!; + DataColumn dataTypeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.DataType]!; + DataColumn isAutoIncermentableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsAutoIncrementable]!; + DataColumn isCaseSensitiveColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsCaseSensitive]!; + DataColumn isFixedLengthColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength]!; + DataColumn isFixedPrecisionScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedPrecisionScale]!; + DataColumn isLongColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsLong]!; + DataColumn isNullableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable]!; + DataColumn isSearchableColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable]!; + DataColumn isSearchableWithLikeColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchableWithLike]!; + DataColumn isUnsignedColumn = dataTypesTable.Columns[DbMetaDataColumnNames.IsUnsigned]!; + DataColumn maximumScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.MaximumScale]!; + DataColumn minimumScaleColumn = dataTypesTable.Columns[DbMetaDataColumnNames.MinimumScale]!; + DataColumn literalPrefixColumn = dataTypesTable.Columns[DbMetaDataColumnNames.LiteralPrefix]!; + DataColumn literalSuffixColumn = dataTypesTable.Columns[DbMetaDataColumnNames.LiteralSuffix]!; + DataColumn SQLTypeNameColumn = dataTypesTable.Columns[OdbcMetaDataColumnNames.SQLType]!; const int indexTYPE_NAME = 0; @@ -234,7 +235,7 @@ namespace System.Data.Odbc const int SQL_DATE_V2 = 9; const int SQL_TIME_V2 = 10; - TypeMap typeMap; + TypeMap? typeMap; while (dataReader.Read()) @@ -247,11 +248,9 @@ namespace System.Data.Odbc dataTypesRow[typeNameColumn] = getTypeInfoValues[indexTYPE_NAME]; dataTypesRow[SQLTypeNameColumn] = getTypeInfoValues[indexDATA_TYPE]; - sqlType = (ODBC32.SQL_TYPE)(int)Convert.ChangeType(getTypeInfoValues[indexDATA_TYPE], - typeof(int), - (System.IFormatProvider)null); + sqlType = (ODBC32.SQL_TYPE)(int)Convert.ChangeType(getTypeInfoValues[indexDATA_TYPE], typeof(int), null); // if the driver is pre version 3 and it returned the v2 SQL_DATE or SQL_TIME types they need - // to be mapped to thier v3 equlivants + // to be mapped to their v3 equivalent if (connection.IsV3Driver == false) { if ((int)sqlType == SQL_DATE_V2) @@ -428,7 +427,7 @@ namespace System.Data.Odbc private DataTable DataTableFromDataReaderIndex(IDataReader reader, string tableName, - string restrictionIndexName) + string? restrictionIndexName) { // set up the column structure of the data table from the reader object[] values; @@ -499,7 +498,7 @@ namespace System.Data.Odbc return resultTable; } - private void FillOutRestrictions(int restrictionsCount, string[] restrictions, object[] allRestrictions, string collectionName) + private void FillOutRestrictions(int restrictionsCount, string?[]? restrictions, object?[] allRestrictions, string collectionName) { Debug.Assert(allRestrictions.Length >= restrictionsCount); @@ -530,11 +529,11 @@ namespace System.Data.Odbc } - private DataTable GetColumnsCollection(string[] restrictions, OdbcConnection connection) + private DataTable GetColumnsCollection(string?[]? restrictions, OdbcConnection connection) { - OdbcCommand command = null; - OdbcDataReader dataReader = null; - DataTable resultTable = null; + OdbcCommand? command = null; + OdbcDataReader? dataReader = null; + DataTable? resultTable = null; const int columnsRestrictionsCount = 4; try @@ -563,7 +562,7 @@ namespace System.Data.Odbc } - private DataTable GetDataSourceInformationCollection(string[] restrictions, + private DataTable GetDataSourceInformationCollection(string?[]? restrictions, OdbcConnection connection) { if (ADP.IsEmptyArray(restrictions) == false) @@ -572,7 +571,7 @@ namespace System.Data.Odbc } // verify that the data source information table is in the data set - DataTable dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; + DataTable? dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; if (dataSourceInformationTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataSourceInformation); @@ -588,7 +587,7 @@ namespace System.Data.Odbc } DataRow dataSourceInformation = dataSourceInformationTable.Rows[0]; - string stringValue; + string? stringValue; short int16Value; int int32Value; ODBC32.RetCode retcode; @@ -724,7 +723,7 @@ namespace System.Data.Odbc } // build the QuotedIdentifierPattern using the quote prefix and suffix from the provider and - // assuming that the quote suffix is escaped via repetion (i.e " becomes "") + // assuming that the quote suffix is escaped via repetition (i.e " becomes "") stringValue = connection.QuoteChar(ADP.GetSchema); if (stringValue != null) @@ -733,7 +732,7 @@ namespace System.Data.Odbc // quoted identifiers if (stringValue != " ") { - // only know how to build the parttern if the quote characters is 1 character + // only know how to build the pattern if the quote characters is 1 character // in all other cases just leave the field null if (stringValue.Length == 1) { @@ -782,7 +781,7 @@ namespace System.Data.Odbc } - private DataTable GetDataTypesCollection(string[] restrictions, OdbcConnection connection) + private DataTable GetDataTypesCollection(string?[]? restrictions, OdbcConnection connection) { if (ADP.IsEmptyArray(restrictions) == false) { @@ -792,7 +791,7 @@ namespace System.Data.Odbc // verify the existance of the table in the data set - DataTable dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; + DataTable? dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; if (dataTypesTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes); @@ -801,8 +800,8 @@ namespace System.Data.Odbc // copy the data table it dataTypesTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataTypes, null); - OdbcCommand command = null; - OdbcDataReader dataReader = null; + OdbcCommand? command = null; + OdbcDataReader? dataReader = null; object[] allArguments = new object[1]; allArguments[0] = ODBC32.SQL_ALL_TYPES; @@ -831,11 +830,11 @@ namespace System.Data.Odbc return dataTypesTable; } - private DataTable GetIndexCollection(string[] restrictions, OdbcConnection connection) + private DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection connection) { - OdbcCommand command = null; - OdbcDataReader dataReader = null; - DataTable resultTable = null; + OdbcCommand? command = null; + OdbcDataReader? dataReader = null; + DataTable? resultTable = null; const int nativeRestrictionsCount = 5; const int indexRestrictionsCount = 4; const int indexOfTableName = 2; @@ -857,7 +856,7 @@ namespace System.Data.Odbc dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLSTATISTICS); - string indexName = null; + string? indexName = null; if (restrictions != null) { if (restrictions.Length >= indexOfIndexName + 1) @@ -885,11 +884,11 @@ namespace System.Data.Odbc return resultTable; } - private DataTable GetProcedureColumnsCollection(string[] restrictions, OdbcConnection connection, bool isColumns) + private DataTable GetProcedureColumnsCollection(string?[]? restrictions, OdbcConnection connection, bool isColumns) { - OdbcCommand command = null; - OdbcDataReader dataReader = null; - DataTable resultTable = null; + OdbcCommand? command = null; + OdbcDataReader? dataReader = null; + DataTable? resultTable = null; const int procedureColumnsRestrictionsCount = 4; try @@ -928,18 +927,18 @@ namespace System.Data.Odbc return resultTable; } - private DataTable GetProceduresCollection(string[] restrictions, OdbcConnection connection) + private DataTable GetProceduresCollection(string?[]? restrictions, OdbcConnection connection) { - OdbcCommand command = null; - OdbcDataReader dataReader = null; - DataTable resultTable = null; + OdbcCommand? command = null; + OdbcDataReader? dataReader = null; + DataTable? resultTable = null; const int columnsRestrictionsCount = 4; const int indexOfProcedureType = 3; try { command = GetCommand(connection); - string[] allRestrictions = new string[columnsRestrictionsCount]; + string?[] allRestrictions = new string[columnsRestrictionsCount]; FillOutRestrictions(columnsRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Procedures); @@ -952,7 +951,7 @@ namespace System.Data.Odbc else { short procedureType; - if ((restrictions[indexOfProcedureType] == "SQL_PT_UNKNOWN") || + if ((restrictions![indexOfProcedureType] == "SQL_PT_UNKNOWN") || (restrictions[indexOfProcedureType] == "0" /*ODBC32.SQL_PROCEDURETYPE.UNKNOWN*/)) { procedureType = (short)ODBC32.SQL_PROCEDURETYPE.UNKNOWN; @@ -990,7 +989,7 @@ namespace System.Data.Odbc return resultTable; } - private DataTable GetReservedWordsCollection(string[] restrictions, OdbcConnection connection) + private DataTable GetReservedWordsCollection(string?[]? restrictions, OdbcConnection connection) { if (ADP.IsEmptyArray(restrictions) == false) { @@ -998,7 +997,7 @@ namespace System.Data.Odbc } // verify the existance of the table in the data set - DataTable reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; + DataTable? reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; if (reservedWordsTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); @@ -1007,13 +1006,13 @@ namespace System.Data.Odbc // copy the table filtering out any rows that don't apply to tho current version of the prrovider reservedWordsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.ReservedWords, null); - DataColumn reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; + DataColumn? reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; if (reservedWordColumn == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); } - string keywords = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.KEYWORDS); + string? keywords = connection.GetInfoStringUnhandled(ODBC32.SQL_INFO.KEYWORDS); if (null != keywords) { @@ -1031,11 +1030,11 @@ namespace System.Data.Odbc return reservedWordsTable; } - private DataTable GetTablesCollection(string[] restrictions, OdbcConnection connection, bool isTables) + private DataTable GetTablesCollection(string?[]? restrictions, OdbcConnection connection, bool isTables) { - OdbcCommand command = null; - OdbcDataReader dataReader = null; - DataTable resultTable = null; + OdbcCommand? command = null; + OdbcDataReader? dataReader = null; + DataTable? resultTable = null; const int tablesRestrictionsCount = 3; const string includedTableTypesTables = "TABLE,SYSTEM TABLE"; const string includedTableTypesViews = "VIEW"; @@ -1081,7 +1080,7 @@ namespace System.Data.Odbc } private bool IncludeIndexRow(object rowIndexName, - string restrictionIndexName, + string? restrictionIndexName, short rowIndexType) { // never include table statictics rows @@ -1112,9 +1111,9 @@ namespace System.Data.Odbc return resultTable; } - protected override DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection) + protected override DataTable PrepareCollection(string collectionName, string?[]? restrictions, DbConnection connection) { - DataTable resultTable = null; + DataTable? resultTable = null; OdbcConnection odbcConnection = (OdbcConnection)connection; if (collectionName == OdbcMetaDataCollectionNames.Tables) diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs index 23d65eb..08c95dc 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs @@ -5,6 +5,7 @@ using System.ComponentModel; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Text; @@ -32,10 +33,10 @@ namespace System.Data.Odbc // Bind: Bind may change _bindtype if the type is not supported through the driver // - private TypeMap _typemap; - private TypeMap _bindtype; + private TypeMap? _typemap; + private TypeMap? _bindtype; - private string _parameterName; + private string? _parameterName; private byte _precision; private byte _scale; private bool _hasScale; @@ -47,7 +48,7 @@ namespace System.Data.Odbc private int _boundScale; private IntPtr _boundBuffer; private IntPtr _boundIntbuffer; - private TypeMap _originalbindtype; // the original type in case we had to change the bindtype + private TypeMap? _originalbindtype; // the original type in case we had to change the bindtype // (e.g. decimal to string) private byte _internalPrecision; private bool _internalShouldSerializeSize; @@ -56,12 +57,12 @@ namespace System.Data.Odbc private byte _internalScale; private int _internalOffset; internal bool _internalUserSpecifiedType; - private object _internalValue; + private object? _internalValue; private int _preparedOffset; private int _preparedSize; private int _preparedBufferSize; - private object _preparedValue; + private object? _preparedValue; private int _preparedIntOffset; private int _preparedValueOffset; @@ -72,26 +73,26 @@ namespace System.Data.Odbc // uses System.Threading! } - public OdbcParameter(string name, object value) : this() + public OdbcParameter(string? name, object? value) : this() { ParameterName = name; Value = value; } - public OdbcParameter(string name, OdbcType type) : this() + public OdbcParameter(string? name, OdbcType type) : this() { ParameterName = name; OdbcType = type; } - public OdbcParameter(string name, OdbcType type, int size) : this() + public OdbcParameter(string? name, OdbcType type, int size) : this() { ParameterName = name; OdbcType = type; Size = size; } - public OdbcParameter(string name, OdbcType type, int size, string sourcecolumn) : this() + public OdbcParameter(string? name, OdbcType type, int size, string? sourcecolumn) : this() { ParameterName = name; OdbcType = type; @@ -101,16 +102,16 @@ namespace System.Data.Odbc [EditorBrowsableAttribute(EditorBrowsableState.Advanced)] // MDAC 69508 - public OdbcParameter(string parameterName, + public OdbcParameter(string? parameterName, OdbcType odbcType, int size, ParameterDirection parameterDirection, bool isNullable, byte precision, byte scale, - string srcColumn, + string? srcColumn, DataRowVersion srcVersion, - object value + object? value ) : this() { // V1.0 everything this.ParameterName = parameterName; @@ -126,12 +127,12 @@ namespace System.Data.Odbc } [EditorBrowsableAttribute(EditorBrowsableState.Advanced)] // MDAC 69508 - public OdbcParameter(string parameterName, + public OdbcParameter(string? parameterName, OdbcType odbcType, int size, ParameterDirection parameterDirection, byte precision, byte scale, - string sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, - object value) : this() + string? sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, + object? value) : this() { // V2.0 everything - round trip all browsable properties + precision/scale this.ParameterName = parameterName; this.OdbcType = odbcType; @@ -151,7 +152,7 @@ namespace System.Data.Odbc { if (_userSpecifiedType) { - return _typemap._dbType; + return _typemap!._dbType; } return TypeMap._NVarChar._dbType; // default type } @@ -181,7 +182,7 @@ namespace System.Data.Odbc { if (_userSpecifiedType) { - return _typemap._odbcType; + return _typemap!._odbcType; } return TypeMap._NVarChar._odbcType; // default type } @@ -219,11 +220,12 @@ namespace System.Data.Odbc } } + [AllowNull] public override string ParameterName { // V1.2.3300, XXXParameter V1.0.3300 get { - string parameterName = _parameterName; + string? parameterName = _parameterName; return ((null != parameterName) ? parameterName : string.Empty); } set @@ -314,16 +316,16 @@ namespace System.Data.Odbc } // returns the count of bytes for the data (ColumnSize argument to SqlBindParameter) - private int GetColumnSize(object value, int offset, int ordinal) + private int GetColumnSize(object? value, int offset, int ordinal) { - if ((ODBC32.SQL_C.NUMERIC == _bindtype._sql_c) && (0 != _internalPrecision)) + if ((ODBC32.SQL_C.NUMERIC == _bindtype!._sql_c) && (0 != _internalPrecision)) { return Math.Min((int)_internalPrecision, ADP.DecimalMaxPrecision); } int cch = _bindtype._columnSize; if (0 >= cch) { - if (ODBC32.SQL_C.NUMERIC == _typemap._sql_c) + if (ODBC32.SQL_C.NUMERIC == _typemap!._sql_c) { cch = 62; // (DecimalMaxPrecision+sign+terminator)*BytesPerUnicodeCharacter } @@ -414,9 +416,9 @@ namespace System.Data.Odbc // Return the count of bytes for the data (size in bytes for the native buffer) // - private int GetValueSize(object value, int offset) + private int GetValueSize(object? value, int offset) { - if ((ODBC32.SQL_C.NUMERIC == _bindtype._sql_c) && (0 != _internalPrecision)) + if ((ODBC32.SQL_C.NUMERIC == _bindtype!._sql_c) && (0 != _internalPrecision)) { return Math.Min((int)_internalPrecision, ADP.DecimalMaxPrecision); } @@ -457,12 +459,12 @@ namespace System.Data.Odbc // return the count of bytes for the data, used for SQLBindParameter // - private int GetParameterSize(object value, int offset, int ordinal) + private int GetParameterSize(object? value, int offset, int ordinal) { - int ccb = _bindtype._bufferSize; + int ccb = _bindtype!._bufferSize; if (0 >= ccb) { - if (ODBC32.SQL_C.NUMERIC == _typemap._sql_c) + if (ODBC32.SQL_C.NUMERIC == _typemap!._sql_c) { ccb = 518; // _bindtype would be VarChar ([0-9]?{255} + '-' + '.') * 2 } @@ -529,7 +531,7 @@ namespace System.Data.Odbc return ccb; } - private byte GetParameterPrecision(object value) + private byte GetParameterPrecision(object? value) { if (0 != _internalPrecision && value is decimal) { @@ -556,7 +558,7 @@ namespace System.Data.Odbc } - private byte GetParameterScale(object value) + private byte GetParameterScale(object? value) { // For any value that is not decimal simply return the Scale // @@ -618,11 +620,13 @@ namespace System.Data.Odbc internal void PrepareForBind(OdbcCommand command, short ordinal, ref int parameterBufferSize) { + Debug.Assert(command.Connection != null); + // make a snapshot of the current properties. Properties may change while we work on them // CopyParameterInternal(); - object value = ProcessAndGetParameterValue(); + object? value = ProcessAndGetParameterValue(); int offset = _internalOffset; int size = _internalSize; ODBC32.SQL_C sql_c_type; @@ -663,7 +667,7 @@ namespace System.Data.Odbc // type support verification for certain data types // - switch (_bindtype._sql_type) + switch (_bindtype!._sql_type) { case ODBC32.SQL_TYPE.DECIMAL: case ODBC32.SQL_TYPE.NUMERIC: @@ -703,7 +707,7 @@ namespace System.Data.Odbc case ODBC32.SQL_TYPE.WLONGVARCHAR: if (value is char) { - value = value.ToString(); + value = value.ToString()!; size = ((string)value).Length; offset = 0; } @@ -739,7 +743,7 @@ namespace System.Data.Odbc int lcid = System.Globalization.CultureInfo.CurrentCulture.LCID; CultureInfo culInfo = new CultureInfo(lcid); Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage); - value = cpe.GetBytes(value.ToString()); + value = cpe.GetBytes(value.ToString()!); size = ((byte[])value).Length; } } @@ -786,13 +790,15 @@ namespace System.Data.Odbc internal void Bind(OdbcStatementHandle hstmt, OdbcCommand command, short ordinal, CNativeBuffer parameterBuffer, bool allowReentrance) { + Debug.Assert(command.Connection != null); + ODBC32.RetCode retcode; ODBC32.SQL_C sql_c_type = _prepared_Sql_C_Type; ODBC32.SQL_PARAM sqldirection = SqlDirectionFromParameterDirection(); int offset = _preparedOffset; int size = _preparedSize; - object value = _preparedValue; + object? value = _preparedValue; int cbValueSize = GetValueSize(value, offset); // count of bytes for the data int cchSize = GetColumnSize(value, offset, ordinal); // count of bytes for the data, used to allocate the buffer length byte precision = GetParameterPrecision(value); @@ -843,7 +849,7 @@ namespace System.Data.Odbc if (!_hasChanged && (_boundSqlCType == sql_c_type) - && (_boundParameterType == _bindtype._sql_type) + && (_boundParameterType == _bindtype!._sql_type) && (_boundSize == cchSize) && (_boundScale == scale) && (_boundBuffer == valueBuffer.Handle) @@ -858,7 +864,7 @@ namespace System.Data.Odbc ordinal, // Parameter Number (short)sqldirection, // InputOutputType sql_c_type, // ValueType - _bindtype._sql_type, // ParameterType + _bindtype!._sql_type, // ParameterType (IntPtr)cchSize, // ColumnSize (IntPtr)scale, // DecimalDigits valueBuffer, // ParameterValuePtr @@ -968,7 +974,7 @@ namespace System.Data.Odbc } } - if ((typemap != _typemap) && (null != Value) && !Convert.IsDBNull(Value) && (Value.GetType() != _typemap._type)) + if ((typemap != _typemap) && (null != Value) && !Convert.IsDBNull(Value) && (Value.GetType() != _typemap!._type)) { Debug.Assert(ODBC32.SQL_C.NUMERIC == _typemap._sql_c, "unexpected"); Value = decimal.Parse((string)Value, System.Globalization.CultureInfo.CurrentCulture); @@ -977,9 +983,9 @@ namespace System.Data.Odbc } } - private object ProcessAndGetParameterValue() + private object? ProcessAndGetParameterValue() { - object value = _internalValue; + object? value = _internalValue; if (_internalUserSpecifiedType) { if ((null != value) && !Convert.IsDBNull(value)) @@ -987,11 +993,11 @@ namespace System.Data.Odbc Type valueType = value.GetType(); if (!valueType.IsArray) { - if (valueType != _typemap._type) + if (valueType != _typemap!._type) { try { - value = Convert.ChangeType(value, _typemap._type, (System.IFormatProvider)null); + value = Convert.ChangeType(value, _typemap._type, null); } catch (Exception e) { @@ -1040,7 +1046,7 @@ namespace System.Data.Odbc //CoercedValue = null; } - internal void SetInputValue(object value, ODBC32.SQL_C sql_c_type, int cbsize, int sizeorprecision, int offset, CNativeBuffer parameterBuffer) + internal void SetInputValue(object? value, ODBC32.SQL_C sql_c_type, int cbsize, int sizeorprecision, int offset, CNativeBuffer parameterBuffer) { //Handle any input params if ((ParameterDirection.Input == _internalDirection) || (ParameterDirection.InputOutput == _internalDirection)) { @@ -1105,7 +1111,7 @@ namespace System.Data.Odbc } } - public override object Value + public override object? Value { // V1.2.3300, XXXParameter V1.0.3300 get { @@ -1118,17 +1124,17 @@ namespace System.Data.Odbc } } - private byte ValuePrecision(object value) + private byte ValuePrecision(object? value) { return ValuePrecisionCore(value); } - private byte ValueScale(object value) + private byte ValueScale(object? value) { return ValueScaleCore(value); } - private int ValueSize(object value) + private int ValueSize(object? value) { return ValueSizeCore(value); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollection.cs index b84fac3..d86b6d3 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollection.cs @@ -63,29 +63,29 @@ namespace System.Data.Odbc [EditorBrowsableAttribute(EditorBrowsableState.Never)] [ObsoleteAttribute("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). https://go.microsoft.com/fwlink/?linkid=14202", false)] // 79027 - public OdbcParameter Add(string parameterName, object value) + public OdbcParameter Add(string? parameterName, object? value) { // MDAC 59206 return Add(new OdbcParameter(parameterName, value)); } - public OdbcParameter AddWithValue(string parameterName, object value) + public OdbcParameter AddWithValue(string? parameterName, object? value) { // MDAC 79027 return Add(new OdbcParameter(parameterName, value)); } - public OdbcParameter Add(string parameterName, OdbcType odbcType) + public OdbcParameter Add(string? parameterName, OdbcType odbcType) { return Add(new OdbcParameter(parameterName, odbcType)); } - public OdbcParameter Add(string parameterName, OdbcType odbcType, int size) + public OdbcParameter Add(string? parameterName, OdbcType odbcType, int size) { return Add(new OdbcParameter(parameterName, odbcType, size)); } - public OdbcParameter Add(string parameterName, OdbcType odbcType, int size, string sourceColumn) + public OdbcParameter Add(string? parameterName, OdbcType odbcType, int size, string? sourceColumn) { return Add(new OdbcParameter(parameterName, odbcType, size, sourceColumn)); } @@ -102,7 +102,7 @@ namespace System.Data.Odbc { for (int i = 0; i < Count; ++i) { - this[i].Bind(cmdWrapper.StatementHandle, command, checked((short)(i + 1)), parameterBuffer, true); + this[i].Bind(cmdWrapper.StatementHandle!, command, checked((short)(i + 1)), parameterBuffer, true); } _rebindCollection = false; } @@ -160,7 +160,7 @@ namespace System.Data.Odbc // mdac 88542 - we will not read out the parameters if the collection has changed if (!_rebindCollection) { - CNativeBuffer parameterBuffer = cmdWrapper._nativeParameterBuffer; + CNativeBuffer parameterBuffer = cmdWrapper._nativeParameterBuffer!; for (int i = 0; i < Count; ++i) { this[i].GetOutputValue(parameterBuffer); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs index 668a4ae..671b509 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterCollectionHelper.cs @@ -10,7 +10,7 @@ namespace System.Data.Odbc { public sealed partial class OdbcParameterCollection : DbParameterCollection { - private List _items; + private List? _items; public override int Count { @@ -24,7 +24,7 @@ namespace System.Data.Odbc { get { - List items = _items; + List? items = _items; if (null == items) { @@ -297,7 +297,7 @@ namespace System.Data.Odbc throw ADP.ParameterNull(nameof(value), this, s_itemType); } - object parent = ((OdbcParameter)value).CompareExchangeParent(this, null); + object? parent = ((OdbcParameter)value).CompareExchangeParent(this, null); if (null != parent) { if (this != parent) diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs index 0173da3..60634ace 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs @@ -2,25 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Data.Common; +using System.Diagnostics.CodeAnalysis; namespace System.Data.Odbc { public sealed partial class OdbcParameter : DbParameter { - private object _value; + private object? _value; - private object _parent; + private object? _parent; private ParameterDirection _direction; private int _size; private int _offset; - private string _sourceColumn; + private string? _sourceColumn; private DataRowVersion _sourceVersion; private bool _sourceColumnNullMapping; private bool _isNullable; - private object _coercedValue; + private object? _coercedValue; private OdbcParameter(OdbcParameter source) : this() // V1.2.3300, Clone { @@ -28,14 +29,13 @@ namespace System.Data.Odbc source.CloneHelper(this); - ICloneable cloneable = (_value as ICloneable); - if (null != cloneable) + if (_value is ICloneable cloneable) { // MDAC 49322 _value = cloneable.Clone(); } } - private object CoercedValue + private object? CoercedValue { get { @@ -134,11 +134,12 @@ namespace System.Data.Odbc return (0 != _size); } + [AllowNull] public override string SourceColumn { get { - string sourceColumn = _sourceColumn; + string? sourceColumn = _sourceColumn; return ((null != sourceColumn) ? sourceColumn : string.Empty); } set @@ -195,9 +196,9 @@ namespace System.Data.Odbc destination._isNullable = _isNullable; } - internal object CompareExchangeParent(object value, object comparand) + internal object? CompareExchangeParent(object? value, object? comparand) { - object parent = _parent; + object? parent = _parent; if (comparand == parent) { _parent = value; @@ -215,7 +216,7 @@ namespace System.Data.Odbc return ParameterName; } - private byte ValuePrecisionCore(object value) + private byte ValuePrecisionCore(object? value) { if (value is decimal) { @@ -224,7 +225,7 @@ namespace System.Data.Odbc return 0; } - private byte ValueScaleCore(object value) + private byte ValueScaleCore(object? value) { if (value is decimal) { @@ -233,29 +234,19 @@ namespace System.Data.Odbc return 0; } - private int ValueSizeCore(object value) + private int ValueSizeCore(object? value) { if (!ADP.IsNull(value)) { - string svalue = (value as string); - if (null != svalue) + return value switch { - return svalue.Length; - } - byte[] bvalue = (value as byte[]); - if (null != bvalue) - { - return bvalue.Length; - } - char[] cvalue = (value as char[]); - if (null != cvalue) - { - return cvalue.Length; - } - if ((value is byte) || (value is char)) - { - return 1; - } + string svalue => svalue.Length, + byte[] bvalue => bvalue.Length, + char[] cvalue => cvalue.Length, + byte _ => 1, + char _ => 1, + _ => 0 + }; } return 0; } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcRowUpdatingEvent.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcRowUpdatingEvent.cs index 61da7ce..05f6e51 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcRowUpdatingEvent.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcRowUpdatingEvent.cs @@ -19,12 +19,12 @@ namespace System.Data.Odbc ///////////////////////////////////////////////////////////////////////// public sealed class OdbcRowUpdatingEventArgs : RowUpdatingEventArgs { - public OdbcRowUpdatingEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + public OdbcRowUpdatingEventArgs(DataRow row, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) : base(row, command, statementType, tableMapping) { } - public new OdbcCommand Command + public new OdbcCommand? Command { get { return (base.Command as OdbcCommand); } set @@ -33,7 +33,7 @@ namespace System.Data.Odbc } } - protected override IDbCommand BaseCommand + protected override IDbCommand? BaseCommand { get { return base.BaseCommand; } set { base.BaseCommand = (value as OdbcCommand); } @@ -46,14 +46,14 @@ namespace System.Data.Odbc ///////////////////////////////////////////////////////////////////////// public sealed class OdbcRowUpdatedEventArgs : RowUpdatedEventArgs { - public OdbcRowUpdatedEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + public OdbcRowUpdatedEventArgs(DataRow row, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) : base(row, command, statementType, tableMapping) { } - public new OdbcCommand Command + public new OdbcCommand? Command { - get { return (OdbcCommand)base.Command; } + get { return (OdbcCommand?)base.Command; } } } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcStatementHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcStatementHandle.cs index dba62ed..11d970c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcStatementHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcStatementHandle.cs @@ -62,7 +62,7 @@ namespace System.Data.Odbc internal sealed class OdbcStatementHandle : OdbcHandle { - internal OdbcStatementHandle(OdbcConnectionHandle connectionHandle) : base(ODBC32.SQL_HANDLE.STMT, connectionHandle) + internal OdbcStatementHandle(OdbcConnectionHandle? connectionHandle) : base(ODBC32.SQL_HANDLE.STMT, connectionHandle) { } @@ -215,7 +215,7 @@ namespace System.Data.Odbc return retcode; } - internal ODBC32.RetCode PrimaryKeys(string catalogName, string schemaName, string tableName) + internal ODBC32.RetCode PrimaryKeys(string? catalogName, string? schemaName, string tableName) { ODBC32.RetCode retcode = Interop.Odbc.SQLPrimaryKeysW(this, catalogName, ODBC.ShortStringLength(catalogName), // CatalogName @@ -242,10 +242,10 @@ namespace System.Data.Odbc return retcode; } - internal ODBC32.RetCode ProcedureColumns(string procedureCatalog, - string procedureSchema, - string procedureName, - string columnName) + internal ODBC32.RetCode ProcedureColumns(string? procedureCatalog, + string? procedureSchema, + string? procedureName, + string? columnName) { ODBC32.RetCode retcode = Interop.Odbc.SQLProcedureColumnsW(this, procedureCatalog, @@ -287,8 +287,8 @@ namespace System.Data.Odbc return retcode; } - internal ODBC32.RetCode Statistics(string tableCatalog, - string tableSchema, + internal ODBC32.RetCode Statistics(string? tableCatalog, + string? tableSchema, string tableName, short unique, short accuracy) diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs index 38ae74d..aceee7e 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcTransaction.cs @@ -7,9 +7,9 @@ namespace System.Data.Odbc { public sealed class OdbcTransaction : DbTransaction { - private OdbcConnection _connection; + private OdbcConnection? _connection; private IsolationLevel _isolevel = IsolationLevel.Unspecified; - private OdbcConnectionHandle _handle; + private OdbcConnectionHandle? _handle; internal OdbcTransaction(OdbcConnection connection, IsolationLevel isolevel, OdbcConnectionHandle handle) { @@ -18,7 +18,7 @@ namespace System.Data.Odbc _handle = handle; } - public new OdbcConnection Connection + public new OdbcConnection? Connection { // MDAC 66655 get { @@ -26,7 +26,7 @@ namespace System.Data.Odbc } } - protected override DbConnection DbConnection + protected override DbConnection? DbConnection { // MDAC 66655 get { @@ -38,7 +38,7 @@ namespace System.Data.Odbc { get { - OdbcConnection connection = _connection; + OdbcConnection? connection = _connection; if (null == connection) { throw ADP.TransactionZombied(this); @@ -67,7 +67,7 @@ namespace System.Data.Odbc public override void Commit() { - OdbcConnection connection = _connection; + OdbcConnection? connection = _connection; if (null == connection) { throw ADP.TransactionZombied(this); @@ -76,7 +76,7 @@ namespace System.Data.Odbc connection.CheckState(ADP.CommitTransaction); // MDAC 68289 //Note: SQLEndTran success if not actually in a transaction, so we have to throw - //since the IDbTransaciton spec indicates this is an error for the managed packages + //since the IDbTransaction spec indicates this is an error for the managed packages if (null == _handle) { throw ODBC.NotInTransaction(); @@ -100,7 +100,7 @@ namespace System.Data.Odbc { if (disposing) { - OdbcConnectionHandle handle = _handle; + OdbcConnectionHandle? handle = _handle; _handle = null; if (null != handle) { @@ -112,7 +112,7 @@ namespace System.Data.Odbc //don't throw an exception here, but trace it so it can be logged if (_connection != null) { - Exception e = _connection.HandleErrorNoThrow(handle, retcode); + Exception e = _connection.HandleErrorNoThrow(handle, retcode)!; ADP.TraceExceptionWithoutRethrow(e); } } @@ -141,7 +141,7 @@ namespace System.Data.Odbc public override void Rollback() { - OdbcConnection connection = _connection; + OdbcConnection? connection = _connection; if (null == connection) { throw ADP.TransactionZombied(this); @@ -149,7 +149,7 @@ namespace System.Data.Odbc connection.CheckState(ADP.RollbackTransaction); // MDAC 68289 //Note: SQLEndTran success if not actually in a transaction, so we have to throw - //since the IDbTransaciton spec indicates this is an error for the managed packages + //since the IDbTransaction spec indicates this is an error for the managed packages if (null == _handle) { throw ODBC.NotInTransaction(); diff --git a/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs b/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs index 76a78d3..7ad5fdf 100644 --- a/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs +++ b/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs @@ -9,21 +9,21 @@ namespace System.Data.OleDb public sealed partial class OleDbCommand : System.Data.Common.DbCommand, System.Data.IDbCommand, System.ICloneable, System.IDisposable { public OleDbCommand() { } - public OleDbCommand(string cmdText) { } - public OleDbCommand(string cmdText, System.Data.OleDb.OleDbConnection connection) { } - public OleDbCommand(string cmdText, System.Data.OleDb.OleDbConnection connection, System.Data.OleDb.OleDbTransaction transaction) { } + public OleDbCommand(string? cmdText) { } + public OleDbCommand(string? cmdText, System.Data.OleDb.OleDbConnection? connection) { } + public OleDbCommand(string? cmdText, System.Data.OleDb.OleDbConnection? connection, System.Data.OleDb.OleDbTransaction? transaction) { } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] - public override string CommandText { get { throw null; } set { } } + public override string? CommandText { get { throw null; } set { } } public override int CommandTimeout { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.CommandType.Text)] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public override System.Data.CommandType CommandType { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] - public new System.Data.OleDb.OleDbConnection Connection { get { throw null; } set { } } - protected override System.Data.Common.DbConnection DbConnection { get { throw null; } set { } } + public new System.Data.OleDb.OleDbConnection? Connection { get { throw null; } set { } } + protected override System.Data.Common.DbConnection? DbConnection { get { throw null; } set { } } protected override System.Data.Common.DbParameterCollection DbParameterCollection { get { throw null; } } - protected override System.Data.Common.DbTransaction DbTransaction { get { throw null; } set { } } + protected override System.Data.Common.DbTransaction? DbTransaction { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(true)] [System.ComponentModel.DesignOnlyAttribute(true)] @@ -32,7 +32,7 @@ namespace System.Data.OleDb public new System.Data.OleDb.OleDbParameterCollection Parameters { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public new System.Data.OleDb.OleDbTransaction Transaction { get { throw null; } set { } } + public new System.Data.OleDb.OleDbTransaction? Transaction { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.UpdateRowSource.Both)] public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } } public override void Cancel() { } @@ -44,7 +44,7 @@ namespace System.Data.OleDb public override int ExecuteNonQuery() { throw null; } public new System.Data.OleDb.OleDbDataReader ExecuteReader() { throw null; } public new System.Data.OleDb.OleDbDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; } - public override object ExecuteScalar() { throw null; } + public override object? ExecuteScalar() { throw null; } public override void Prepare() { } public void ResetCommandTimeout() { } System.Data.IDataReader System.Data.IDbCommand.ExecuteReader() { throw null; } @@ -54,9 +54,9 @@ namespace System.Data.OleDb public sealed partial class OleDbCommandBuilder : System.Data.Common.DbCommandBuilder { public OleDbCommandBuilder() { } - public OleDbCommandBuilder(System.Data.OleDb.OleDbDataAdapter adapter) { } + public OleDbCommandBuilder(System.Data.OleDb.OleDbDataAdapter? adapter) { } [System.ComponentModel.DefaultValueAttribute(null)] - public new System.Data.OleDb.OleDbDataAdapter DataAdapter { get { throw null; } set { } } + public new System.Data.OleDb.OleDbDataAdapter? DataAdapter { get { throw null; } set { } } protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { } public static void DeriveParameters(System.Data.OleDb.OleDbCommand command) { } public new System.Data.OleDb.OleDbCommand GetDeleteCommand() { throw null; } @@ -78,11 +78,12 @@ namespace System.Data.OleDb public sealed partial class OleDbConnection : System.Data.Common.DbConnection, System.Data.IDbConnection, System.ICloneable, System.IDisposable { public OleDbConnection() { } - public OleDbConnection(string connectionString) { } + public OleDbConnection(string? connectionString) { } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.RecommendedAsConfigurableAttribute(true)] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.ComponentModel.SettingsBindableAttribute(true)] + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string ConnectionString { get { throw null; } set { } } [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override int ConnectionTimeout { get { throw null; } } @@ -97,7 +98,7 @@ namespace System.Data.OleDb [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override System.Data.ConnectionState State { get { throw null; } } - public event System.Data.OleDb.OleDbInfoMessageEventHandler InfoMessage { add { } remove { } } + public event System.Data.OleDb.OleDbInfoMessageEventHandler? InfoMessage { add { } remove { } } protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; } public new System.Data.OleDb.OleDbTransaction BeginTransaction() { throw null; } public new System.Data.OleDb.OleDbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) { throw null; } @@ -106,11 +107,11 @@ namespace System.Data.OleDb public new System.Data.OleDb.OleDbCommand CreateCommand() { throw null; } protected override System.Data.Common.DbCommand CreateDbCommand() { throw null; } protected override void Dispose(bool disposing) { } - public override void EnlistTransaction(System.Transactions.Transaction transaction) { } - public System.Data.DataTable GetOleDbSchemaTable(System.Guid schema, object[] restrictions) { throw null; } + public override void EnlistTransaction(System.Transactions.Transaction? transaction) { } + public System.Data.DataTable GetOleDbSchemaTable(System.Guid schema, object?[]? restrictions) { throw null; } public override System.Data.DataTable GetSchema() { throw null; } public override System.Data.DataTable GetSchema(string collectionName) { throw null; } - public override System.Data.DataTable GetSchema(string collectionName, string[] restrictionValues) { throw null; } + public override System.Data.DataTable GetSchema(string collectionName, string?[]? restrictionValues) { throw null; } public override void Open() { } public static void ReleaseObjectPool() { } public void ResetState() { } @@ -121,13 +122,14 @@ namespace System.Data.OleDb public sealed partial class OleDbConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder { public OleDbConnectionStringBuilder() { } - public OleDbConnectionStringBuilder(string connectionString) { } + public OleDbConnectionStringBuilder(string? connectionString) { } [System.ComponentModel.DisplayNameAttribute("Data Source")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string DataSource { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("File Name")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string FileName { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override object this[string keyword] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } [System.ComponentModel.DisplayNameAttribute("Persist Security Info")] @@ -136,28 +138,28 @@ namespace System.Data.OleDb public override void Clear() { } public override bool ContainsKey(string keyword) { throw null; } public override bool Remove(string keyword) { throw null; } - public override bool TryGetValue(string keyword, out object value) { throw null; } + public override bool TryGetValue(string keyword, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out object? value) { throw null; } } public sealed partial class OleDbDataAdapter : System.Data.Common.DbDataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable { public OleDbDataAdapter() { } - public OleDbDataAdapter(System.Data.OleDb.OleDbCommand selectCommand) { } - public OleDbDataAdapter(string selectCommandText, System.Data.OleDb.OleDbConnection selectConnection) { } - public OleDbDataAdapter(string selectCommandText, string selectConnectionString) { } + public OleDbDataAdapter(System.Data.OleDb.OleDbCommand? selectCommand) { } + public OleDbDataAdapter(string? selectCommandText, System.Data.OleDb.OleDbConnection? selectConnection) { } + public OleDbDataAdapter(string? selectCommandText, string? selectConnectionString) { } [System.ComponentModel.DefaultValueAttribute(null)] - public new System.Data.OleDb.OleDbCommand DeleteCommand { get { throw null; } set { } } + public new System.Data.OleDb.OleDbCommand? DeleteCommand { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] - public new System.Data.OleDb.OleDbCommand InsertCommand { get { throw null; } set { } } + public new System.Data.OleDb.OleDbCommand? InsertCommand { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] - public new System.Data.OleDb.OleDbCommand SelectCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } + public new System.Data.OleDb.OleDbCommand? SelectCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] - public new System.Data.OleDb.OleDbCommand UpdateCommand { get { throw null; } set { } } - public event System.Data.OleDb.OleDbRowUpdatedEventHandler RowUpdated { add { } remove { } } - public event System.Data.OleDb.OleDbRowUpdatingEventHandler RowUpdating { add { } remove { } } + public new System.Data.OleDb.OleDbCommand? UpdateCommand { get { throw null; } set { } } + public event System.Data.OleDb.OleDbRowUpdatedEventHandler? RowUpdated { add { } remove { } } + public event System.Data.OleDb.OleDbRowUpdatingEventHandler? RowUpdating { add { } remove { } } protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } public int Fill(System.Data.DataSet dataSet, object ADODBRecordSet, string srcTable) { throw null; } @@ -180,9 +182,9 @@ namespace System.Data.OleDb public override void Close() { } public override bool GetBoolean(int ordinal) { throw null; } public override byte GetByte(int ordinal) { throw null; } - public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; } + public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int bufferIndex, int length) { throw null; } public override char GetChar(int ordinal) { throw null; } - public override long GetChars(int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; } + public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int bufferIndex, int length) { throw null; } public new System.Data.OleDb.OleDbDataReader GetData(int ordinal) { throw null; } public override string GetDataTypeName(int index) { throw null; } public override System.DateTime GetDateTime(int ordinal) { throw null; } @@ -259,7 +261,7 @@ namespace System.Data.OleDb public int ErrorCode { get { throw null; } } public System.Data.OleDb.OleDbErrorCollection Errors { get { throw null; } } public string Message { get { throw null; } } - public string Source { get { throw null; } } + public string? Source { get { throw null; } } public override string ToString() { throw null; } } public delegate void OleDbInfoMessageEventHandler(object sender, System.Data.OleDb.OleDbInfoMessageEventArgs e); @@ -319,12 +321,12 @@ namespace System.Data.OleDb public sealed partial class OleDbParameter : System.Data.Common.DbParameter, System.Data.IDataParameter, System.Data.IDbDataParameter, System.ICloneable { public OleDbParameter() { } - public OleDbParameter(string name, System.Data.OleDb.OleDbType dataType) { } - public OleDbParameter(string name, System.Data.OleDb.OleDbType dataType, int size) { } - public OleDbParameter(string parameterName, System.Data.OleDb.OleDbType dbType, int size, System.Data.ParameterDirection direction, bool isNullable, byte precision, byte scale, string srcColumn, System.Data.DataRowVersion srcVersion, object value) { } - public OleDbParameter(string parameterName, System.Data.OleDb.OleDbType dbType, int size, System.Data.ParameterDirection direction, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value) { } - public OleDbParameter(string name, System.Data.OleDb.OleDbType dataType, int size, string srcColumn) { } - public OleDbParameter(string name, object value) { } + public OleDbParameter(string? name, System.Data.OleDb.OleDbType dataType) { } + public OleDbParameter(string? name, System.Data.OleDb.OleDbType dataType, int size) { } + public OleDbParameter(string? parameterName, System.Data.OleDb.OleDbType dbType, int size, System.Data.ParameterDirection direction, bool isNullable, byte precision, byte scale, string? srcColumn, System.Data.DataRowVersion srcVersion, object? value) { } + public OleDbParameter(string? parameterName, System.Data.OleDb.OleDbType dbType, int size, System.Data.ParameterDirection direction, byte precision, byte scale, string? sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object? value) { } + public OleDbParameter(string? name, System.Data.OleDb.OleDbType dataType, int size, string? srcColumn) { } + public OleDbParameter(string? name, object? value) { } public override System.Data.DbType DbType { get { throw null; } set { } } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public override System.Data.ParameterDirection Direction { get { throw null; } set { } } @@ -332,18 +334,20 @@ namespace System.Data.OleDb [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)] public System.Data.OleDb.OleDbType OleDbType { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string ParameterName { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((byte)0)] public new byte Precision { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((byte)0)] public new byte Scale { get { throw null; } set { } } public override int Size { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string SourceColumn { get { throw null; } set { } } public override bool SourceColumnNullMapping { get { throw null; } set { } } public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.ComponentModel.TypeConverterAttribute(typeof(System.ComponentModel.StringConverter))] - public override object Value { get { throw null; } set { } } + public override object? Value { get { throw null; } set { } } public override void ResetDbType() { } public void ResetOleDbType() { } object System.ICloneable.Clone() { throw null; } @@ -365,13 +369,13 @@ namespace System.Data.OleDb public override object SyncRoot { get { throw null; } } public System.Data.OleDb.OleDbParameter Add(System.Data.OleDb.OleDbParameter value) { throw null; } public override int Add(object value) { throw null; } - public System.Data.OleDb.OleDbParameter Add(string parameterName, System.Data.OleDb.OleDbType oleDbType) { throw null; } - public System.Data.OleDb.OleDbParameter Add(string parameterName, System.Data.OleDb.OleDbType oleDbType, int size) { throw null; } - public System.Data.OleDb.OleDbParameter Add(string parameterName, System.Data.OleDb.OleDbType oleDbType, int size, string sourceColumn) { throw null; } - public System.Data.OleDb.OleDbParameter Add(string parameterName, object value) { throw null; } + public System.Data.OleDb.OleDbParameter Add(string? parameterName, System.Data.OleDb.OleDbType oleDbType) { throw null; } + public System.Data.OleDb.OleDbParameter Add(string? parameterName, System.Data.OleDb.OleDbType oleDbType, int size) { throw null; } + public System.Data.OleDb.OleDbParameter Add(string? parameterName, System.Data.OleDb.OleDbType oleDbType, int size, string? sourceColumn) { throw null; } + public System.Data.OleDb.OleDbParameter Add(string? parameterName, object? value) { throw null; } public override void AddRange(System.Array values) { } public void AddRange(System.Data.OleDb.OleDbParameter[] values) { } - public System.Data.OleDb.OleDbParameter AddWithValue(string parameterName, object value) { throw null; } + public System.Data.OleDb.OleDbParameter AddWithValue(string? parameterName, object? value) { throw null; } public override void Clear() { } public bool Contains(System.Data.OleDb.OleDbParameter value) { throw null; } public override bool Contains(object value) { throw null; } @@ -396,14 +400,14 @@ namespace System.Data.OleDb public sealed partial class OleDbRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs { public OleDbRowUpdatedEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } - public new System.Data.OleDb.OleDbCommand Command { get { throw null; } } + public new System.Data.OleDb.OleDbCommand? Command { get { throw null; } } } public delegate void OleDbRowUpdatedEventHandler(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e); public sealed partial class OleDbRowUpdatingEventArgs : System.Data.Common.RowUpdatingEventArgs { public OleDbRowUpdatingEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } - protected override System.Data.IDbCommand BaseCommand { get { throw null; } set { } } - public new System.Data.OleDb.OleDbCommand Command { get { throw null; } set { } } + protected override System.Data.IDbCommand? BaseCommand { get { throw null; } set { } } + public new System.Data.OleDb.OleDbCommand? Command { get { throw null; } set { } } } public delegate void OleDbRowUpdatingEventHandler(object sender, System.Data.OleDb.OleDbRowUpdatingEventArgs e); public sealed partial class OleDbSchemaGuid @@ -450,8 +454,8 @@ namespace System.Data.OleDb public sealed partial class OleDbTransaction : System.Data.Common.DbTransaction { internal OleDbTransaction() { } - public new System.Data.OleDb.OleDbConnection Connection { get { throw null; } } - protected override System.Data.Common.DbConnection DbConnection { get { throw null; } } + public new System.Data.OleDb.OleDbConnection? Connection { get { throw null; } } + protected override System.Data.Common.DbConnection? DbConnection { get { throw null; } } public override System.Data.IsolationLevel IsolationLevel { get { throw null; } } public System.Data.OleDb.OleDbTransaction Begin() { throw null; } public System.Data.OleDb.OleDbTransaction Begin(System.Data.IsolationLevel isolevel) { throw null; } diff --git a/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.csproj b/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.csproj index 44d08a1..912dfa3 100644 --- a/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.csproj +++ b/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.csproj @@ -2,6 +2,7 @@ netstandard2.0;net461 $(NoWarn);0618 + enable diff --git a/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs b/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs index d8a0ac6..4ffe04c 100644 --- a/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs +++ b/src/libraries/System.Data.OleDb/src/AdapterSwitches.cs @@ -9,13 +9,13 @@ namespace System.Data.Common { internal static class AdapterSwitches { - private static TraceSwitch _dataSchema; + private static TraceSwitch? _dataSchema; internal static TraceSwitch DataSchema { get { - TraceSwitch dataSchema = _dataSchema; + TraceSwitch? dataSchema = _dataSchema; if (null == dataSchema) { _dataSchema = dataSchema = new TraceSwitch("Data.Schema", "Enable tracing for schema actions."); diff --git a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs index 322e30c..3433415 100644 --- a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs +++ b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs @@ -19,14 +19,14 @@ namespace System.Data.OleDb private readonly Bindings _bindings; // unique to this ColumnBinding - private readonly OleDbParameter _parameter; // output value + private readonly OleDbParameter? _parameter; // output value private readonly int _parameterChangeID; private readonly int _offsetStatus; private readonly int _offsetLength; private readonly int _offsetValue; // Delegate ad hoc created 'Marshal.GetIDispatchForObject' reflection object cache - private static Func s_getIDispatchForObject; + private static Func? s_getIDispatchForObject; private readonly int _ordinal; private readonly int _maxLen; @@ -42,15 +42,15 @@ namespace System.Data.OleDb // unique per current input value private int _valueBindingOffset; private int _valueBindingSize; - internal StringMemHandle _sptr; + internal StringMemHandle? _sptr; private GCHandle _pinnedBuffer; // value is cached via property getters so the original may be released // for Value, ValueByteArray, ValueString, ValueVariant - private object _value; + private object? _value; internal ColumnBinding(OleDbDataReader dataReader, int index, int indexForAccessor, int indexWithinAccessor, - OleDbParameter parameter, RowBinding rowbinding, Bindings bindings, tagDBBINDING binding, int offset, + OleDbParameter? parameter, RowBinding rowbinding, Bindings bindings, tagDBBINDING binding, int offset, bool ifIRowsetElseIRow) { Debug.Assert(null != rowbinding, "null rowbinding"); @@ -123,7 +123,7 @@ namespace System.Data.OleDb private Type ExpectedType { - get { return NativeDBType.FromDBType(DbType, false, false).dataType; } + get { return NativeDBType.FromDBType(DbType, false, false).dataType!; } } internal int Index @@ -203,7 +203,7 @@ namespace System.Data.OleDb { _value = null; - StringMemHandle sptr = _sptr; + StringMemHandle? sptr = _sptr; _sptr = null; if (null != sptr) @@ -274,8 +274,8 @@ namespace System.Data.OleDb internal object Value() { - object value = _value; - if (null == value) + object value; + if (null == _value) { switch (StatusValue()) { @@ -433,9 +433,9 @@ namespace System.Data.OleDb } _value = value; } - return value; + return _value!; } - internal void Value(object value) + internal void Value(object? value) { if (null == value) { @@ -663,7 +663,7 @@ namespace System.Data.OleDb { Debug.Assert(((NativeDBType.BYREF | NativeDBType.BYTES) == DbType), "Value_ByRefBYTES"); Debug.Assert((DBStatus.S_OK == StatusValue()), "Value_ByRefBYTES"); - byte[] value = null; + byte[]? value = null; RowBinding bindings = RowBinding; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -948,7 +948,8 @@ namespace System.Data.OleDb Debug.Assert(NativeDBType.HCHAPTER == DbType, "Value_HCHAPTER"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_HCHAPTER"); - return DataReader().ResetChapter(IndexForAccessor, IndexWithinAccessor, RowBinding, ValueOffset); + // TODO-NULLABLE: This shouldn't return null + return DataReader().ResetChapter(IndexForAccessor, IndexWithinAccessor, RowBinding, ValueOffset)!; } private sbyte Value_I1() @@ -1042,15 +1043,15 @@ namespace System.Data.OleDb // lazy init reflection objects if (s_getIDispatchForObject == null) { - object delegateInstance = null; - MethodInfo mi = typeof(Marshal).GetMethod("GetIDispatchForObject", BindingFlags.Public | BindingFlags.Static); + object? delegateInstance = null; + MethodInfo? mi = typeof(Marshal).GetMethod("GetIDispatchForObject", BindingFlags.Public | BindingFlags.Static); if (mi == null) { throw new NotSupportedException(SR.PlatformNotSupported_GetIDispatchForObject); } Volatile.Write(ref delegateInstance, mi.CreateDelegate(typeof(Func))); s_getIDispatchForObject = delegateInstance as Func; - ptr = s_getIDispatchForObject(value); + ptr = s_getIDispatchForObject!(value); } RowBinding.WriteIntPtr(ValueOffset, ptr); } @@ -1272,7 +1273,7 @@ namespace System.Data.OleDb internal byte[] ValueByteArray() { - byte[] value = (byte[])_value; + byte[]? value = (byte[]?)_value; if (null == value) { switch (StatusValue()) @@ -1340,7 +1341,7 @@ namespace System.Data.OleDb internal OleDbDataReader ValueChapter() { - OleDbDataReader value = (OleDbDataReader)_value; + OleDbDataReader? value = (OleDbDataReader?)_value; if (null == value) { switch (StatusValue()) @@ -1605,7 +1606,7 @@ namespace System.Data.OleDb internal string ValueString() { - string value = (string)_value; + string? value = (string?)_value; if (null == value) { switch (StatusValue()) @@ -1652,7 +1653,7 @@ namespace System.Data.OleDb private object ValueVariant() { - object value = _value; + object? value = _value; if (null == value) { value = Value_VARIANT(); diff --git a/src/libraries/System.Data.OleDb/src/DbBindings.cs b/src/libraries/System.Data.OleDb/src/DbBindings.cs index 512985e..c380281 100644 --- a/src/libraries/System.Data.OleDb/src/DbBindings.cs +++ b/src/libraries/System.Data.OleDb/src/DbBindings.cs @@ -9,16 +9,16 @@ namespace System.Data.OleDb { internal sealed class Bindings { - private readonly tagDBPARAMBINDINFO[] _bindInfo; + private readonly tagDBPARAMBINDINFO[]? _bindInfo; private readonly tagDBBINDING[] _dbbindings; private readonly tagDBCOLUMNACCESS[] _dbcolumns; - private OleDbParameter[] _parameters; + private OleDbParameter[]? _parameters; private readonly int _collectionChangeID; - private OleDbDataReader _dataReader; - private ColumnBinding[] _columnBindings; - private RowBinding _rowBinding; + private OleDbDataReader? _dataReader; + private ColumnBinding[]? _columnBindings; + private RowBinding? _rowBinding; private int _index; private readonly int _count; @@ -53,7 +53,7 @@ namespace System.Data.OleDb _ifIRowsetElseIRow = ifIRowsetElseIRow; } - internal tagDBPARAMBINDINFO[] BindInfo + internal tagDBPARAMBINDINFO[]? BindInfo { get { return _bindInfo; } } @@ -84,7 +84,7 @@ namespace System.Data.OleDb return _parameters; } - internal RowBinding RowBinding() + internal RowBinding? RowBinding() { //Debug.Assert(null != _rowBinding, "null RowBinding"); return _rowBinding; @@ -102,7 +102,7 @@ namespace System.Data.OleDb //get { return _bindInfo[_index].pwszDataSourceType; } set { - _bindInfo[_index].pwszDataSourceType = value; + _bindInfo![_index].pwszDataSourceType = value; } } internal IntPtr Name @@ -110,7 +110,7 @@ namespace System.Data.OleDb //get { return _bindInfo[_index].pwszName; } set { - _bindInfo[_index].pwszName = value; + _bindInfo![_index].pwszName = value; } } internal IntPtr ParamSize @@ -125,7 +125,7 @@ namespace System.Data.OleDb } set { - _bindInfo[_index].ulParamSize = value; + _bindInfo![_index].ulParamSize = value; } } internal int Flags @@ -133,7 +133,7 @@ namespace System.Data.OleDb //get { return _bindInfo[_index].dwFlag; } set { - _bindInfo[_index].dwFlags = value; + _bindInfo![_index].dwFlags = value; } } @@ -246,7 +246,7 @@ namespace System.Data.OleDb } } - internal int AllocateForAccessor(OleDbDataReader dataReader, int indexStart, int indexForAccessor) + internal int AllocateForAccessor(OleDbDataReader? dataReader, int indexStart, int indexForAccessor) { Debug.Assert(null == _rowBinding, "row binding already allocated"); Debug.Assert(null == _columnBindings, "column bindings already allocated"); @@ -283,7 +283,7 @@ namespace System.Data.OleDb ColumnBinding[] columnBindings = this.ColumnBindings(); OleDbParameter[] parameters = this.Parameters(); - RowBinding().StartDataBlock(); + RowBinding()!.StartDataBlock(); for (int i = 0; i < parameters.Length; ++i) { if (ADP.IsDirection(parameters[i], ParameterDirection.Input)) @@ -345,7 +345,7 @@ namespace System.Data.OleDb internal void CleanupBindings() { - RowBinding rowBinding = this.RowBinding(); + RowBinding? rowBinding = this.RowBinding(); if (null != rowBinding) { rowBinding.ResetValues(); @@ -384,7 +384,7 @@ namespace System.Data.OleDb _dataReader = null; _columnBindings = null; - RowBinding rowBinding = _rowBinding; + RowBinding? rowBinding = _rowBinding; _rowBinding = null; if (null != rowBinding) { diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs index aa42ab2..11c5e01 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs @@ -3,6 +3,7 @@ using System.Collections; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Versioning; using System.Text; @@ -96,7 +97,7 @@ namespace System.Data.Common private readonly string _usersConnectionString; private readonly Hashtable _parsetable; - internal readonly NameValuePair KeyChain; + internal readonly NameValuePair? KeyChain; internal readonly bool HasPasswordKeyword; internal readonly bool HasUserIdKeyword; @@ -117,14 +118,14 @@ namespace System.Data.Common internal readonly bool UseOdbcRules; // called by derived classes that may cache based on connectionString - public DbConnectionOptions(string connectionString) + public DbConnectionOptions(string? connectionString) : this(connectionString, null, false) { } // synonyms hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string - public DbConnectionOptions(string connectionString, Hashtable synonyms, bool useOdbcRules) + public DbConnectionOptions(string? connectionString, Hashtable? synonyms, bool useOdbcRules) { UseOdbcRules = useOdbcRules; _parsetable = new Hashtable(); @@ -171,12 +172,12 @@ namespace System.Data.Common get { return (null == KeyChain); } } - public string this[string keyword] + public string? this[string keyword] { - get { return (string)_parsetable[keyword]; } + get { return (string?)_parsetable[keyword]; } } - internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules) + internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string? keyValue, bool useOdbcRules) { ADP.CheckArgumentNull(builder, "builder"); ADP.CheckArgumentLength(keyName, "keyName"); @@ -251,7 +252,7 @@ namespace System.Data.Common public bool ConvertValueToBoolean(string keyName, bool defaultValue) { - object value = _parsetable[keyName]; + object? value = _parsetable[keyName]; if (null == value) { return defaultValue; @@ -281,7 +282,7 @@ namespace System.Data.Common public int ConvertValueToInt32(string keyName, int defaultValue) { - object value = _parsetable[keyName]; + object? value = _parsetable[keyName]; if (null == value) { return defaultValue; @@ -305,9 +306,9 @@ namespace System.Data.Common } } - public string ConvertValueToString(string keyName, string defaultValue) + public string? ConvertValueToString(string keyName, string? defaultValue) { - string value = (string)_parsetable[keyName]; + string? value = (string?)_parsetable[keyName]; return ((null != value) ? value : defaultValue); } @@ -330,16 +331,16 @@ namespace System.Data.Common // * this method queries "DataDirectory" value from the current AppDomain. // This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource". // * This method uses GetFullPath to validate that root path is valid, the result is not exposed out. - internal static string ExpandDataDirectory(string keyword, string value, ref string datadir) + internal static string? ExpandDataDirectory(string keyword, string? value, ref string? datadir) { - string fullPath = null; + string? fullPath = null; if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) { - string rootFolderPath = datadir; + string? rootFolderPath = datadir; if (null == rootFolderPath) { // find the replacement path - object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); + object? rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); rootFolderPath = (rootFolderObject as string); if ((null != rootFolderObject) && (null == rootFolderPath)) { @@ -388,16 +389,16 @@ namespace System.Data.Common return fullPath; } - internal string ExpandDataDirectories(ref string filename, ref int position) + internal string? ExpandDataDirectories(ref string? filename, ref int position) { - string value = null; + string? value = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - string datadir = null; + string? datadir = null; int copyPosition = 0; bool expanded = false; - for (NameValuePair current = KeyChain; null != current; current = current.Next) + for (NameValuePair? current = KeyChain; null != current; current = current.Next) { value = current.Value; @@ -481,11 +482,11 @@ namespace System.Data.Common } [System.Diagnostics.Conditional("DEBUG")] - private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) + private static void DebugTraceKeyValuePair(string keyname, string? keyvalue, Hashtable? synonyms) { Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower"); - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + string? realkeyname = ((null != synonyms) ? (string)synonyms[keyname]! : keyname); if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! if (null != keyvalue) @@ -543,7 +544,7 @@ namespace System.Data.Common NullTermination, }; - internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue) + internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string? keyname, out string? keyvalue) { int startposition = currentPosition; @@ -747,7 +748,7 @@ namespace System.Data.Common return currentPosition; } - private static bool IsValueValidInternal(string keyvalue) + private static bool IsValueValidInternal(string? keyvalue) { if (null != keyvalue) { @@ -760,7 +761,7 @@ namespace System.Data.Common return true; } - private static bool IsKeyNameValid(string keyname) + private static bool IsKeyNameValid([NotNullWhen(true)] string? keyname) { if (null != keyname) { @@ -774,7 +775,7 @@ namespace System.Data.Common } #if DEBUG - private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey) + private static Hashtable SplitConnectionString(string connectionString, Hashtable? synonyms, bool firstKey) { Hashtable parsetable = new Hashtable(); Regex parser = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex); @@ -795,7 +796,7 @@ namespace System.Data.Common foreach (Capture keypair in match.Groups[KeyIndex].Captures) { string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant(); - string keyvalue = keyvalues[indexValue++].Value; + string? keyvalue = keyvalues[indexValue++].Value; if (0 < keyvalue.Length) { if (!firstKey) @@ -819,7 +820,7 @@ namespace System.Data.Common } DebugTraceKeyValuePair(keyname, keyvalue, synonyms); - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + string? realkeyname = ((null != synonyms) ? (string)synonyms[keyname]! : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); @@ -833,7 +834,7 @@ namespace System.Data.Common return parsetable; } - private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, bool firstKey, Exception e) + private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable? synonyms, bool firstKey, Exception? e) { try { @@ -841,8 +842,8 @@ namespace System.Data.Common foreach (DictionaryEntry entry in parsedvalues) { string keyname = (string)entry.Key; - string value1 = (string)entry.Value; - string value2 = (string)parsetable[keyname]; + string? value1 = (string?)entry.Value; + string? value2 = (string?)parsetable[keyname]; Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">"); Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">"); } @@ -884,11 +885,11 @@ namespace System.Data.Common } } #endif - private static NameValuePair ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable synonyms, bool firstKey) + private static NameValuePair? ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable? synonyms, bool firstKey) { Debug.Assert(null != connectionString, "null connectionstring"); StringBuilder buffer = new StringBuilder(); - NameValuePair localKeychain = null, keychain = null; + NameValuePair? localKeychain = null, keychain = null; #if DEBUG try { @@ -899,7 +900,7 @@ namespace System.Data.Common { int startPosition = nextStartPosition; - string keyname, keyvalue; + string? keyname, keyvalue; nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue); if (ADP.IsEmpty(keyname)) { @@ -912,7 +913,7 @@ namespace System.Data.Common Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname"); Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue"); #endif - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + string? realkeyname = ((null != synonyms) ? (string)synonyms[keyname]! : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); @@ -943,13 +944,13 @@ namespace System.Data.Common return keychain; } - internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) + internal NameValuePair? ReplacePasswordPwd(out string constr, bool fakePassword) { bool expanded = false; int copyPosition = 0; - NameValuePair head = null, tail = null, next = null; + NameValuePair? head = null, tail = null, next = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair current = KeyChain; null != current; current = current.Next) + for (NameValuePair? current = KeyChain; null != current; current = current.Next) { if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name)) { diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs b/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs index 9ee6ade..9477bb4 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data.Common @@ -111,7 +112,7 @@ namespace System.Data.Common } } - object System.Collections.IEnumerator.Current + object? System.Collections.IEnumerator.Current { get { @@ -131,7 +132,7 @@ namespace System.Data.Common internal static bool ConvertToBoolean(object value) { Debug.Assert(null != value, "ConvertToBoolean(null)"); - string svalue = (value as string); + string? svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) diff --git a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs index a78b359..a89572d 100644 --- a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs +++ b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs @@ -3,24 +3,25 @@ using System.ComponentModel; using System.Data.Common; +using System.Diagnostics.CodeAnalysis; namespace System.Data.OleDb { public sealed partial class OleDbParameter : DbParameter { // V1.2.3300 - private object _value; + private object? _value; - private object _parent; + private object? _parent; private ParameterDirection _direction; private int _size; - private string _sourceColumn; + private string? _sourceColumn; private DataRowVersion _sourceVersion; private bool _sourceColumnNullMapping; private bool _isNullable; - private object _coercedValue; + private object? _coercedValue; private OleDbParameter(OleDbParameter source) : this() { // V1.2.3300, Clone @@ -28,14 +29,14 @@ namespace System.Data.OleDb source.CloneHelper(this); - ICloneable cloneable = (_value as ICloneable); + ICloneable? cloneable = (_value as ICloneable); if (null != cloneable) { _value = cloneable.Clone(); } } - private object CoercedValue + private object? CoercedValue { // V1.2.3300 get { @@ -134,11 +135,12 @@ namespace System.Data.OleDb return (0 != _size); } + [AllowNull] public override string SourceColumn { // V1.2.3300, XXXParameter V1.0.3300 get { - string sourceColumn = _sourceColumn; + string? sourceColumn = _sourceColumn; return ((null != sourceColumn) ? sourceColumn : string.Empty); } set @@ -200,13 +202,13 @@ namespace System.Data.OleDb CloneHelper((OleDbParameter)destination); } - internal object CompareExchangeParent(object value, object comparand) + internal object? CompareExchangeParent(object? value, object? comparand) { // the interlock guarantees same parameter won't belong to multiple collections // at the same time, but to actually occur the user must really try // since we never declared thread safety, we don't care at this time //return System.Threading.Interlocked.CompareExchange(ref _parent, value, comparand); - object parent = _parent; + object? parent = _parent; if (comparand == parent) { _parent = value; @@ -224,7 +226,7 @@ namespace System.Data.OleDb return ParameterName; } - private byte ValuePrecisionCore(object value) + private byte ValuePrecisionCore(object? value) { // V1.2.3300 if (value is decimal) { @@ -233,7 +235,7 @@ namespace System.Data.OleDb return 0; } - private byte ValueScaleCore(object value) + private byte ValueScaleCore(object? value) { // V1.2.3300 if (value is decimal) { @@ -242,21 +244,21 @@ namespace System.Data.OleDb return 0; } - private int ValueSizeCore(object value) + private int ValueSizeCore(object? value) { // V1.2.3300 if (!ADP.IsNull(value)) { - string svalue = (value as string); + string? svalue = (value as string); if (null != svalue) { return svalue.Length; } - byte[] bvalue = (value as byte[]); + byte[]? bvalue = (value as byte[]); if (null != bvalue) { return bvalue.Length; } - char[] cvalue = (value as char[]); + char[]? cvalue = (value as char[]); if (null != cvalue) { return cvalue.Length; diff --git a/src/libraries/System.Data.OleDb/src/DbPropSet.cs b/src/libraries/System.Data.OleDb/src/DbPropSet.cs index b4fb008..30935b1 100644 --- a/src/libraries/System.Data.OleDb/src/DbPropSet.cs +++ b/src/libraries/System.Data.OleDb/src/DbPropSet.cs @@ -14,7 +14,7 @@ namespace System.Data.OleDb private readonly int propertySetCount; // stores the exception with last error.HRESULT from IDBProperties.GetProperties - private Exception lastErrorFromProvider; + private Exception? lastErrorFromProvider; private DBPropSet() : base(IntPtr.Zero, true) { @@ -42,7 +42,7 @@ namespace System.Data.OleDb } } - internal DBPropSet(UnsafeNativeMethods.IDBProperties properties, PropertyIDSet propidset, out OleDbHResult hr) : this() + internal DBPropSet(UnsafeNativeMethods.IDBProperties properties, PropertyIDSet? propidset, out OleDbHResult hr) : this() { Debug.Assert(null != properties, "null IDBProperties"); @@ -60,7 +60,7 @@ namespace System.Data.OleDb } } - internal DBPropSet(UnsafeNativeMethods.IRowsetInfo properties, PropertyIDSet propidset, out OleDbHResult hr) : this() + internal DBPropSet(UnsafeNativeMethods.IRowsetInfo properties, PropertyIDSet? propidset, out OleDbHResult hr) : this() { Debug.Assert(null != properties, "null IRowsetInfo"); @@ -78,7 +78,7 @@ namespace System.Data.OleDb } } - internal DBPropSet(UnsafeNativeMethods.ICommandProperties properties, PropertyIDSet propidset, out OleDbHResult hr) : this() + internal DBPropSet(UnsafeNativeMethods.ICommandProperties properties, PropertyIDSet? propidset, out OleDbHResult hr) : this() { Debug.Assert(null != properties, "null ICommandProperties"); @@ -99,7 +99,7 @@ namespace System.Data.OleDb private void SetLastErrorInfo(OleDbHResult lastErrorHr) { // note: OleDbHResult is actually a simple wrapper over HRESULT with OLEDB-specific codes - UnsafeNativeMethods.IErrorInfo errorInfo = null; + UnsafeNativeMethods.IErrorInfo? errorInfo = null; string message = string.Empty; OleDbHResult errorInfoHr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo @@ -172,7 +172,7 @@ namespace System.Data.OleDb } tagDBPROPSET propset = new tagDBPROPSET(); - ItagDBPROP[] properties = null; + ItagDBPROP[]? properties = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); diff --git a/src/libraries/System.Data.OleDb/src/NativeMethods.cs b/src/libraries/System.Data.OleDb/src/NativeMethods.cs index 871ae1b..6592ed5 100644 --- a/src/libraries/System.Data.OleDb/src/NativeMethods.cs +++ b/src/libraries/System.Data.OleDb/src/NativeMethods.cs @@ -27,7 +27,7 @@ namespace System.Data.Common int GetOptionsObject(IntPtr ppOptions); void JoinTransaction( - [In, MarshalAs(UnmanagedType.Interface)] object punkTransactionCoord, + [In, MarshalAs(UnmanagedType.Interface)] object? punkTransactionCoord, [In] int isoLevel, [In] int isoFlags, [In] IntPtr pOtherOptions); diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs index ced289c..329200e 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -14,24 +15,24 @@ namespace System.Data.OleDb public sealed class OleDbCommand : DbCommand, ICloneable, IDbCommand { // command data - private string _commandText; + private string? _commandText; private CommandType _commandType; private int _commandTimeout = ADP.DefaultCommandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; - private OleDbConnection _connection; - private OleDbTransaction _transaction; + private OleDbConnection? _connection; + private OleDbTransaction? _transaction; - private OleDbParameterCollection _parameters; + private OleDbParameterCollection? _parameters; // native information - private UnsafeNativeMethods.ICommandText _icommandText; + private UnsafeNativeMethods.ICommandText? _icommandText; // if executing with a different CommandBehavior.KeyInfo behavior // original ICommandText must be released and a new ICommandText generated private CommandBehavior commandBehavior; - private Bindings _dbBindings; + private Bindings? _dbBindings; internal bool canceling; private bool _isPrepared; @@ -48,18 +49,18 @@ namespace System.Data.OleDb GC.SuppressFinalize(this); } - public OleDbCommand(string cmdText) : this() + public OleDbCommand(string? cmdText) : this() { CommandText = cmdText; } - public OleDbCommand(string cmdText, OleDbConnection connection) : this() + public OleDbCommand(string? cmdText, OleDbConnection? connection) : this() { CommandText = cmdText; Connection = connection; } - public OleDbCommand(string cmdText, OleDbConnection connection, OleDbTransaction transaction) : this() + public OleDbCommand(string? cmdText, OleDbConnection? connection, OleDbTransaction? transaction) : this() { CommandText = cmdText; Connection = connection; @@ -79,11 +80,11 @@ namespace System.Data.OleDb OleDbParameterCollection parameters = Parameters; foreach (object parameter in from.Parameters) { - parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter); + parameters.Add(parameter is ICloneable cloneableParameter ? cloneableParameter.Clone() : parameter); } } - private Bindings ParameterBindings + private Bindings? ParameterBindings { get { @@ -91,7 +92,7 @@ namespace System.Data.OleDb } set { - Bindings bindings = _dbBindings; + Bindings? bindings = _dbBindings; _dbBindings = value; if ((null != bindings) && (value != bindings)) { @@ -102,11 +103,12 @@ namespace System.Data.OleDb [DefaultValue("")] [RefreshProperties(RefreshProperties.All)] + [AllowNull] public override string CommandText { get { - string value = _commandText; + string? value = _commandText; return ((null != value) ? value : string.Empty); } set @@ -174,7 +176,7 @@ namespace System.Data.OleDb } [DefaultValue(null)] - public new OleDbConnection Connection + public new OleDbConnection? Connection { get { @@ -182,7 +184,7 @@ namespace System.Data.OleDb } set { - OleDbConnection connection = _connection; + OleDbConnection? connection = _connection; if (value != connection) { PropertyChanging(); @@ -200,7 +202,7 @@ namespace System.Data.OleDb private void ResetConnection() { - OleDbConnection connection = _connection; + OleDbConnection? connection = _connection; if (null != connection) { PropertyChanging(); @@ -214,7 +216,7 @@ namespace System.Data.OleDb _connection = null; } - protected override DbConnection DbConnection + protected override DbConnection? DbConnection { // V1.2.3300 get { @@ -222,7 +224,7 @@ namespace System.Data.OleDb } set { - Connection = (OleDbConnection)value; + Connection = (OleDbConnection?)value; } } @@ -234,7 +236,7 @@ namespace System.Data.OleDb } } - protected override DbTransaction DbTransaction + protected override DbTransaction? DbTransaction { // V1.2.3300 get { @@ -242,7 +244,7 @@ namespace System.Data.OleDb } set { - Transaction = (OleDbTransaction)value; + Transaction = (OleDbTransaction?)value; } } @@ -276,7 +278,7 @@ namespace System.Data.OleDb { get { - OleDbParameterCollection value = _parameters; + OleDbParameterCollection? value = _parameters; if (null == value) { // delay the creation of the OleDbParameterCollection @@ -290,7 +292,7 @@ namespace System.Data.OleDb private bool HasParameters() { - OleDbParameterCollection value = _parameters; + OleDbParameterCollection? value = _parameters; return (null != value) && (0 < value.Count); } @@ -298,13 +300,13 @@ namespace System.Data.OleDb Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new OleDbTransaction Transaction + public new OleDbTransaction? Transaction { get { // find the last non-zombied local transaction object, but not transactions // that may have been started after the current local transaction - OleDbTransaction transaction = _transaction; + OleDbTransaction? transaction = _transaction; while ((null != transaction) && (null == transaction.Connection)) { transaction = transaction.Parent; @@ -358,20 +360,20 @@ namespace System.Data.OleDb } // optional interface, unsafe cast - private UnsafeNativeMethods.ICommandPrepare ICommandPrepare() + private UnsafeNativeMethods.ICommandPrepare? ICommandPrepare() { Debug.Assert(null != _icommandText, "ICommandPrepare: null ICommandText"); - return (_icommandText as UnsafeNativeMethods.ICommandPrepare); + return _icommandText as UnsafeNativeMethods.ICommandPrepare; } // optional interface, unsafe cast private UnsafeNativeMethods.ICommandWithParameters ICommandWithParameters() { Debug.Assert(null != _icommandText, "ICommandWithParameters: null ICommandText"); - UnsafeNativeMethods.ICommandWithParameters value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters); + UnsafeNativeMethods.ICommandWithParameters? value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters); if (null == value) { - throw ODB.NoProviderSupportForParameters(_connection.Provider, (Exception)null); + throw ODB.NoProviderSupportForParameters(_connection!.Provider, null); } return value; } @@ -385,7 +387,7 @@ namespace System.Data.OleDb // do this first in-case the command doesn't support parameters UnsafeNativeMethods.ICommandWithParameters commandWithParameters = ICommandWithParameters(); - OleDbParameterCollection collection = _parameters; + OleDbParameterCollection collection = _parameters!; OleDbParameter[] parameters = new OleDbParameter[collection.Count]; collection.CopyTo(parameters, 0); @@ -399,7 +401,7 @@ namespace System.Data.OleDb bindings.AllocateForAccessor(null, 0, 0); - ApplyParameterBindings(commandWithParameters, bindings.BindInfo); + ApplyParameterBindings(commandWithParameters, bindings.BindInfo!); UnsafeNativeMethods.IAccessor iaccessor = IAccessor(); OleDbHResult hr = bindings.CreateAccessor(iaccessor, ODB.DBACCESSOR_PARAMETERDATA); @@ -454,7 +456,7 @@ namespace System.Data.OleDb unchecked { _changeID++; } - UnsafeNativeMethods.ICommandText icmdtxt = _icommandText; + UnsafeNativeMethods.ICommandText? icmdtxt = _icommandText; if (null != icmdtxt) { OleDbHResult hr = OleDbHResult.S_OK; @@ -516,7 +518,7 @@ namespace System.Data.OleDb // may be called from either // OleDbDataReader.Close/Dispose // via OleDbCommand.Dispose or OleDbConnection.Close - internal void CloseFromDataReader(Bindings bindings) + internal void CloseFromDataReader(Bindings? bindings) { if (null != bindings) { @@ -541,7 +543,7 @@ namespace System.Data.OleDb this.commandBehavior = CommandBehavior.Default; _isPrepared = false; - UnsafeNativeMethods.ICommandText ict = Interlocked.Exchange(ref _icommandText, null); + UnsafeNativeMethods.ICommandText? ict = Interlocked.Exchange(ref _icommandText, null); if (null != ict) { lock (ict) @@ -554,7 +556,7 @@ namespace System.Data.OleDb private void CloseInternalParameters() { Debug.Assert(null != _connection, "no connection, CloseInternalParameters"); - Bindings bindings = _dbBindings; + Bindings? bindings = _dbBindings; _dbBindings = null; if (null != bindings) { @@ -606,7 +608,7 @@ namespace System.Data.OleDb public new OleDbDataReader ExecuteReader(CommandBehavior behavior) { _executeQuery = true; - return ExecuteReaderInternal(behavior, ADP.ExecuteReader); + return ExecuteReaderInternal(behavior, ADP.ExecuteReader)!; } IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) @@ -619,10 +621,10 @@ namespace System.Data.OleDb return ExecuteReader(behavior); } - private OleDbDataReader ExecuteReaderInternal(CommandBehavior behavior, string method) + private OleDbDataReader? ExecuteReaderInternal(CommandBehavior behavior, string method) { - OleDbDataReader dataReader = null; - OleDbException nextResultsFailure = null; + OleDbDataReader? dataReader = null; + OleDbException? nextResultsFailure = null; int state = ODB.InternalStateClosed; try { @@ -634,7 +636,7 @@ namespace System.Data.OleDb behavior |= CommandBehavior.SingleResult; } - object executeResult; + object? executeResult; int resultType; switch (CommandType) @@ -657,7 +659,7 @@ namespace System.Data.OleDb { try { - dataReader = new OleDbDataReader(_connection, this, 0, this.commandBehavior); + dataReader = new OleDbDataReader(_connection!, this, 0, this.commandBehavior); switch (resultType) { @@ -679,7 +681,7 @@ namespace System.Data.OleDb { PrepareCommandText(2); } - OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText, behavior); + OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText!, behavior); break; default: Debug.Assert(false, "ExecuteReaderInternal: unknown result type"); @@ -687,7 +689,7 @@ namespace System.Data.OleDb } executeResult = null; _hasDataReader = true; - _connection.AddWeakReference(dataReader, OleDbReferenceCollection.DataReaderTag); + _connection!.AddWeakReference(dataReader, OleDbReferenceCollection.DataReaderTag); // command stays in the executing state until the connection // has a datareader to track for it being closed @@ -713,10 +715,10 @@ namespace System.Data.OleDb { if (ODB.ExecutedIMultipleResults == resultType) { - UnsafeNativeMethods.IMultipleResults multipleResults = (UnsafeNativeMethods.IMultipleResults)executeResult; + UnsafeNativeMethods.IMultipleResults? multipleResults = (UnsafeNativeMethods.IMultipleResults?)executeResult; // may cause a Connection.ResetState which closes connection - nextResultsFailure = OleDbDataReader.NextResults(multipleResults, _connection, this, out _recordsAffected); + nextResultsFailure = OleDbDataReader.NextResults(multipleResults, _connection!, this, out _recordsAffected); } } finally @@ -782,7 +784,7 @@ namespace System.Data.OleDb return dataReader; } - private int ExecuteCommand(CommandBehavior behavior, out object executeResult) + private int ExecuteCommand(CommandBehavior behavior, out object? executeResult) { if (InitializeCommand(behavior, false)) { @@ -802,19 +804,20 @@ namespace System.Data.OleDb private int ExecuteCommandText(out object executeResult) { int retcode; - tagDBPARAMS dbParams = null; - RowBinding rowbinding = null; - Bindings bindings = ParameterBindings; + tagDBPARAMS? dbParams = null; + RowBinding? rowbinding = null; + Bindings? bindings = ParameterBindings; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { + // TODO-NULLABLE: Code below seems to assume that bindings will always be non-null if (null != bindings) { // parameters may be suppressed rowbinding = bindings.RowBinding(); - rowbinding.DangerousAddRef(ref mustRelease); + rowbinding!.DangerousAddRef(ref mustRelease); // bindings can't be released until after last rowset is released // that is when output parameters are populated @@ -826,24 +829,24 @@ namespace System.Data.OleDb dbParams.cParamSets = 1; dbParams.hAccessor = rowbinding.DangerousGetAccessorHandle(); } - if ((0 == (CommandBehavior.SingleResult & this.commandBehavior)) && _connection.SupportMultipleResults()) + if ((0 == (CommandBehavior.SingleResult & this.commandBehavior)) && _connection!.SupportMultipleResults()) { - retcode = ExecuteCommandTextForMultpleResults(dbParams, out executeResult); + retcode = ExecuteCommandTextForMultpleResults(dbParams!, out executeResult); } else if (0 == (CommandBehavior.SingleRow & this.commandBehavior) || !_executeQuery) { - retcode = ExecuteCommandTextForSingleResult(dbParams, out executeResult); + retcode = ExecuteCommandTextForSingleResult(dbParams!, out executeResult); } else { - retcode = ExecuteCommandTextForSingleRow(dbParams, out executeResult); + retcode = ExecuteCommandTextForSingleRow(dbParams!, out executeResult); } } finally { if (mustRelease) { - rowbinding.DangerousRelease(); + rowbinding!.DangerousRelease(); } } return retcode; @@ -853,7 +856,7 @@ namespace System.Data.OleDb { Debug.Assert(0 == (CommandBehavior.SingleRow & this.commandBehavior), "SingleRow implies SingleResult"); OleDbHResult hr; - hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult); + hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult); if (OleDbHResult.E_NOINTERFACE != hr) { @@ -871,11 +874,11 @@ namespace System.Data.OleDb // (Microsoft.Jet.OLEDB.4.0 returns 0 for recordsAffected instead of -1) if (_executeQuery) { - hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult); + hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult); } else { - hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult); + hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult); } ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIRowset; @@ -885,10 +888,10 @@ namespace System.Data.OleDb { Debug.Assert(_executeQuery, "ExecuteNonQuery should always use ExecuteCommandTextForSingleResult"); - if (_connection.SupportIRow(this)) + if (_connection!.SupportIRow(this)) { OleDbHResult hr; - hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult); + hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult); if (OleDbHResult.DB_E_NOTFOUND == hr) { @@ -907,7 +910,7 @@ namespace System.Data.OleDb private void ExecuteCommandTextErrorHandling(OleDbHResult hr) { - Exception e = OleDbConnection.ProcessResults(hr, _connection, this); + Exception? e = OleDbConnection.ProcessResults(hr, _connection, this); if (null != e) { e = ExecuteCommandTextSpecialErrorHandling(hr, e); @@ -927,7 +930,7 @@ namespace System.Data.OleDb Debug.Assert(null != e, "missing inner exception"); StringBuilder builder = new StringBuilder(); - ParameterBindings.ParameterStatus(builder); + ParameterBindings!.ParameterStatus(builder); e = ODB.CommandParameterStatus(builder.ToString(), e); } return e; @@ -940,11 +943,11 @@ namespace System.Data.OleDb return ADP.IntPtrToInt32(_recordsAffected); } - public override object ExecuteScalar() + public override object? ExecuteScalar() { - object value = null; + object? value = null; _executeQuery = true; - using (OleDbDataReader reader = ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteScalar)) + using (OleDbDataReader reader = ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteScalar)!) { if (reader.Read() && (0 < reader.FieldCount)) { @@ -954,14 +957,14 @@ namespace System.Data.OleDb return value; } - private int ExecuteTableDirect(CommandBehavior behavior, out object executeResult) + private int ExecuteTableDirect(CommandBehavior behavior, out object? executeResult) { this.commandBehavior = behavior; executeResult = null; OleDbHResult hr = OleDbHResult.S_OK; - StringMemHandle sptr = null; + StringMemHandle? sptr = null; bool mustReleaseStringHandle = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -978,9 +981,9 @@ namespace System.Data.OleDb tableID.eKind = ODB.DBKIND_NAME; tableID.ulPropid = sptr.DangerousGetHandle(); - using (IOpenRowsetWrapper iopenRowset = _connection.IOpenRowset()) + using (IOpenRowsetWrapper iopenRowset = _connection!.IOpenRowset()) { - using (DBPropSet propSet = CommandPropertySets()) + using (DBPropSet? propSet = CommandPropertySets()) { if (null != propSet) { @@ -1016,7 +1019,7 @@ namespace System.Data.OleDb { if (mustReleaseStringHandle) { - sptr.DangerousRelease(); + sptr!.DangerousRelease(); } } ProcessResults(hr); @@ -1118,7 +1121,7 @@ namespace System.Data.OleDb private void ParameterCleanup() { - Bindings bindings = ParameterBindings; + Bindings? bindings = ParameterBindings; if (null != bindings) { bindings.CleanupBindings(); @@ -1143,7 +1146,7 @@ namespace System.Data.OleDb return false; } - if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters)) + if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters!)) { CloseInternalParameters(); } @@ -1163,7 +1166,7 @@ namespace System.Data.OleDb string commandText = ExpandCommandText(); - hr = _icommandText.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText); + hr = _icommandText!.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText); if (hr < 0) { @@ -1199,7 +1202,7 @@ namespace System.Data.OleDb private void PrepareCommandText(int expectedExecutionCount) { - OleDbParameterCollection parameters = _parameters; + OleDbParameterCollection? parameters = _parameters; if (null != parameters) { foreach (OleDbParameter parameter in parameters) @@ -1213,7 +1216,7 @@ namespace System.Data.OleDb } } } - UnsafeNativeMethods.ICommandPrepare icommandPrepare = ICommandPrepare(); + UnsafeNativeMethods.ICommandPrepare? icommandPrepare = ICommandPrepare(); if (null != icommandPrepare) { OleDbHResult hr; @@ -1228,19 +1231,19 @@ namespace System.Data.OleDb private void ProcessResults(OleDbHResult hr) { - Exception e = OleDbConnection.ProcessResults(hr, _connection, this); + Exception? e = OleDbConnection.ProcessResults(hr, _connection, this); if (null != e) { throw e; } } private void ProcessResultsNoReset(OleDbHResult hr) { - Exception e = OleDbConnection.ProcessResults(hr, null, this); + Exception? e = OleDbConnection.ProcessResults(hr, null, this); if (null != e) { throw e; } } - internal object GetPropertyValue(Guid propertySet, int propertyID) + internal object? GetPropertyValue(Guid propertySet, int propertyID) { if (null != _icommandText) { @@ -1272,6 +1275,8 @@ namespace System.Data.OleDb private bool PropertiesOnCommand(bool throwNotSupported) { + Debug.Assert(_connection != null); + if (null != _icommandText) { return true; @@ -1279,10 +1284,7 @@ namespace System.Data.OleDb Debug.Assert(!_isPrepared, "null command isPrepared"); OleDbConnection connection = _connection; - if (null == connection) - { - connection.CheckStateOpen(ODB.Properties); - } + connection.CheckStateOpen(ODB.Properties); if (!_trackingForClose) { _trackingForClose = true; @@ -1299,7 +1301,7 @@ namespace System.Data.OleDb return false; } - using (DBPropSet propSet = CommandPropertySets()) + using (DBPropSet? propSet = CommandPropertySets()) { if (null != propSet) { @@ -1315,9 +1317,9 @@ namespace System.Data.OleDb return true; } - private DBPropSet CommandPropertySets() + private DBPropSet? CommandPropertySets() { - DBPropSet propSet = null; + DBPropSet? propSet = null; bool keyInfo = (0 != (CommandBehavior.KeyInfo & this.commandBehavior)); @@ -1351,9 +1353,9 @@ namespace System.Data.OleDb return propSet; } - internal Bindings TakeBindingOwnerShip() + internal Bindings? TakeBindingOwnerShip() { - Bindings bindings = _dbBindings; + Bindings? bindings = _dbBindings; _dbBindings = null; return bindings; } @@ -1382,7 +1384,7 @@ namespace System.Data.OleDb private void ValidateConnectionAndTransaction(string method) { ValidateConnection(method); - _transaction = _connection.ValidateTransaction(Transaction, method); + _transaction = _connection!.ValidateTransaction(Transaction, method); this.canceling = false; } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs index a421943..7eeabb8 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs @@ -15,13 +15,13 @@ namespace System.Data.OleDb GC.SuppressFinalize(this); } - public OleDbCommandBuilder(OleDbDataAdapter adapter) : this() + public OleDbCommandBuilder(OleDbDataAdapter? adapter) : this() { DataAdapter = adapter; } [DefaultValue(null)] - public new OleDbDataAdapter DataAdapter + public new OleDbDataAdapter? DataAdapter { get { @@ -122,7 +122,7 @@ namespace System.Data.OleDb { throw ADP.CommandTextRequired(ADP.DeriveParameters); } - OleDbConnection connection = command.Connection; + OleDbConnection? connection = command.Connection; if (null == connection) { throw ADP.ConnectionRequired(ADP.DeriveParameters); @@ -155,13 +155,13 @@ namespace System.Data.OleDb string quotePrefix, quoteSuffix; connection.GetLiteralQuotes(ADP.DeriveParameters, out quotePrefix, out quoteSuffix); - object[] parsed = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quotePrefix, quoteSuffix, '.', 4, true, SR.OLEDB_OLEDBCommandText, false); + object?[] parsed = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quotePrefix, quoteSuffix, '.', 4, true, SR.OLEDB_OLEDBCommandText, false); if (null == parsed[3]) { throw ADP.NoStoredProcedureExists(command.CommandText); } - object[] restrictions = new object[4]; + object?[] restrictions = new object[4]; object value; // Parse returns an enforced 4 part array @@ -182,19 +182,19 @@ namespace System.Data.OleDb //if (cmdConnection.IsServer_msdaora) { // restrictions[1] = Convert.ToString(cmdConnection.UserId).ToUpper(); //} - DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters, restrictions); + DataTable? table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters, restrictions); if (null != table) { DataColumnCollection columns = table.Columns; - DataColumn parameterName = null; - DataColumn parameterDirection = null; - DataColumn dataType = null; - DataColumn maxLen = null; - DataColumn numericPrecision = null; - DataColumn numericScale = null; - DataColumn backendtype = null; + DataColumn? parameterName = null; + DataColumn? parameterDirection = null; + DataColumn? dataType = null; + DataColumn? maxLen = null; + DataColumn? numericPrecision = null; + DataColumn? numericScale = null; + DataColumn? backendtype = null; int index = columns.IndexOf(ODB.PARAMETER_NAME); if (-1 != index) @@ -235,7 +235,7 @@ namespace System.Data.OleDb if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default)) { // $CONSIDER - not trimming the @ from the beginning but to left the designer do that - parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture).TrimStart(new char[] { '@', ' ', ':' }); + parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(new char[] { '@', ' ', ':' }); } if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default)) { @@ -271,7 +271,7 @@ namespace System.Data.OleDb case OleDbType.VarBinary: case OleDbType.VarChar: case OleDbType.VarWChar: - value = dataRow[backendtype, DataRowVersion.Default]; + value = dataRow[backendtype!, DataRowVersion.Default]; if (value is string) { string backendtypename = ((string)value).ToLowerInvariant(); @@ -316,8 +316,8 @@ namespace System.Data.OleDb } if ((0 == plist.Length) && connection.SupportSchemaRowset(OleDbSchemaGuid.Procedures)) { - restrictions = new object[4] { null, null, command.CommandText, null }; - table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions); + restrictions = new object?[4] { null, null, command.CommandText, null }; + table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions)!; if (0 == table.Rows.Count) { throw ADP.NoStoredProcedureExists(command.CommandText); @@ -326,8 +326,8 @@ namespace System.Data.OleDb } else if (connection.SupportSchemaRowset(OleDbSchemaGuid.Procedures)) { - object[] restrictions = new object[4] { null, null, command.CommandText, null }; - DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions); + object?[] restrictions = new object?[4] { null, null, command.CommandText, null }; + DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions)!; if (0 == table.Rows.Count) { throw ADP.NoStoredProcedureExists(command.CommandText); @@ -356,7 +356,7 @@ namespace System.Data.OleDb { return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } - public string QuoteIdentifier(string unquotedIdentifier, OleDbConnection connection) + public string QuoteIdentifier(string unquotedIdentifier, OleDbConnection? connection) { ADP.CheckArgumentNull(unquotedIdentifier, "unquotedIdentifier"); @@ -406,7 +406,7 @@ namespace System.Data.OleDb return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } - public string UnquoteIdentifier(string quotedIdentifier, OleDbConnection connection) + public string UnquoteIdentifier(string quotedIdentifier, OleDbConnection? connection) { ADP.CheckArgumentNull(quotedIdentifier, "quotedIdentifier"); @@ -435,13 +435,11 @@ namespace System.Data.OleDb } } - string unquotedIdentifier; + string? unquotedIdentifier; // ignoring the return value because it is acceptable for the quotedString to not be quoted in this // context. ADP.RemoveStringQuotes(quotePrefix, quoteSuffix, quotedIdentifier, out unquotedIdentifier); - return unquotedIdentifier; - + return unquotedIdentifier!; } - } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index fef98be..0696369 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -25,7 +25,7 @@ namespace System.Data.OleDb { private static readonly object EventInfoMessage = new object(); - public OleDbConnection(string connectionString) : this() + public OleDbConnection(string? connectionString) : this() { ConnectionString = connectionString; } @@ -42,6 +42,7 @@ namespace System.Data.OleDb #pragma warning restore 618 SettingsBindable(true), RefreshProperties(RefreshProperties.All), + AllowNull ] public override string ConnectionString { @@ -55,9 +56,9 @@ namespace System.Data.OleDb } } - private OleDbConnectionString OleDbConnectionStringValue + private OleDbConnectionString? OleDbConnectionStringValue { - get { return (OleDbConnectionString)ConnectionOptions; } + get { return (OleDbConnectionString?)ConnectionOptions; } } [ @@ -67,14 +68,14 @@ namespace System.Data.OleDb { get { - object value = null; + object? value = null; if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_TIMEOUT); } else { - OleDbConnectionString constr = this.OleDbConnectionStringValue; + OleDbConnectionString? constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout; } if (null != value) @@ -93,8 +94,8 @@ namespace System.Data.OleDb { get { - OleDbConnectionString constr = (OleDbConnectionString)UserConnectionOptions; - object value = (null != constr) ? constr.InitialCatalog : string.Empty; + OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; + object? value = (null != constr) ? constr.InitialCatalog : string.Empty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { OleDbConnectionInternal connection = GetOpenConnection(); @@ -115,7 +116,7 @@ namespace System.Data.OleDb value = (null != constr) ? constr.InitialCatalog : string.Empty; } } - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } @@ -126,14 +127,14 @@ namespace System.Data.OleDb { get { - OleDbConnectionString constr = (OleDbConnectionString)UserConnectionOptions; - object value = (null != constr) ? constr.DataSource : string.Empty; + OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; + object? value = (null != constr) ? constr.DataSource : string.Empty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_DATASOURCE); - if ((null == value) || ((value is string) && (0 == (value as string).Length))) + if ((null == value) || ((value is string) && (0 == (value as string)!.Length))) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DATASOURCENAME); } @@ -144,7 +145,7 @@ namespace System.Data.OleDb value = (null != constr) ? constr.DataSource : string.Empty; } } - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } @@ -153,7 +154,7 @@ namespace System.Data.OleDb get { return (null != GetOpenConnection()); } } - internal OleDbTransaction LocalTransaction + internal OleDbTransaction? LocalTransaction { set { @@ -174,8 +175,8 @@ namespace System.Data.OleDb { get { - OleDbConnectionString constr = this.OleDbConnectionStringValue; - string value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null); + OleDbConnectionString? constr = this.OleDbConnectionStringValue; + string? value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null); return ((null != value) ? value : string.Empty); } } @@ -184,7 +185,8 @@ namespace System.Data.OleDb { get { - return (OleDbConnectionPoolGroupProviderInfo)PoolGroup.ProviderInfo; + Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); + return (OleDbConnectionPoolGroupProviderInfo)PoolGroup!.ProviderInfo!; } } @@ -214,7 +216,7 @@ namespace System.Data.OleDb { if (IsOpen) { - object value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS); + object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS); if (value is int) { int connectionStatus = (int)value; @@ -238,7 +240,7 @@ namespace System.Data.OleDb } } - public event OleDbInfoMessageEventHandler InfoMessage + public event OleDbInfoMessageEventHandler? InfoMessage { add { @@ -250,7 +252,7 @@ namespace System.Data.OleDb } } - internal UnsafeNativeMethods.ICommandText ICommandText() + internal UnsafeNativeMethods.ICommandText? ICommandText() { Debug.Assert(null != GetOpenConnection(), "ICommandText closed"); return GetOpenConnection().ICommandText(); @@ -291,7 +293,7 @@ namespace System.Data.OleDb Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString QuotedIdentifierCase"); int quotedIdentifierCase; - object value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); + object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); if (value is int) {// not OleDbPropertyStatus quotedIdentifierCase = (int)value; @@ -379,15 +381,15 @@ namespace System.Data.OleDb return transaction; } - internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID) + internal object? GetDataSourcePropertyValue(Guid propertySet, int propertyID) { OleDbConnectionInternal connection = GetOpenConnection(); return connection.GetDataSourcePropertyValue(propertySet, propertyID); } - internal object GetDataSourceValue(Guid propertySet, int propertyID) + internal object? GetDataSourceValue(Guid propertySet, int propertyID) { - object value = GetDataSourcePropertyValue(propertySet, propertyID); + object? value = GetDataSourcePropertyValue(propertySet, propertyID); if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) { value = null; @@ -398,7 +400,7 @@ namespace System.Data.OleDb private OleDbConnectionInternal GetOpenConnection() { DbConnectionInternal innerConnection = InnerConnection; - return (innerConnection as OleDbConnectionInternal); + return (innerConnection as OleDbConnectionInternal)!; } internal void GetLiteralQuotes(string method, out string quotePrefix, out string quoteSuffix) @@ -407,27 +409,19 @@ namespace System.Data.OleDb OleDbConnectionPoolGroupProviderInfo info = ProviderInfo; if (info.HasQuoteFix) { - quotePrefix = info.QuotePrefix; - quoteSuffix = info.QuoteSuffix; + quotePrefix = info.QuotePrefix!; + quoteSuffix = info.QuoteSuffix!; } else { OleDbConnectionInternal connection = GetOpenConnection(); - quotePrefix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_PREFIX); - quoteSuffix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_SUFFIX); - if (null == quotePrefix) - { - quotePrefix = ""; - } - if (null == quoteSuffix) - { - quoteSuffix = quotePrefix; - } + quotePrefix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_PREFIX) ?? ""; + quoteSuffix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_SUFFIX) ?? ""; info.SetQuoteFix(quotePrefix, quoteSuffix); } } - public DataTable GetOleDbSchemaTable(Guid schema, object[] restrictions) + public DataTable? GetOleDbSchemaTable(Guid schema, object?[]? restrictions) { CheckStateOpen(ADP.GetOleDbSchemaTable); OleDbConnectionInternal connection = GetOpenConnection(); @@ -474,7 +468,7 @@ namespace System.Data.OleDb } } - internal DataTable GetSchemaRowset(Guid schema, object[] restrictions) + internal DataTable? GetSchemaRowset(Guid schema, object?[] restrictions) { Debug.Assert(null != GetOpenConnection(), "GetSchemaRowset closed"); return GetOpenConnection().GetSchemaRowset(schema, restrictions); @@ -494,7 +488,7 @@ namespace System.Data.OleDb internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode) { - OleDbInfoMessageEventHandler handler = (OleDbInfoMessageEventHandler)Events[EventInfoMessage]; + OleDbInfoMessageEventHandler? handler = (OleDbInfoMessageEventHandler?)Events[EventInfoMessage]; if (null != handler) { try @@ -522,7 +516,7 @@ namespace System.Data.OleDb // need to manually enlist in some cases, because // native OLE DB doesn't know about SysTx transactions. - if ((0 != (ODB.DBPROPVAL_OS_TXNENLISTMENT & ((OleDbConnectionString)(this.ConnectionOptions)).OleDbServices)) + if ((0 != (ODB.DBPROPVAL_OS_TXNENLISTMENT & ((OleDbConnectionString)(this.ConnectionOptions!)).OleDbServices)) && ADP.NeedManualEnlistment()) { GetOpenConnection().EnlistTransactionInternal(SysTx.Transaction.Current); @@ -541,7 +535,7 @@ namespace System.Data.OleDb if (hr < 0) { - Exception e = OleDbConnection.ProcessResults(hr, null, this); + Exception? e = OleDbConnection.ProcessResults(hr, null, this); if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) { StringBuilder builder = new StringBuilder(); @@ -552,7 +546,7 @@ namespace System.Data.OleDb ODB.PropsetSetFailure(builder, description, dbprops[0].dwStatus); - e = ODB.PropsetSetFailure(builder.ToString(), e); + e = ODB.PropsetSetFailure(builder.ToString(), e!); } if (null != e) { @@ -572,12 +566,12 @@ namespace System.Data.OleDb return GetOpenConnection().SupportSchemaRowset(schema); } - internal OleDbTransaction ValidateTransaction(OleDbTransaction transaction, string method) + internal OleDbTransaction? ValidateTransaction(OleDbTransaction? transaction, string method) { return GetOpenConnection().ValidateTransaction(transaction, method); } - internal static Exception ProcessResults(OleDbHResult hresult, OleDbConnection connection, object src) + internal static Exception? ProcessResults(OleDbHResult hresult, OleDbConnection? connection, object? src) { if ((0 <= (int)hresult) && ((null == connection) || (null == connection.Events[EventInfoMessage]))) { @@ -586,8 +580,8 @@ namespace System.Data.OleDb } // ErrorInfo object is to be checked regardless the hresult returned by the function called - Exception e = null; - UnsafeNativeMethods.IErrorInfo errorInfo = null; + Exception? e = null; + UnsafeNativeMethods.IErrorInfo? errorInfo = null; OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((OleDbHResult.S_OK == hr) && (null != errorInfo)) { @@ -643,7 +637,7 @@ namespace System.Data.OleDb OleDbConnectionFactory.SingletonInstance.ClearAllPools(); } - private static void ResetState(OleDbConnection connection) + private static void ResetState(OleDbConnection? connection) { if (null != connection) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs index a6ab9fd..9b1a7cd 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs @@ -31,13 +31,14 @@ namespace System.Data.OleDb } } - protected override DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) + protected override DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningObject) { - DbConnectionInternal result = new OleDbConnectionInternal((OleDbConnectionString)options, (OleDbConnection)owningObject); + // TODO-NULLABLE: owningObject may actually be null (see DbConnectionPool.CreateObject), in which case this will throw... + DbConnectionInternal result = new OleDbConnectionInternal((OleDbConnectionString)options, (OleDbConnection)owningObject!); return result; } - protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) + protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions? previous) { Debug.Assert(!ADP.IsEmpty(connectionString), "null connectionString"); OleDbConnectionString result = new OleDbConnectionString(connectionString, (null != previous)); @@ -50,17 +51,17 @@ namespace System.Data.OleDb cacheMetaDataFactory = false; OleDbConnectionInternal oleDbInternalConnection = (OleDbConnectionInternal)internalConnection; - OleDbConnection oleDbOuterConnection = oleDbInternalConnection.Connection; + OleDbConnection? oleDbOuterConnection = oleDbInternalConnection.Connection; Debug.Assert(oleDbOuterConnection != null, "outer connection may not be null."); NameValueCollection settings = (NameValueCollection)ConfigurationManager.GetSection("system.data.oledb"); - Stream XMLStream = null; - string providerFileName = oleDbOuterConnection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_PROVIDERFILENAME) as string; + Stream? XMLStream = null; + string? providerFileName = oleDbOuterConnection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_PROVIDERFILENAME) as string; if (settings != null) { - string[] values = null; - string metaDataXML = null; + string[]? values = null; + string? metaDataXML = null; // first try to get the provider specific xml // if providerfilename is not supported we can't build the settings key needed to @@ -81,7 +82,7 @@ namespace System.Data.OleDb // If there is new XML get it if (values != null) { - XMLStream = ADP.GetXmlStreamFromValues(values, metaDataXML); + XMLStream = ADP.GetXmlStreamFromValues(values, metaDataXML!); } } @@ -103,7 +104,7 @@ namespace System.Data.OleDb oleDbInternalConnection.GetSchemaRowsetInformation()); } - protected override DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions) + protected override DbConnectionPoolGroupOptions? CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions) { return null; } @@ -113,9 +114,9 @@ namespace System.Data.OleDb return new OleDbConnectionPoolGroupProviderInfo(); } - internal override DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) + internal override DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnection connection) { - OleDbConnection c = (connection as OleDbConnection); + OleDbConnection? c = (connection as OleDbConnection); if (null != c) { return c.PoolGroup; @@ -125,7 +126,7 @@ namespace System.Data.OleDb internal override void PermissionDemand(DbConnection outerConnection) { - OleDbConnection c = (outerConnection as OleDbConnection); + OleDbConnection? c = (outerConnection as OleDbConnection); if (null != c) { c.PermissionDemand(); @@ -134,7 +135,7 @@ namespace System.Data.OleDb internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { - OleDbConnection c = (outerConnection as OleDbConnection); + OleDbConnection? c = (outerConnection as OleDbConnection); if (null != c) { c.PoolGroup = poolGroup; @@ -143,7 +144,7 @@ namespace System.Data.OleDb internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { - OleDbConnection c = (owningObject as OleDbConnection); + OleDbConnection? c = (owningObject as OleDbConnection); if (null != c) { c.SetInnerConnectionEvent(to); @@ -152,7 +153,7 @@ namespace System.Data.OleDb internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { - OleDbConnection c = (owningObject as OleDbConnection); + OleDbConnection? c = (owningObject as OleDbConnection); if (null != c) { return c.SetInnerConnectionFrom(to, from); @@ -162,7 +163,7 @@ namespace System.Data.OleDb internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { - OleDbConnection c = (owningObject as OleDbConnection); + OleDbConnection? c = (owningObject as OleDbConnection); if (null != c) { c.SetInnerConnectionTo(to); diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs index e4d1e50..09ab698 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs @@ -15,7 +15,7 @@ namespace System.Data.OleDb internal sealed class OleDbConnectionInternal : DbConnectionInternal, IDisposable { - private static volatile OleDbServicesWrapper idataInitialize; + private static volatile OleDbServicesWrapper? idataInitialize; private static readonly object dataInitializeLock = new object(); internal readonly OleDbConnectionString ConnectionString; // parsed connection string attributes @@ -50,18 +50,18 @@ namespace System.Data.OleDb // offered much better performance. // the "Data Source object". - private readonly DataSourceWrapper _datasrcwrp; + private readonly DataSourceWrapper? _datasrcwrp; // the "Session object". - private readonly SessionWrapper _sessionwrp; + private readonly SessionWrapper? _sessionwrp; - private WeakReference weakTransaction; + private WeakReference? weakTransaction; // When set to true the current connection is enlisted in a transaction that must be // un-enlisted during Deactivate. private bool _unEnlistDuringDeactivate; - internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection connection) : base() + internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection? connection) : base() { Debug.Assert((null != constr) && !constr.IsEmpty, "empty connectionstring"); ConnectionString = constr; @@ -100,7 +100,7 @@ namespace System.Data.OleDb } else { - Exception e = OleDbConnection.ProcessResults(hr, null, null); + Exception? e = OleDbConnection.ProcessResults(hr, null, null); Debug.Assert(null != e, "CreateSessionError"); throw e; } @@ -123,11 +123,11 @@ namespace System.Data.OleDb } } - internal OleDbConnection Connection + internal OleDbConnection? Connection { get { - return (OleDbConnection)Owner; + return (OleDbConnection?)Owner; } } @@ -139,14 +139,14 @@ namespace System.Data.OleDb } } - internal OleDbTransaction LocalTransaction + internal OleDbTransaction? LocalTransaction { get { - OleDbTransaction result = null; + OleDbTransaction? result = null; if (null != weakTransaction) { - result = ((OleDbTransaction)weakTransaction.Target); + result = ((OleDbTransaction?)weakTransaction.Target); } return result; } @@ -171,8 +171,8 @@ namespace System.Data.OleDb // consider making a method, not a property get { - object value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSVER); - return Convert.ToString(value, CultureInfo.InvariantCulture); + object value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSVER)!; + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } @@ -218,12 +218,12 @@ namespace System.Data.OleDb } // optional interface, unsafe cast - internal UnsafeNativeMethods.ICommandText ICommandText() + internal UnsafeNativeMethods.ICommandText? ICommandText() { Debug.Assert(null != _datasrcwrp, "IDBCreateCommand: null datasource"); Debug.Assert(null != _sessionwrp, "IDBCreateCommand: null session"); - object icommandText = null; + object? icommandText = null; OleDbHResult hr = _sessionwrp.CreateCommand(ref icommandText); Debug.Assert((0 <= hr) || (null == icommandText), "CreateICommandText: error with ICommandText"); @@ -238,23 +238,23 @@ namespace System.Data.OleDb SafeNativeMethods.Wrapper.ClearErrorInfo(); } } - return (UnsafeNativeMethods.ICommandText)icommandText; + return (UnsafeNativeMethods.ICommandText?)icommandText; } - protected override void Activate(SysTx.Transaction transaction) + protected override void Activate(SysTx.Transaction? transaction) { throw ADP.NotSupported(); } public override DbTransaction BeginTransaction(IsolationLevel isolationLevel) { - OleDbConnection outerConnection = Connection; + OleDbConnection outerConnection = Connection!; if (null != LocalTransaction) { throw ADP.ParallelTransactionsNotSupported(outerConnection); } - object unknown = null; + object? unknown = null; OleDbTransaction transaction; try { @@ -262,10 +262,10 @@ namespace System.Data.OleDb Debug.Assert(null != _datasrcwrp, "ITransactionLocal: null datasource"); Debug.Assert(null != _sessionwrp, "ITransactionLocal: null session"); unknown = _sessionwrp.ComWrapper(); - UnsafeNativeMethods.ITransactionLocal value = (unknown as UnsafeNativeMethods.ITransactionLocal); + UnsafeNativeMethods.ITransactionLocal? value = (unknown as UnsafeNativeMethods.ITransactionLocal); if (null == value) { - throw ODB.TransactionsNotSupported(Provider, (Exception)null); + throw ODB.TransactionsNotSupported(Provider, null); } transaction.BeginInternal(value); } @@ -294,7 +294,7 @@ namespace System.Data.OleDb // Un-enlist transaction as OLEDB connection pool is unaware of managed transactions. EnlistTransactionInternal(null); } - OleDbTransaction transaction = LocalTransaction; + OleDbTransaction? transaction = LocalTransaction; if (null != transaction) { LocalTransaction = null; @@ -318,7 +318,7 @@ namespace System.Data.OleDb base.Dispose(); } - public override void EnlistTransaction(SysTx.Transaction transaction) + public override void EnlistTransaction(SysTx.Transaction? transaction) { if (null != LocalTransaction) { @@ -327,15 +327,15 @@ namespace System.Data.OleDb EnlistTransactionInternal(transaction); } - internal void EnlistTransactionInternal(SysTx.Transaction transaction) + internal void EnlistTransactionInternal(SysTx.Transaction? transaction) { - SysTx.IDtcTransaction oleTxTransaction = ADP.GetOletxTransaction(transaction); + SysTx.IDtcTransaction? oleTxTransaction = ADP.GetOletxTransaction(transaction); using (ITransactionJoinWrapper transactionJoin = ITransactionJoin()) { if (null == transactionJoin.Value) { - throw ODB.TransactionsNotSupported(Provider, (Exception)null); + throw ODB.TransactionsNotSupported(Provider, null); } transactionJoin.Value.JoinTransaction(oleTxTransaction, (int)IsolationLevel.Unspecified, 0, IntPtr.Zero); _unEnlistDuringDeactivate = (null != transaction); @@ -343,9 +343,9 @@ namespace System.Data.OleDb EnlistedTransaction = transaction; } - internal object GetDataSourceValue(Guid propertySet, int propertyID) + internal object? GetDataSourceValue(Guid propertySet, int propertyID) { - object value = GetDataSourcePropertyValue(propertySet, propertyID); + object? value = GetDataSourcePropertyValue(propertySet, propertyID); if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) { value = null; @@ -353,7 +353,7 @@ namespace System.Data.OleDb return value; } - internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID) + internal object? GetDataSourcePropertyValue(Guid propertySet, int propertyID) { OleDbHResult hr; ItagDBPROP[] dbprops; @@ -380,11 +380,12 @@ namespace System.Data.OleDb return dbprops[0].dwStatus; } - internal DataTable BuildInfoLiterals() + internal DataTable? BuildInfoLiterals() { using (IDBInfoWrapper wrapper = IDBInfo()) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; + // TODO-NULLABLE: check may not be necessary (and thus method may return non-nullable) if (null == dbInfo) { return null; @@ -445,9 +446,9 @@ namespace System.Data.OleDb } } - internal DataTable BuildInfoKeywords() + internal DataTable? BuildInfoKeywords() { - DataTable table = new DataTable(ODB.DbInfoKeywords); + DataTable? table = new DataTable(ODB.DbInfoKeywords); table.Locale = CultureInfo.InvariantCulture; DataColumn keyword = new DataColumn(ODB.Keyword, typeof(string)); table.Columns.Add(keyword); @@ -506,7 +507,7 @@ namespace System.Data.OleDb table.Columns.Add(schemaGuid); table.Columns.Add(restrictionSupport); - SchemaSupport[] supportedSchemas = GetSchemaRowsetInformation(); + SchemaSupport[]? supportedSchemas = GetSchemaRowsetInformation(); if (null != supportedSchemas) { @@ -523,7 +524,7 @@ namespace System.Data.OleDb return table; } - internal string GetLiteralInfo(int literal) + internal string? GetLiteralInfo(int literal) { using (IDBInfoWrapper wrapper = IDBInfo()) { @@ -532,7 +533,7 @@ namespace System.Data.OleDb { return null; } - string literalValue = null; + string? literalValue = null; IntPtr literalInfo = ADP.PtrZero; int literalCount = 0; OleDbHResult hr; @@ -560,17 +561,17 @@ namespace System.Data.OleDb } } - internal SchemaSupport[] GetSchemaRowsetInformation() + internal SchemaSupport[]? GetSchemaRowsetInformation() { OleDbConnectionString constr = ConnectionString; - SchemaSupport[] supportedSchemas = constr.SchemaSupport; + SchemaSupport[]? supportedSchemas = constr.SchemaSupport; if (null != supportedSchemas) { return supportedSchemas; } using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) { - UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value; + UnsafeNativeMethods.IDBSchemaRowset? dbSchemaRowset = wrapper.Value; if (null == dbSchemaRowset) { return null; // IDBSchemaRowset not supported @@ -595,7 +596,7 @@ namespace System.Data.OleDb for (int i = 0, offset = 0; i < supportedSchemas.Length; ++i, offset += ODB.SizeOf_Guid) { IntPtr ptr = ADP.IntPtrOffset(schemaGuids, i * ODB.SizeOf_Guid); - supportedSchemas[i]._schemaRowset = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid)); + supportedSchemas[i]._schemaRowset = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid))!; } } if (ADP.PtrZero != schemaRestrictions) @@ -611,13 +612,13 @@ namespace System.Data.OleDb } } - internal DataTable GetSchemaRowset(Guid schema, object[] restrictions) + internal DataTable? GetSchemaRowset(Guid schema, object?[]? restrictions) { if (null == restrictions) { restrictions = Array.Empty(); } - DataTable dataTable = null; + DataTable? dataTable = null; using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) { UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value; @@ -626,7 +627,7 @@ namespace System.Data.OleDb throw ODB.SchemaRowsetsNotSupported(Provider); } - UnsafeNativeMethods.IRowset rowset = null; + UnsafeNativeMethods.IRowset? rowset = null; OleDbHResult hr; hr = dbSchemaRowset.GetRowset(ADP.PtrZero, ref schema, restrictions.Length, restrictions, ref ODB.IID_IRowset, 0, ADP.PtrZero, out rowset); @@ -656,7 +657,7 @@ namespace System.Data.OleDb // returns true if there is an active data reader on the specified command internal bool HasLiveReader(OleDbCommand cmd) { - OleDbDataReader reader = null; + OleDbDataReader? reader = null; if (null != ReferenceCollection) { @@ -668,15 +669,15 @@ namespace System.Data.OleDb private void ProcessResults(OleDbHResult hr) { - OleDbConnection connection = Connection; // get value from weakref only once - Exception e = OleDbConnection.ProcessResults(hr, connection, connection); + OleDbConnection? connection = Connection; // get value from weakref only once + Exception? e = OleDbConnection.ProcessResults(hr, connection, connection); if (null != e) { throw e; } } internal bool SupportSchemaRowset(Guid schema) { - SchemaSupport[] schemaSupport = GetSchemaRowsetInformation(); + SchemaSupport[]? schemaSupport = GetSchemaRowsetInformation(); if (null != schemaSupport) { for (int i = 0; i < schemaSupport.Length; ++i) @@ -692,8 +693,8 @@ namespace System.Data.OleDb private static object CreateInstanceDataLinks() { - Type datalink = Type.GetTypeFromCLSID(ODB.CLSID_DataLinks, true); - return Activator.CreateInstance(datalink, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); + Type datalink = Type.GetTypeFromCLSID(ODB.CLSID_DataLinks, true)!; + return Activator.CreateInstance(datalink, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null)!; } // @devnote: should be multithread safe access to OleDbConnection.idataInitialize, @@ -701,7 +702,7 @@ namespace System.Data.OleDb // OLE DB will ensure I'll work with just the single pool private static OleDbServicesWrapper GetObjectPool() { - OleDbServicesWrapper wrapper = OleDbConnectionInternal.idataInitialize; + OleDbServicesWrapper? wrapper = OleDbConnectionInternal.idataInitialize; if (null == wrapper) { lock (dataInitializeLock) @@ -764,11 +765,11 @@ namespace System.Data.OleDb OleDbConnectionInternal.idataInitialize = null; } - internal OleDbTransaction ValidateTransaction(OleDbTransaction transaction, string method) + internal OleDbTransaction? ValidateTransaction(OleDbTransaction? transaction, string method) { if (null != this.weakTransaction) { - OleDbTransaction head = (OleDbTransaction)this.weakTransaction.Target; + OleDbTransaction? head = (OleDbTransaction?)this.weakTransaction.Target; if ((null != head) && this.weakTransaction.IsAlive) { head = OleDbTransaction.TransactionUpdate(head); @@ -817,9 +818,9 @@ namespace System.Data.OleDb return null; } - internal Dictionary GetPropertyInfo(Guid[] propertySets) + internal Dictionary? GetPropertyInfo(Guid[] propertySets) { - Dictionary properties = null; + Dictionary? properties = null; if (null == propertySets) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionPoolGroupProviderInfo.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionPoolGroupProviderInfo.cs index fc472aa..594f0db 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionPoolGroupProviderInfo.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionPoolGroupProviderInfo.cs @@ -8,7 +8,7 @@ namespace System.Data.OleDb internal sealed class OleDbConnectionPoolGroupProviderInfo : DbConnectionPoolGroupProviderInfo { private bool _hasQuoteFix; - private string _quotePrefix, _quoteSuffix; + private string? _quotePrefix, _quoteSuffix; internal OleDbConnectionPoolGroupProviderInfo() { @@ -18,11 +18,11 @@ namespace System.Data.OleDb { get { return _hasQuoteFix; } } - internal string QuotePrefix + internal string? QuotePrefix { get { return _quotePrefix; } } - internal string QuoteSuffix + internal string? QuoteSuffix { get { return _quoteSuffix; } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs index 665421f..7f39462 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs @@ -50,7 +50,7 @@ namespace System.Data.OleDb internal static volatile bool _PoolSizeInit; internal static int _PoolSize; - internal static volatile Dictionary _Pool; + internal static volatile Dictionary? _Pool; internal static object _PoolLock = new object(); } @@ -61,11 +61,11 @@ namespace System.Data.OleDb // set during ctor internal readonly bool PossiblePrompt; - internal readonly string ActualConnectionString; // cached value passed to GetDataSource + internal readonly string? ActualConnectionString; // cached value passed to GetDataSource - private readonly string _expandedConnectionString; + private readonly string? _expandedConnectionString; - internal SchemaSupport[] _schemaSupport; + internal SchemaSupport[]? _schemaSupport; internal int _sqlSupport; internal bool _supportMultipleResults; @@ -76,10 +76,10 @@ namespace System.Data.OleDb private int _oledbServices; // these are cached delegates (per unique connectionstring) - internal UnsafeNativeMethods.IUnknownQueryInterface DangerousDataSourceIUnknownQueryInterface; - internal UnsafeNativeMethods.IDBInitializeInitialize DangerousIDBInitializeInitialize; - internal UnsafeNativeMethods.IDBCreateSessionCreateSession DangerousIDBCreateSessionCreateSession; - internal UnsafeNativeMethods.IDBCreateCommandCreateCommand DangerousIDBCreateCommandCreateCommand; + internal UnsafeNativeMethods.IUnknownQueryInterface? DangerousDataSourceIUnknownQueryInterface; + internal UnsafeNativeMethods.IDBInitializeInitialize? DangerousIDBInitializeInitialize; + internal UnsafeNativeMethods.IDBCreateSessionCreateSession? DangerousIDBCreateSessionCreateSession; + internal UnsafeNativeMethods.IDBCreateCommandCreateCommand? DangerousIDBCreateCommandCreateCommand; // since IDBCreateCommand interface may not be supported for a particular provider (only IOpenRowset) // we cache that fact rather than call QueryInterface on every call to Open @@ -89,17 +89,17 @@ namespace System.Data.OleDb // from the UDL file. The UDL file is opened as FileMode.Open, FileAccess.Read, FileShare.Read, allowing concurrent access to it. internal OleDbConnectionString(string connectionString, bool validate) : base(connectionString) { - string prompt = this[KEY.Prompt]; + string? prompt = this[KEY.Prompt]; PossiblePrompt = ((!ADP.IsEmpty(prompt) && (0 != string.Compare(prompt, VALUES.NoPrompt, StringComparison.OrdinalIgnoreCase))) || !ADP.IsEmpty(this[KEY.WindowHandle])); if (!IsEmpty) { - string udlConnectionString = null; + string? udlConnectionString = null; if (!validate) { int position = 0; - string udlFileName = null; + string? udlFileName = null; _expandedConnectionString = ExpandDataDirectories(ref udlFileName, ref position); if (!ADP.IsEmpty(udlFileName)) @@ -112,7 +112,7 @@ namespace System.Data.OleDb if (!ADP.IsEmpty(udlConnectionString)) { - _expandedConnectionString = _expandedConnectionString.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position); + _expandedConnectionString = _expandedConnectionString!.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position); } } } @@ -130,12 +130,12 @@ namespace System.Data.OleDb internal string DataSource { - get { return base.ConvertValueToString(KEY.Data_Source, string.Empty); } + get { return base.ConvertValueToString(KEY.Data_Source, string.Empty)!; } } internal string InitialCatalog { - get { return base.ConvertValueToString(KEY.Initial_Catalog, string.Empty); } + get { return base.ConvertValueToString(KEY.Initial_Catalog, string.Empty)!; } } internal string Provider @@ -143,7 +143,7 @@ namespace System.Data.OleDb get { Debug.Assert(!ADP.IsEmpty(this[KEY.Provider]), "no Provider"); - return this[KEY.Provider]; + return this[KEY.Provider]!; } } @@ -155,7 +155,7 @@ namespace System.Data.OleDb } } - internal SchemaSupport[] SchemaSupport + internal SchemaSupport[]? SchemaSupport { // OleDbConnection.GetSchemaRowsetInformation get { return _schemaSupport; } set { _schemaSupport = value; } @@ -178,7 +178,7 @@ namespace System.Data.OleDb int sqlSupport = _sqlSupport; if (!_hasSqlSupport) { - object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_SQLSUPPORT); + object? value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_SQLSUPPORT); if (value is int) { // not OleDbPropertyStatus sqlSupport = (int)value; @@ -194,7 +194,7 @@ namespace System.Data.OleDb bool supportIRow = _supportIRow; if (!_hasSupportIRow) { - object value = command.GetPropertyValue(OleDbPropertySetGuid.Rowset, ODB.DBPROP_IRow); + object? value = command.GetPropertyValue(OleDbPropertySetGuid.Rowset, ODB.DBPROP_IRow); // SQLOLEDB always returns VARIANT_FALSE for DBPROP_IROW, so base the answer on existance supportIRow = !(value is OleDbPropertyStatus); @@ -209,7 +209,7 @@ namespace System.Data.OleDb bool supportMultipleResults = _supportMultipleResults; if (!_hasSupportMultipleResults) { - object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_MULTIPLERESULTS); + object? value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_MULTIPLERESULTS); if (value is int) {// not OleDbPropertyStatus supportMultipleResults = (ODB.DBPROPVAL_MR_NOTSUPPORTED != (int)value); @@ -228,7 +228,7 @@ namespace System.Data.OleDb int poolsize = UDL._PoolSize; if (!UDL._PoolSizeInit) { - object value = ADP.LocalMachineRegistryValue(UDL.Location, UDL.Pooling); + object? value = ADP.LocalMachineRegistryValue(UDL.Location, UDL.Pooling); if (value is int) { poolsize = (int)value; @@ -241,10 +241,10 @@ namespace System.Data.OleDb } } - private static string LoadStringFromStorage(string udlfilename) + private static string? LoadStringFromStorage(string udlfilename) { - string udlConnectionString = null; - Dictionary udlcache = UDL._Pool; + string? udlConnectionString = null; + Dictionary? udlcache = UDL._Pool; if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString)) { @@ -295,8 +295,8 @@ namespace System.Data.OleDb // [oledb] // ; Everything after this line is an OLE DB initstring // - string connectionString = null; - Exception failure = null; + string? connectionString = null; + Exception? failure = null; try { int hdrlength = ADP.CharSize * UDL.Header.Length; @@ -342,7 +342,7 @@ namespace System.Data.OleDb { throw failure; } - return connectionString.Trim(); + return connectionString!.Trim(); } private string ValidateConnectionString(string connectionString) @@ -358,7 +358,7 @@ namespace System.Data.OleDb throw ADP.InvalidConnectTimeoutValue(); } - string progid = ConvertValueToString(KEY.Data_Provider, null); + string? progid = ConvertValueToString(KEY.Data_Provider, null); if (null != progid) { progid = progid.Trim(); @@ -376,7 +376,7 @@ namespace System.Data.OleDb ValidateProvider(progid); } } - progid = ConvertValueToString(KEY.Provider, string.Empty).Trim(); + progid = ConvertValueToString(KEY.Provider, string.Empty)!.Trim(); ValidateProvider(progid); // will fail on empty 'Provider' value // initialize to default @@ -385,10 +385,10 @@ namespace System.Data.OleDb // our default is -13, we turn off ODB.DBPROPVAL_OS_AGR_AFTERSESSION and ODB.DBPROPVAL_OS_CLIENTCURSOR flags _oledbServices = DbConnectionStringDefaults.OleDbServices; - bool hasOleDBServices = (base.ContainsKey(KEY.Ole_DB_Services) && !ADP.IsEmpty((string)base[KEY.Ole_DB_Services])); + bool hasOleDBServices = (base.ContainsKey(KEY.Ole_DB_Services) && !ADP.IsEmpty((string?)base[KEY.Ole_DB_Services])); if (!hasOleDBServices) { // don't touch registry if they have OLE DB Services - string classid = (string)ADP.ClassesRootRegistryValue(progid + "\\CLSID", string.Empty); + string? classid = (string?)ADP.ClassesRootRegistryValue(progid + "\\CLSID", string.Empty); if ((null != classid) && (0 < classid.Length)) { // CLSID detection of 'Microsoft OLE DB Provider for ODBC Drivers' @@ -397,7 +397,7 @@ namespace System.Data.OleDb { throw ODB.MSDASQLNotSupported(); } - object tmp = ADP.ClassesRootRegistryValue("CLSID\\{" + classidProvider.ToString("D", CultureInfo.InvariantCulture) + "}", ODB.OLEDB_SERVICES); + object? tmp = ADP.ClassesRootRegistryValue("CLSID\\{" + classidProvider.ToString("D", CultureInfo.InvariantCulture) + "}", ODB.OLEDB_SERVICES); if (null != tmp) { // @devnote: some providers like MSDataShape don't have the OLEDB_SERVICES value diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs index 0ffb804..91e07a3 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; @@ -41,8 +42,8 @@ namespace System.Data.OleDb { DbConnectionStringKeywords.OleDbServices, Keywords.OleDbServices }, }; - private string[] _knownKeywords; - private Dictionary _propertyInfo; + private string[]? _knownKeywords; + private Dictionary? _propertyInfo; private string _fileName = DbConnectionStringDefaults.FileName; @@ -58,7 +59,7 @@ namespace System.Data.OleDb _knownKeywords = s_validKeywords; } - public OleDbConnectionStringBuilder(string connectionString) : base() + public OleDbConnectionStringBuilder(string? connectionString) : base() { if (!ADP.IsEmpty(connectionString)) { @@ -66,12 +67,13 @@ namespace System.Data.OleDb } } + [AllowNull] public override object this[string keyword] { get { ADP.CheckArgumentNull(keyword, "keyword"); - object value; + object? value; Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { @@ -81,7 +83,7 @@ namespace System.Data.OleDb { Dictionary dynamic = GetProviderInfo(Provider); OleDbPropertyInfo info = dynamic[keyword]; - value = info._defaultValue; + value = info._defaultValue!; } return value; } @@ -199,7 +201,7 @@ namespace System.Data.OleDb { get { - string[] knownKeywords = _knownKeywords; + string[]? knownKeywords = _knownKeywords; if (null == knownKeywords) { Dictionary dynamic = GetProviderInfo(Provider); @@ -369,11 +371,11 @@ namespace System.Data.OleDb private void SetValue(string keyword, bool value) { - base[keyword] = value.ToString((System.IFormatProvider)null); + base[keyword] = value.ToString(null); } private void SetValue(string keyword, int value) { - base[keyword] = value.ToString((System.IFormatProvider)null); + base[keyword] = value.ToString((System.IFormatProvider?)null); } private void SetValue(string keyword, string value) { @@ -381,7 +383,7 @@ namespace System.Data.OleDb base[keyword] = value; } - public override bool TryGetValue(string keyword, out object value) + public override bool TryGetValue(string keyword, [NotNullWhen(true)] out object? value) { ADP.CheckArgumentNull(keyword, "keyword"); Keywords index; @@ -393,10 +395,10 @@ namespace System.Data.OleDb else if (!base.TryGetValue(keyword, out value)) { Dictionary dynamic = GetProviderInfo(Provider); - OleDbPropertyInfo info; + OleDbPropertyInfo? info; if (dynamic.TryGetValue(keyword, out info)) { - value = info._defaultValue; + value = info._defaultValue!; return true; } return false; @@ -406,13 +408,13 @@ namespace System.Data.OleDb private Dictionary GetProviderInfo(string provider) { - Dictionary providerInfo = _propertyInfo; + Dictionary? providerInfo = _propertyInfo; if (null == providerInfo) { providerInfo = new Dictionary(StringComparer.OrdinalIgnoreCase); if (!ADP.IsEmpty(provider)) { - Dictionary hash = null; + Dictionary? hash = null; try { StringBuilder builder = new StringBuilder(); @@ -420,15 +422,15 @@ namespace System.Data.OleDb OleDbConnectionString constr = new OleDbConnectionString(builder.ToString(), true); // load provider without calling Initialize or CreateDataSource - using (OleDbConnectionInternal connection = new OleDbConnectionInternal(constr, (OleDbConnection)null)) + using (OleDbConnectionInternal connection = new OleDbConnectionInternal(constr, null)) { // get all the init property information for the provider - hash = connection.GetPropertyInfo(new Guid[] { OleDbPropertySetGuid.DBInitAll }); + hash = connection.GetPropertyInfo(new Guid[] { OleDbPropertySetGuid.DBInitAll })!; foreach (KeyValuePair entry in hash) { Keywords index; OleDbPropertyInfo info = entry.Value; - if (!s_keywords.TryGetValue(info._description, out index)) + if (!s_keywords.TryGetValue(info._description!, out index)) { if ((OleDbPropertySetGuid.DBInit == info._propertySet) && ((ODB.DBPROP_INIT_ASYNCH == info._propertyID) || @@ -437,7 +439,7 @@ namespace System.Data.OleDb { continue; // skip this keyword } - providerInfo[info._description] = info; + providerInfo[info._description!] = info; } } @@ -529,7 +531,7 @@ namespace System.Data.OleDb private const int DBSOURCETYPE_DATASOURCE_TDP = 1; private const int DBSOURCETYPE_DATASOURCE_MDP = 3; - private StandardValuesCollection _standardValues; + private StandardValuesCollection? _standardValues; // converter classes should have public ctor public OleDbProviderConverter() @@ -546,16 +548,16 @@ namespace System.Data.OleDb return false; } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext context) { - StandardValuesCollection dataSourceNames = _standardValues; + StandardValuesCollection? dataSourceNames = _standardValues; if (null == _standardValues) { // Get the sources rowset for the SQLOLEDB enumerator DataTable table = (new OleDbEnumerator()).GetElements(); - DataColumn column2 = table.Columns["SOURCES_NAME"]; - DataColumn column5 = table.Columns["SOURCES_TYPE"]; + DataColumn column2 = table.Columns["SOURCES_NAME"]!; + DataColumn column5 = table.Columns["SOURCES_TYPE"]!; //DataColumn column4 = table.Columns["SOURCES_DESCRIPTION"]; System.Collections.Generic.List providerNames = new System.Collections.Generic.List(table.Rows.Count); @@ -597,7 +599,7 @@ namespace System.Data.OleDb internal sealed class OleDbServicesConverter : TypeConverter { - private StandardValuesCollection _standardValues; + private StandardValuesCollection? _standardValues; // converter classes should have public ctor public OleDbServicesConverter() : base() @@ -612,7 +614,7 @@ namespace System.Data.OleDb public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - string svalue = (value as string); + string? svalue = (value as string); if (null != svalue) { int services; @@ -631,7 +633,6 @@ namespace System.Data.OleDb convertedValue |= (int)(OleDbServiceValues)Enum.Parse(typeof(OleDbServiceValues), v, true); } return (int)convertedValue; - ; } else { @@ -669,7 +670,7 @@ namespace System.Data.OleDb public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - StandardValuesCollection standardValues = _standardValues; + StandardValuesCollection? standardValues = _standardValues; if (null == standardValues) { Array objValues = Enum.GetValues(typeof(OleDbServiceValues)); @@ -711,7 +712,7 @@ namespace System.Data.OleDb } if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) { - OleDbConnectionStringBuilder obj = (value as OleDbConnectionStringBuilder); + OleDbConnectionStringBuilder? obj = (value as OleDbConnectionStringBuilder); if (null != obj) { return ConvertToInstanceDescriptor(obj); @@ -724,7 +725,7 @@ namespace System.Data.OleDb { Type[] ctorParams = new Type[] { typeof(string) }; object[] ctorValues = new object[] { options.ConnectionString }; - System.Reflection.ConstructorInfo ctor = typeof(OleDbConnectionStringBuilder).GetConstructor(ctorParams); + System.Reflection.ConstructorInfo ctor = typeof(OleDbConnectionStringBuilder).GetConstructor(ctorParams)!; return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs index 6b772f1..05714ce 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs @@ -13,25 +13,25 @@ namespace System.Data.OleDb private static readonly object EventRowUpdated = new object(); private static readonly object EventRowUpdating = new object(); - private OleDbCommand _deleteCommand, _insertCommand, _selectCommand, _updateCommand; + private OleDbCommand? _deleteCommand, _insertCommand, _selectCommand, _updateCommand; public OleDbDataAdapter() : base() { GC.SuppressFinalize(this); } - public OleDbDataAdapter(OleDbCommand selectCommand) : this() + public OleDbDataAdapter(OleDbCommand? selectCommand) : this() { SelectCommand = selectCommand; } - public OleDbDataAdapter(string selectCommandText, string selectConnectionString) : this() + public OleDbDataAdapter(string? selectCommandText, string? selectConnectionString) : this() { OleDbConnection connection = new OleDbConnection(selectConnectionString); SelectCommand = new OleDbCommand(selectCommandText, connection); } - public OleDbDataAdapter(string selectCommandText, OleDbConnection selectConnection) : this() + public OleDbDataAdapter(string? selectCommandText, OleDbConnection? selectConnection) : this() { SelectCommand = new OleDbCommand(selectCommandText, selectConnection); } @@ -44,80 +44,80 @@ namespace System.Data.OleDb [ DefaultValue(null), ] - public new OleDbCommand DeleteCommand + public new OleDbCommand? DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = value; } } - IDbCommand IDbDataAdapter.DeleteCommand + IDbCommand? IDbDataAdapter.DeleteCommand { get { return _deleteCommand; } - set { _deleteCommand = (OleDbCommand)value; } + set { _deleteCommand = (OleDbCommand?)value; } } [ DefaultValue(null) ] - public new OleDbCommand InsertCommand + public new OleDbCommand? InsertCommand { get { return _insertCommand; } set { _insertCommand = value; } } - IDbCommand IDbDataAdapter.InsertCommand + IDbCommand? IDbDataAdapter.InsertCommand { get { return _insertCommand; } - set { _insertCommand = (OleDbCommand)value; } + set { _insertCommand = (OleDbCommand?)value; } } [ DefaultValue(null) ] - public new OleDbCommand SelectCommand + public new OleDbCommand? SelectCommand { get { return _selectCommand; } set { _selectCommand = value; } } - IDbCommand IDbDataAdapter.SelectCommand + IDbCommand? IDbDataAdapter.SelectCommand { get { return _selectCommand; } - set { _selectCommand = (OleDbCommand)value; } + set { _selectCommand = (OleDbCommand?)value; } } [ DefaultValue(null) ] - public new OleDbCommand UpdateCommand + public new OleDbCommand? UpdateCommand { get { return _updateCommand; } set { _updateCommand = value; } } - IDbCommand IDbDataAdapter.UpdateCommand + IDbCommand? IDbDataAdapter.UpdateCommand { get { return _updateCommand; } - set { _updateCommand = (OleDbCommand)value; } + set { _updateCommand = (OleDbCommand?)value; } } - public event OleDbRowUpdatedEventHandler RowUpdated + public event OleDbRowUpdatedEventHandler? RowUpdated { add { Events.AddHandler(EventRowUpdated, value); } remove { Events.RemoveHandler(EventRowUpdated, value); } } - public event OleDbRowUpdatingEventHandler RowUpdating + public event OleDbRowUpdatingEventHandler? RowUpdating { add { - OleDbRowUpdatingEventHandler handler = (OleDbRowUpdatingEventHandler)Events[EventRowUpdating]; + OleDbRowUpdatingEventHandler? handler = (OleDbRowUpdatingEventHandler?)Events[EventRowUpdating]; // prevent someone from registering two different command builders on the adapter by // silently removing the old one if ((null != handler) && (value.Target is DbCommandBuilder)) { - OleDbRowUpdatingEventHandler d = (OleDbRowUpdatingEventHandler)ADP.FindBuilder(handler); + OleDbRowUpdatingEventHandler? d = (OleDbRowUpdatingEventHandler?)ADP.FindBuilder(handler); if (null != d) { Events.RemoveHandler(EventRowUpdating, d); @@ -133,12 +133,12 @@ namespace System.Data.OleDb return new OleDbDataAdapter(this); } - protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { return new OleDbRowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } - protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { return new OleDbRowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } @@ -179,7 +179,7 @@ namespace System.Data.OleDb return FillFromADODB((object)dataSet, ADODBRecordSet, srcTable, true); } - private int FillFromADODB(object data, object adodb, string srcTable, bool multipleResults) + private int FillFromADODB(object data, object adodb, string? srcTable, bool multipleResults) { Debug.Assert(null != data, "FillFromADODB: null data object"); Debug.Assert(null != adodb, "FillFromADODB: null ADODB"); @@ -200,8 +200,8 @@ namespace System.Data.OleDb */ bool closeRecordset = multipleResults; - UnsafeNativeMethods.ADORecordsetConstruction recordset = (adodb as UnsafeNativeMethods.ADORecordsetConstruction); - UnsafeNativeMethods.ADORecordConstruction record = null; + UnsafeNativeMethods.ADORecordsetConstruction? recordset = (adodb as UnsafeNativeMethods.ADORecordsetConstruction); + UnsafeNativeMethods.ADORecordConstruction? record = null; if (null != recordset) { @@ -237,10 +237,10 @@ namespace System.Data.OleDb do { - string tmp = null; + string? tmp = null; if (data is DataSet) { - tmp = GetSourceTableName(srcTable, resultCount); + tmp = GetSourceTableName(srcTable!, resultCount); } results += FillFromRecordset(data, recordset, tmp, out incrementResultCount); @@ -257,7 +257,7 @@ namespace System.Data.OleDb // Current provider does not support returning multiple recordsets from a single execution. if (ODB.ADODB_NextResultError != (int)hr) { - UnsafeNativeMethods.IErrorInfo errorInfo = null; + UnsafeNativeMethods.IErrorInfo? errorInfo = null; UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); string message = string.Empty; @@ -287,7 +287,7 @@ namespace System.Data.OleDb } else if (null != record) { - results = FillFromRecord(data, record, srcTable); + results = FillFromRecord(data, record, srcTable!); if (closeRecordset) { FillClose(false, record); @@ -304,12 +304,12 @@ namespace System.Data.OleDb // return base.Fill(dataTable, dataReader); //} - private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConstruction recordset, string srcTable, out bool incrementResultCount) + private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConstruction recordset, string? srcTable, out bool incrementResultCount) { incrementResultCount = false; IntPtr chapter; /*ODB.DB_NULL_HCHAPTER*/ - object result = null; + object? result = null; try { result = recordset.get_Rowset(); @@ -331,7 +331,7 @@ namespace System.Data.OleDb CommandBehavior behavior = (MissingSchemaAction.AddWithKey != MissingSchemaAction) ? 0 : CommandBehavior.KeyInfo; behavior |= CommandBehavior.SequentialAccess; - OleDbDataReader dataReader = null; + OleDbDataReader? dataReader = null; try { // intialized with chapter only since we don't want ReleaseChapter called for this chapter handle @@ -350,7 +350,7 @@ namespace System.Data.OleDb } else { - return base.Fill((DataSet)data, srcTable, dataReader, 0, 0); + return base.Fill((DataSet)data, srcTable!, dataReader, 0, 0); } } } @@ -367,7 +367,7 @@ namespace System.Data.OleDb private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstruction record, string srcTable) { - object result = null; + object? result = null; try { result = record.get_Row(); @@ -388,7 +388,7 @@ namespace System.Data.OleDb CommandBehavior behavior = (MissingSchemaAction.AddWithKey != MissingSchemaAction) ? 0 : CommandBehavior.KeyInfo; behavior |= CommandBehavior.SequentialAccess | CommandBehavior.SingleRow; - OleDbDataReader dataReader = null; + OleDbDataReader? dataReader = null; try { dataReader = new OleDbDataReader(null, null, 0, behavior); @@ -428,7 +428,7 @@ namespace System.Data.OleDb } if ((0 < (int)hr) && (ODB.ADODB_AlreadyClosedError != (int)hr)) { - UnsafeNativeMethods.IErrorInfo errorInfo = null; + UnsafeNativeMethods.IErrorInfo? errorInfo = null; UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); string message = string.Empty; throw new COMException(message, (int)hr); @@ -437,7 +437,7 @@ namespace System.Data.OleDb protected override void OnRowUpdated(RowUpdatedEventArgs value) { - OleDbRowUpdatedEventHandler handler = (OleDbRowUpdatedEventHandler)Events[EventRowUpdated]; + OleDbRowUpdatedEventHandler? handler = (OleDbRowUpdatedEventHandler?)Events[EventRowUpdated]; if ((null != handler) && (value is OleDbRowUpdatedEventArgs)) { handler(this, (OleDbRowUpdatedEventArgs)value); @@ -447,7 +447,7 @@ namespace System.Data.OleDb protected override void OnRowUpdating(RowUpdatingEventArgs value) { - OleDbRowUpdatingEventHandler handler = (OleDbRowUpdatingEventHandler)Events[EventRowUpdating]; + OleDbRowUpdatingEventHandler? handler = (OleDbRowUpdatingEventHandler?)Events[EventRowUpdating]; if ((null != handler) && (value is OleDbRowUpdatingEventArgs)) { handler(this, (OleDbRowUpdatingEventArgs)value); diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 5560f3f..cf0a8ef 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -18,17 +18,17 @@ namespace System.Data.OleDb private readonly CommandBehavior _commandBehavior; // object model interaction - private OleDbConnection _connection; - private OleDbCommand _command; + private OleDbConnection? _connection; + private OleDbCommand? _command; // DataReader owns the parameter bindings until CloseDataReader // this allows OleDbCommand.Dispose to not require OleDbDataReader.Dispose - private Bindings _parameterBindings; + private Bindings? _parameterBindings; // OLEDB interfaces - private UnsafeNativeMethods.IMultipleResults _imultipleResults; - private UnsafeNativeMethods.IRowset _irowset; - private UnsafeNativeMethods.IRow _irow; + private UnsafeNativeMethods.IMultipleResults? _imultipleResults; + private UnsafeNativeMethods.IRowset? _irowset; + private UnsafeNativeMethods.IRow? _irow; private ChapterHandle _chapterHandle = ChapterHandle.DB_NULL_HCHAPTER; @@ -38,7 +38,7 @@ namespace System.Data.OleDb private long _sequentialBytesRead; private int _sequentialOrdinal; - private Bindings[] _bindings; // _metdata contains the ColumnBinding + private Bindings?[]? _bindings; // _metdata contains the ColumnBinding // do we need to jump to the next accessor private int _nextAccessorForRetrieval; @@ -55,20 +55,20 @@ namespace System.Data.OleDb // cached information for Reading (rowhandles/status) private IntPtr _rowHandleFetchCount; // (>1 fails against jet) - private RowHandleBuffer _rowHandleNativeBuffer; + private RowHandleBuffer? _rowHandleNativeBuffer; private IntPtr _rowFetchedCount; private int _currentRow; - private DataTable _dbSchemaTable; + private DataTable? _dbSchemaTable; private int _visibleFieldCount; - private MetaData[] _metadata; - private FieldNameLookup _fieldNameLookup; + private MetaData[]? _metadata; + private FieldNameLookup? _fieldNameLookup; // ctor for an ICommandText, IMultipleResults, IRowset, IRow // ctor for an ADODB.Recordset, ADODB.Record or Hierarchial resultset - internal OleDbDataReader(OleDbConnection connection, OleDbCommand command, int depth, CommandBehavior commandBehavior) + internal OleDbDataReader(OleDbConnection? connection, OleDbCommand? command, int depth, CommandBehavior commandBehavior) { _connection = connection; _command = command; @@ -92,12 +92,12 @@ namespace System.Data.OleDb } } - internal void InitializeIMultipleResults(object result) + internal void InitializeIMultipleResults(object? result) { Initialize(); - _imultipleResults = (UnsafeNativeMethods.IMultipleResults)result; // maybe null if no results + _imultipleResults = (UnsafeNativeMethods.IMultipleResults?)result; // maybe null if no results } - internal void InitializeIRowset(object result, ChapterHandle chapterHandle, IntPtr recordsAffected) + internal void InitializeIRowset(object? result, ChapterHandle chapterHandle, IntPtr recordsAffected) { // if from ADODB, connection will be null if ((null == _connection) || (ChapterHandle.DB_NULL_HCHAPTER != chapterHandle)) @@ -107,21 +107,21 @@ namespace System.Data.OleDb Initialize(); _recordsAffected = recordsAffected; - _irowset = (UnsafeNativeMethods.IRowset)result; // maybe null if no results + _irowset = (UnsafeNativeMethods.IRowset?)result; // maybe null if no results _chapterHandle = chapterHandle; } - internal void InitializeIRow(object result, IntPtr recordsAffected) + internal void InitializeIRow(object? result, IntPtr recordsAffected) { Initialize(); Debug.Assert(_singleRow, "SingleRow not already set"); _singleRow = true; _recordsAffected = recordsAffected; - _irow = (UnsafeNativeMethods.IRow)result; // maybe null if no results + _irow = (UnsafeNativeMethods.IRow?)result; // maybe null if no results _hasRows = (null != _irow); } - internal OleDbCommand Command + internal OleDbCommand? Command { get { @@ -149,7 +149,7 @@ namespace System.Data.OleDb { throw ADP.DataReaderClosed("FieldCount"); } - MetaData[] metadata = MetaData; + MetaData[]? metadata = MetaData; return ((null != metadata) ? metadata.Length : 0); } } @@ -178,7 +178,7 @@ namespace System.Data.OleDb } } - private MetaData[] MetaData + private MetaData[]? MetaData { get { return _metadata; } } @@ -232,7 +232,7 @@ namespace System.Data.OleDb private UnsafeNativeMethods.IRowset IRowset() { - UnsafeNativeMethods.IRowset irowset = _irowset; + UnsafeNativeMethods.IRowset? irowset = _irowset; if (null == irowset) { Debug.Assert(false, "object is disposed"); @@ -243,7 +243,7 @@ namespace System.Data.OleDb private UnsafeNativeMethods.IRow IRow() { - UnsafeNativeMethods.IRow irow = _irow; + UnsafeNativeMethods.IRow? irow = _irow; if (null == irow) { Debug.Assert(false, "object is disposed"); @@ -254,10 +254,10 @@ namespace System.Data.OleDb public override DataTable GetSchemaTable() { - DataTable schemaTable = _dbSchemaTable; + DataTable? schemaTable = _dbSchemaTable; if (null == schemaTable) { - MetaData[] metadata = MetaData; + MetaData[]? metadata = MetaData; if ((null != metadata) && (0 < metadata.Length)) { if ((0 < metadata.Length) && _useIColumnsRowset && (null != _connection)) @@ -273,7 +273,10 @@ namespace System.Data.OleDb //GetSchemaTable() is defined to return null after NextResult returns false //throw ADP.DataReaderNoData(); } +// TODO-NULLABLE: Behavior change (https://github.com/dotnet/runtime/issues/509) +#nullable disable return schemaTable; +#nullable enable } internal void BuildMetaInfo() @@ -451,7 +454,7 @@ namespace System.Data.OleDb Debug.Assert(null == _dbSchemaTable, "non-null SchemaTable"); Debug.Assert(null == _metadata, "non-null metadata"); Debug.Assert(null != handle, "unexpected null rowset"); - UnsafeNativeMethods.IColumnsInfo icolumnsInfo = (handle as UnsafeNativeMethods.IColumnsInfo); + UnsafeNativeMethods.IColumnsInfo? icolumnsInfo = (handle as UnsafeNativeMethods.IColumnsInfo); if (null == icolumnsInfo) { _dbSchemaTable = null; @@ -606,11 +609,11 @@ namespace System.Data.OleDb { Debug.Assert(null == _dbSchemaTable, "BuildSchemaTableRowset - non-null SchemaTable"); Debug.Assert(null != handle, "BuildSchemaTableRowset(object) - unexpected null handle"); - UnsafeNativeMethods.IColumnsRowset icolumnsRowset = (handle as UnsafeNativeMethods.IColumnsRowset); + UnsafeNativeMethods.IColumnsRowset? icolumnsRowset = (handle as UnsafeNativeMethods.IColumnsRowset); if (null != icolumnsRowset) { - UnsafeNativeMethods.IRowset rowset = null; + UnsafeNativeMethods.IRowset? rowset = null; IntPtr cOptColumns; OleDbHResult hr; @@ -643,11 +646,11 @@ namespace System.Data.OleDb public override void Close() { - OleDbConnection con = _connection; - OleDbCommand cmd = _command; - Bindings bindings = _parameterBindings; - _connection = null; - _command = null; + OleDbConnection? con = _connection; + OleDbCommand? cmd = _command; + Bindings? bindings = _parameterBindings; + _connection = null!; + _command = null!; _parameterBindings = null; _isClosed = true; @@ -667,7 +670,7 @@ namespace System.Data.OleDb } else { - UnsafeNativeMethods.IMultipleResults multipleResults = _imultipleResults; + UnsafeNativeMethods.IMultipleResults? multipleResults = _imultipleResults; _imultipleResults = null; if (null != multipleResults) @@ -682,7 +685,7 @@ namespace System.Data.OleDb if ((null != cmd) && !cmd.canceling) { IntPtr affected = IntPtr.Zero; - OleDbException nextResultsFailure = NextResults(multipleResults, null, cmd, out affected); + OleDbException? nextResultsFailure = NextResults(multipleResults, null, cmd, out affected); _recordsAffected = AddRecordsAffected(_recordsAffected, affected); if (null != nextResultsFailure) { @@ -718,7 +721,7 @@ namespace System.Data.OleDb } // release unmanaged objects - RowHandleBuffer rowHandleNativeBuffer = _rowHandleNativeBuffer; + RowHandleBuffer? rowHandleNativeBuffer = _rowHandleNativeBuffer; _rowHandleNativeBuffer = null; if (null != rowHandleNativeBuffer) { @@ -738,7 +741,7 @@ namespace System.Data.OleDb // called from the connection which will remove this from its ReferenceCollection // we want the NextResult behavior, but no errors - _connection = null; + _connection = null!; Close(); } @@ -754,16 +757,16 @@ namespace System.Data.OleDb _nextAccessorForRetrieval = 0; _nextValueForRetrieval = 0; - Bindings[] bindings = _bindings; + Bindings?[]? bindings = _bindings; _bindings = null; if (null != bindings) { for (int i = 0; i < bindings.Length; ++i) { - if (null != bindings[i]) + if (bindings[i] is Bindings binding) { - bindings[i].Dispose(); + binding.Dispose(); } } } @@ -779,7 +782,7 @@ namespace System.Data.OleDb private void DisposeNativeMultipleResults() { - UnsafeNativeMethods.IMultipleResults imultipleResults = _imultipleResults; + UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults; _imultipleResults = null; if (null != imultipleResults) @@ -790,7 +793,7 @@ namespace System.Data.OleDb private void DisposeNativeRowset() { - UnsafeNativeMethods.IRowset irowset = _irowset; + UnsafeNativeMethods.IRowset? irowset = _irowset; _irowset = null; ChapterHandle chapter = _chapterHandle; @@ -809,7 +812,7 @@ namespace System.Data.OleDb private void DisposeNativeRow() { - UnsafeNativeMethods.IRow irow = _irow; + UnsafeNativeMethods.IRow? irow = _irow; _irow = null; if (null != irow) @@ -860,7 +863,7 @@ namespace System.Data.OleDb return binding; } - public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length) + public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int bufferIndex, int length) { ColumnBinding binding = DoSequentialCheck(ordinal, dataIndex, ADP.GetBytes); byte[] value = binding.ValueByteArray(); @@ -896,7 +899,7 @@ namespace System.Data.OleDb return byteCount; } - public override long GetChars(int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length) + public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int bufferIndex, int length) { ColumnBinding binding = DoSequentialCheck(ordinal, dataIndex, ADP.GetChars); string value = binding.ValueString(); @@ -951,21 +954,22 @@ namespace System.Data.OleDb return GetData(ordinal); } - internal OleDbDataReader ResetChapter(int bindingIndex, int index, RowBinding rowbinding, int valueOffset) + internal OleDbDataReader? ResetChapter(int bindingIndex, int index, RowBinding rowbinding, int valueOffset) { - return GetDataForReader(_metadata[bindingIndex + index].ordinal, rowbinding, valueOffset); + return GetDataForReader(_metadata![bindingIndex + index].ordinal, rowbinding, valueOffset); } - private OleDbDataReader GetDataForReader(IntPtr ordinal, RowBinding rowbinding, int valueOffset) + private OleDbDataReader? GetDataForReader(IntPtr ordinal, RowBinding rowbinding, int valueOffset) { UnsafeNativeMethods.IRowsetInfo rowsetInfo = IRowsetInfo(); - UnsafeNativeMethods.IRowset result; + UnsafeNativeMethods.IRowset? result; OleDbHResult hr; hr = rowsetInfo.GetReferencedRowset((IntPtr)ordinal, ref ODB.IID_IRowset, out result); ProcessResults(hr); - OleDbDataReader reader = null; + OleDbDataReader? reader = null; + // TODO: Not sure if GetReferenceRowset above actually returns null, calling code seems to assume it doesn't if (null != result) { // only when the first datareader is closed will the connection close @@ -1021,7 +1025,8 @@ namespace System.Data.OleDb { if (null != _metadata) { - return _metadata[index].type.dataType; + // TODO-NULLABLE: Should throw if null (empty), though it probably doesn't happen + return _metadata[index].type.dataType!; } throw ADP.DataReaderNoData(); } @@ -1102,7 +1107,7 @@ namespace System.Data.OleDb throw ADP.NonSequentialColumnAccess(ordinal, _nextValueForRetrieval); } // @usernote: user may encounter the IndexOutOfRangeException - MetaData info = _metadata[ordinal]; + MetaData info = _metadata![ordinal]; return info; } @@ -1127,7 +1132,7 @@ namespace System.Data.OleDb { if (_nextValueForRetrieval != binding.Index) { // release old value - _metadata[_nextValueForRetrieval].columnBinding.ResetValue(); + _metadata![_nextValueForRetrieval].columnBinding.ResetValue(); } _nextAccessorForRetrieval = binding.IndexForAccessor; } @@ -1166,7 +1171,7 @@ namespace System.Data.OleDb } DoValueCheck(0); int count = Math.Min(values.Length, _visibleFieldCount); - for (int i = 0; (i < _metadata.Length) && (i < count); ++i) + for (int i = 0; (i < _metadata!.Length) && (i < count); ++i) { ColumnBinding binding = GetValueBinding(_metadata[i]); values[i] = binding.Value(); @@ -1187,7 +1192,7 @@ namespace System.Data.OleDb private void ProcessResults(OleDbHResult hr) { - Exception e; + Exception? e; if (null != _command) { e = OleDbConnection.ProcessResults(hr, _connection, _command); @@ -1249,10 +1254,10 @@ namespace System.Data.OleDb _isRead = false; } - internal static OleDbException NextResults(UnsafeNativeMethods.IMultipleResults imultipleResults, OleDbConnection connection, OleDbCommand command, out IntPtr recordsAffected) + internal static OleDbException? NextResults(UnsafeNativeMethods.IMultipleResults? imultipleResults, OleDbConnection? connection, OleDbCommand command, out IntPtr recordsAffected) { recordsAffected = ADP.RecordsUnaffected; - List exceptions = null; + List? exceptions = null; if (null != imultipleResults) { object result; @@ -1278,10 +1283,10 @@ namespace System.Data.OleDb } if (null != connection) { - Exception e = OleDbConnection.ProcessResults(hr, connection, command); + Exception? e = OleDbConnection.ProcessResults(hr, connection, command); if (null != e) { - OleDbException excep = (e as OleDbException); + OleDbException? excep = (e as OleDbException); if (null != excep) { if (null == exceptions) @@ -1337,8 +1342,8 @@ namespace System.Data.OleDb } _fieldNameLookup = null; - OleDbCommand command = _command; - UnsafeNativeMethods.IMultipleResults imultipleResults = _imultipleResults; + OleDbCommand? command = _command; + UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults; if (null != imultipleResults) { DisposeOpenResults(); @@ -1349,7 +1354,7 @@ namespace System.Data.OleDb Debug.Assert(null == _irow, "NextResult: row loop check"); Debug.Assert(null == _irowset, "NextResult: rowset loop check"); - object result = null; + object? result = null; OleDbHResult hr; IntPtr affected; @@ -1394,7 +1399,7 @@ namespace System.Data.OleDb public override bool Read() { bool retflag = false; - OleDbCommand command = _command; + OleDbCommand? command = _command; if ((null != command) && command.canceling) { DisposeOpenResults(); @@ -1439,7 +1444,7 @@ namespace System.Data.OleDb else { _isRead = true; - return (0 < _metadata.Length); + return (0 < _metadata!.Length); } return false; } @@ -1447,7 +1452,7 @@ namespace System.Data.OleDb private bool ReadRowset() { Debug.Assert(null != _irowset, "ReadRow: null IRowset"); - Debug.Assert(0 <= _metadata.Length, "incorrect state for fieldCount"); + Debug.Assert(0 <= _metadata!.Length, "incorrect state for fieldCount"); // releases bindings as necessary // bumps current row, else resets it back to initial state @@ -1477,11 +1482,11 @@ namespace System.Data.OleDb if (0 < (int)_rowFetchedCount) { // release the data in the current row - Bindings[] bindings = _bindings; + Bindings?[]? bindings = _bindings; Debug.Assert(null != bindings, "ReleaseCurrentRow: null dbBindings"); for (int i = 0; (i < bindings.Length) && (i < _nextAccessorForRetrieval); ++i) { - bindings[i].CleanupBindings(); + bindings[i]!.CleanupBindings(); } _nextAccessorForRetrieval = 0; _nextValueForRetrieval = 0; @@ -1516,7 +1521,7 @@ namespace System.Data.OleDb { _rowHandleFetchCount = new IntPtr(1); - object maxRows = GetPropertyValue(ODB.DBPROP_MAXROWS); + object? maxRows = GetPropertyValue(ODB.DBPROP_MAXROWS); if (maxRows is int) { _rowHandleFetchCount = new IntPtr((int)maxRows); @@ -1545,7 +1550,7 @@ namespace System.Data.OleDb int bindingCount = 0; int currentBindingIndex = 0; - MetaData[] metadata = _metadata; + MetaData[] metadata = _metadata!; int[] indexToBinding = new int[metadata.Length]; int[] indexWithinBinding = new int[metadata.Length]; @@ -1723,7 +1728,7 @@ namespace System.Data.OleDb OleDbHResult hr = 0; - RowHandleBuffer rowHandleBuffer = _rowHandleNativeBuffer; + RowHandleBuffer rowHandleBuffer = _rowHandleNativeBuffer!; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1777,7 +1782,7 @@ namespace System.Data.OleDb IntPtr rowHandle = _rowHandleNativeBuffer.GetRowHandle(_currentRow); - RowBinding rowBinding = _bindings[_nextAccessorForRetrieval].RowBinding(); + RowBinding rowBinding = _bindings[_nextAccessorForRetrieval]!.RowBinding()!; IntPtr accessorHandle = rowBinding.DangerousGetAccessorHandle(); bool mustRelease = false; @@ -1811,7 +1816,7 @@ namespace System.Data.OleDb OleDbHResult hr; UnsafeNativeMethods.IRowset irowset = IRowset(); - hr = irowset.ReleaseRows(_rowFetchedCount, _rowHandleNativeBuffer, ADP.PtrZero, ADP.PtrZero, ADP.PtrZero); + hr = irowset.ReleaseRows(_rowFetchedCount, _rowHandleNativeBuffer!, ADP.PtrZero, ADP.PtrZero, ADP.PtrZero); if (hr < 0) { @@ -1824,7 +1829,7 @@ namespace System.Data.OleDb _isRead = false; } - private object GetPropertyValue(int propertyId) + private object? GetPropertyValue(int propertyId) { if (null != _irowset) { @@ -1837,7 +1842,7 @@ namespace System.Data.OleDb return OleDbPropertyStatus.NotSupported; } - private object GetPropertyOnRowset(Guid propertySet, int propertyID) + private object? GetPropertyOnRowset(Guid propertySet, int propertyID) { OleDbHResult hr; ItagDBPROP[] dbprops; @@ -1868,14 +1873,14 @@ namespace System.Data.OleDb Debug.Assert(null != _irow, "GetRowValue: null IRow"); Debug.Assert(null != _metadata, "GetRowValue: null MetaData"); - Bindings bindings = _bindings[_nextAccessorForRetrieval]; + Bindings bindings = _bindings![_nextAccessorForRetrieval]!; ColumnBinding[] columnBindings = bindings.ColumnBindings(); - RowBinding rowBinding = bindings.RowBinding(); + RowBinding rowBinding = bindings.RowBinding()!; Debug.Assert(_nextValueForRetrieval <= columnBindings[0].Index, "backwards retrieval"); bool mustReleaseBinding = false; bool[] mustRelease = new bool[columnBindings.Length]; - StringMemHandle[] sptr = new StringMemHandle[columnBindings.Length]; + StringMemHandle?[] sptr = new StringMemHandle[columnBindings.Length]; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1892,9 +1897,9 @@ namespace System.Data.OleDb columnBindings[i]._sptr = sptr[i]; } - sptr[i].DangerousAddRef(ref mustRelease[i]); + sptr[i]!.DangerousAddRef(ref mustRelease[i]); - IntPtr ulPropid = ((null != sptr[i]) ? sptr[i].DangerousGetHandle() : info.propid); + IntPtr ulPropid = ((null != sptr[i]) ? sptr[i]!.DangerousGetHandle() : info.propid); bindings.GuidKindName(info.guid, info.kind, ulPropid); } @@ -1917,7 +1922,7 @@ namespace System.Data.OleDb { if (mustRelease[i]) { - sptr[i].DangerousRelease(); + sptr[i]!.DangerousRelease(); } } } @@ -1927,7 +1932,7 @@ namespace System.Data.OleDb private int IndexOf(Hashtable hash, string name) { // via case sensitive search, first match with lowest ordinal matches - object index = hash[name]; + object? index = hash[name]; if (null != index) { return (int)index; // match via case-insensitive or by chance lowercase @@ -1963,7 +1968,7 @@ namespace System.Data.OleDb } string schemaName, catalogName; // enforce single table - string baseSchemaName = null, baseCatalogName = null, baseTableName = null; + string? baseSchemaName = null, baseCatalogName = null, baseTableName = null; for (int i = 0; i < _metadata.Length; ++i) { MetaData info = _metadata[i]; @@ -2005,7 +2010,7 @@ namespace System.Data.OleDb { if (ODB.DBPROPVAL_IC_SENSITIVE == _connection.QuotedIdentifierCase()) { - string p = null, s = null; + string? p = null, s = null; _connection.GetLiteralQuotes(ADP.GetSchemaTable, out s, out p); if (null == s) { @@ -2023,7 +2028,7 @@ namespace System.Data.OleDb for (int i = _metadata.Length - 1; 0 <= i; --i) { - string basecolumname = _metadata[i].baseColumnName; + string? basecolumname = _metadata[i].baseColumnName; if (!ADP.IsEmpty(basecolumname)) { baseColumnNames[basecolumname] = i; @@ -2031,7 +2036,7 @@ namespace System.Data.OleDb } for (int i = 0; i < _metadata.Length; ++i) { - string basecolumname = _metadata[i].baseColumnName; + string? basecolumname = _metadata[i].baseColumnName; if (!ADP.IsEmpty(basecolumname)) { basecolumname = basecolumname.ToLowerInvariant(); @@ -2043,9 +2048,9 @@ namespace System.Data.OleDb } // look for primary keys in the table - if (_connection.SupportSchemaRowset(OleDbSchemaGuid.Primary_Keys)) + if (_connection!.SupportSchemaRowset(OleDbSchemaGuid.Primary_Keys)) { - object[] restrictions = new object[] { baseCatalogName, baseSchemaName, baseTableName }; + object?[] restrictions = new object?[] { baseCatalogName, baseSchemaName, baseTableName }; keyCount = AppendSchemaPrimaryKey(baseColumnNames, restrictions); } if (0 != keyCount) @@ -2056,19 +2061,19 @@ namespace System.Data.OleDb // look for a single unique contraint that can be upgraded if (_connection.SupportSchemaRowset(OleDbSchemaGuid.Indexes)) { - object[] restrictions = new object[] { baseCatalogName, baseSchemaName, null, null, baseTableName }; + object?[] restrictions = new object?[] { baseCatalogName, baseSchemaName, null, null, baseTableName }; AppendSchemaUniqueIndexAsKey(baseColumnNames, restrictions); } } - private int AppendSchemaPrimaryKey(Hashtable baseColumnNames, object[] restrictions) + private int AppendSchemaPrimaryKey(Hashtable baseColumnNames, object?[] restrictions) { int keyCount = 0; bool partialPrimaryKey = false; - DataTable table = null; + DataTable? table = null; try { - table = _connection.GetSchemaRowset(OleDbSchemaGuid.Primary_Keys, restrictions); + table = _connection!.GetSchemaRowset(OleDbSchemaGuid.Primary_Keys, restrictions); } catch (Exception e) { @@ -2095,7 +2100,7 @@ namespace System.Data.OleDb int metaindex = IndexOf(baseColumnNames, name); if (0 <= metaindex) { - MetaData info = _metadata[metaindex]; + MetaData info = _metadata![metaindex]; info.isKeyColumn = true; info.flags &= ~ODB.DBCOLUMNFLAGS_ISNULLABLE; keyCount++; @@ -2116,7 +2121,7 @@ namespace System.Data.OleDb } if (partialPrimaryKey) { // partial primary key detected - for (int i = 0; i < _metadata.Length; ++i) + for (int i = 0; i < _metadata!.Length; ++i) { _metadata[i].isKeyColumn = false; } @@ -2125,13 +2130,13 @@ namespace System.Data.OleDb return keyCount; } - private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object[] restrictions) + private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] restrictions) { bool partialPrimaryKey = false; - DataTable table = null; + DataTable? table = null; try { - table = _connection.GetSchemaRowset(OleDbSchemaGuid.Indexes, restrictions); + table = _connection!.GetSchemaRowset(OleDbSchemaGuid.Indexes, restrictions); } catch (Exception e) { @@ -2159,11 +2164,11 @@ namespace System.Data.OleDb DataColumn pkeyColumn = dataColumns[pkeyIndex]; DataColumn uniqCOlumn = dataColumns[uniqIndex]; DataColumn nameColumn = dataColumns[nameIndex]; - DataColumn nulls = ((-1 != nullIndex) ? dataColumns[nullIndex] : null); + DataColumn? nulls = ((-1 != nullIndex) ? dataColumns[nullIndex] : null); - bool[] keys = new bool[_metadata.Length]; - bool[] uniq = new bool[_metadata.Length]; - string uniqueIndexName = null; + bool[] keys = new bool[_metadata!.Length]; + bool[]? uniq = new bool[_metadata.Length]; + string? uniqueIndexName = null; // match pkey name BaseColumnName foreach (DataRow dataRow in table.Rows) @@ -2257,21 +2262,22 @@ namespace System.Data.OleDb } } - private MetaData FindMetaData(string name) + private MetaData? FindMetaData(string name) { - int index = _fieldNameLookup.IndexOfName(name); - return ((-1 != index) ? _metadata[index] : null); + int index = _fieldNameLookup!.IndexOfName(name); + return ((-1 != index) ? _metadata![index] : null); } - internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset rowset) + internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) { List metainfo = new List(); - object hiddenColumns = null; + object? hiddenColumns = null; using (OleDbDataReader dataReader = new OleDbDataReader(_connection, _command, int.MinValue, 0)) { dataReader.InitializeIRowset(rowset, ChapterHandle.DB_NULL_HCHAPTER, IntPtr.Zero); - dataReader.BuildSchemaTableInfo(rowset, true, false); + // TODO-NULLABLE: BuildSchemaTableInfo asserts that rowset isn't null, but doesn't do anything with it + dataReader.BuildSchemaTableInfo(rowset!, true, false); hiddenColumns = GetPropertyValue(ODB.DBPROP_HIDDENCOLUMNS); if (0 == dataReader.FieldCount) @@ -2286,24 +2292,24 @@ namespace System.Data.OleDb // This column, together with the DBCOLUMN_GUID and DBCOLUMN_PROPID // columns, forms the ID of the column. One or more (but not all) of these columns // will be NULL, depending on which elements of the DBID structure the provider uses. - MetaData columnidname = dataReader.FindMetaData(ODB.DBCOLUMN_IDNAME); - MetaData columnguid = dataReader.FindMetaData(ODB.DBCOLUMN_GUID); - MetaData columnpropid = dataReader.FindMetaData(ODB.DBCOLUMN_PROPID); - - MetaData columnname = dataReader.FindMetaData(ODB.DBCOLUMN_NAME); - MetaData columnordinal = dataReader.FindMetaData(ODB.DBCOLUMN_NUMBER); - MetaData dbtype = dataReader.FindMetaData(ODB.DBCOLUMN_TYPE); - MetaData columnsize = dataReader.FindMetaData(ODB.DBCOLUMN_COLUMNSIZE); - MetaData numericprecision = dataReader.FindMetaData(ODB.DBCOLUMN_PRECISION); - MetaData numericscale = dataReader.FindMetaData(ODB.DBCOLUMN_SCALE); - MetaData columnflags = dataReader.FindMetaData(ODB.DBCOLUMN_FLAGS); - MetaData baseschemaname = dataReader.FindMetaData(ODB.DBCOLUMN_BASESCHEMANAME); - MetaData basecatalogname = dataReader.FindMetaData(ODB.DBCOLUMN_BASECATALOGNAME); - MetaData basetablename = dataReader.FindMetaData(ODB.DBCOLUMN_BASETABLENAME); - MetaData basecolumnname = dataReader.FindMetaData(ODB.DBCOLUMN_BASECOLUMNNAME); - MetaData isautoincrement = dataReader.FindMetaData(ODB.DBCOLUMN_ISAUTOINCREMENT); - MetaData isunique = dataReader.FindMetaData(ODB.DBCOLUMN_ISUNIQUE); - MetaData iskeycolumn = dataReader.FindMetaData(ODB.DBCOLUMN_KEYCOLUMN); + MetaData columnidname = dataReader.FindMetaData(ODB.DBCOLUMN_IDNAME)!; + MetaData columnguid = dataReader.FindMetaData(ODB.DBCOLUMN_GUID)!; + MetaData columnpropid = dataReader.FindMetaData(ODB.DBCOLUMN_PROPID)!; + + MetaData columnname = dataReader.FindMetaData(ODB.DBCOLUMN_NAME)!; + MetaData columnordinal = dataReader.FindMetaData(ODB.DBCOLUMN_NUMBER)!; + MetaData dbtype = dataReader.FindMetaData(ODB.DBCOLUMN_TYPE)!; + MetaData columnsize = dataReader.FindMetaData(ODB.DBCOLUMN_COLUMNSIZE)!; + MetaData numericprecision = dataReader.FindMetaData(ODB.DBCOLUMN_PRECISION)!; + MetaData numericscale = dataReader.FindMetaData(ODB.DBCOLUMN_SCALE)!; + MetaData columnflags = dataReader.FindMetaData(ODB.DBCOLUMN_FLAGS)!; + MetaData baseschemaname = dataReader.FindMetaData(ODB.DBCOLUMN_BASESCHEMANAME)!; + MetaData basecatalogname = dataReader.FindMetaData(ODB.DBCOLUMN_BASECATALOGNAME)!; + MetaData basetablename = dataReader.FindMetaData(ODB.DBCOLUMN_BASETABLENAME)!; + MetaData basecolumnname = dataReader.FindMetaData(ODB.DBCOLUMN_BASECOLUMNNAME)!; + MetaData isautoincrement = dataReader.FindMetaData(ODB.DBCOLUMN_ISAUTOINCREMENT)!; + MetaData isunique = dataReader.FindMetaData(ODB.DBCOLUMN_ISUNIQUE)!; + MetaData iskeycolumn = dataReader.FindMetaData(ODB.DBCOLUMN_KEYCOLUMN)!; // @devnote: because we want to use the DBACCESSOR_OPTIMIZED bit, // we are required to create the accessor before fetching any rows @@ -2517,7 +2523,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("Filtered Column: DBCOLUMN_FLAGS=" + info.flags.ToString("X8", (System.IFormatProvider)null) + " DBCOLUMN_NAME=" + info.columnName); + Debug.WriteLine("Filtered Column: DBCOLUMN_FLAGS=" + info.flags.ToString("X8", null) + " DBCOLUMN_NAME=" + info.columnName); } #endif info.isHidden = true; @@ -2542,7 +2548,7 @@ namespace System.Data.OleDb { dataReader.BuildSchemaTableInfo(handle, false, false); // only tries IColumnsInfo } - MetaData[] metadata = dataReader.MetaData; + MetaData[]? metadata = dataReader.MetaData; if ((null != metadata) && (0 < metadata.Length)) { dataReader.BuildSchemaTable(metadata); @@ -2581,17 +2587,17 @@ namespace System.Data.OleDb internal sealed class MetaData : IComparable { - internal Bindings bindings; - internal ColumnBinding columnBinding; + internal Bindings? bindings; + internal ColumnBinding columnBinding = null!; // Late-initialized - internal string columnName; + internal string columnName = null!; // Late-initialized internal Guid guid; internal int kind; internal IntPtr propid; - internal string idname; + internal string? idname; - internal NativeDBType type; + internal NativeDBType type = null!; // Late-initialized internal IntPtr ordinal; internal int size; @@ -2606,22 +2612,22 @@ namespace System.Data.OleDb internal bool isKeyColumn; internal bool isHidden; - internal string baseSchemaName; - internal string baseCatalogName; - internal string baseTableName; - internal string baseColumnName; + internal string? baseSchemaName; + internal string? baseCatalogName; + internal string? baseTableName; + internal string? baseColumnName; - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { - if (isHidden == (obj as MetaData).isHidden) + if (isHidden == (obj as MetaData)!.isHidden) { if (ODB.IsRunningOnX86) { - return ((int)ordinal - (int)(obj as MetaData).ordinal); + return ((int)ordinal - (int)(obj as MetaData)!.ordinal); } else { - long v = ((long)ordinal - (long)(obj as MetaData).ordinal); + long v = ((long)ordinal - (long)(obj as MetaData)!.ordinal); return ((0 < v) ? 1 : ((v < 0) ? -1 : 0)); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs b/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs index 8b78d56..03ddf25 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs @@ -28,17 +28,17 @@ namespace System.Data.OleDb internal static OleDbDataReader GetEnumeratorFromType(Type type) { - object value = Activator.CreateInstance(type, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); + object? value = Activator.CreateInstance(type, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); return GetEnumeratorReader(value); } - private static OleDbDataReader GetEnumeratorReader(object value) + private static OleDbDataReader GetEnumeratorReader(object? value) { - NativeMethods.ISourcesRowset srcrowset = null; + NativeMethods.ISourcesRowset? srcrowset = null; try { - srcrowset = (NativeMethods.ISourcesRowset)value; + srcrowset = (NativeMethods.ISourcesRowset?)value; } catch (InvalidCastException) { @@ -54,7 +54,7 @@ namespace System.Data.OleDb IntPtr propSets = ADP.PtrZero; OleDbHResult hr = srcrowset.GetSourcesRowset(ADP.PtrZero, ODB.IID_IRowset, propCount, propSets, out value); - Exception f = OleDbConnection.ProcessResults(hr, null, null); + Exception? f = OleDbConnection.ProcessResults(hr, null, null); if (null != f) { throw f; @@ -72,7 +72,7 @@ namespace System.Data.OleDb //readonly Guid CLSID_MSDAENUM = new Guid(0xc8b522d0,0x5cf3,0x11ce,0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d); //Type msdaenum = Type.GetTypeFromCLSID(CLSID_MSDAENUM, true); const string PROGID_MSDAENUM = "MSDAENUM"; - Type msdaenum = Type.GetTypeFromProgID(PROGID_MSDAENUM, true); + Type msdaenum = Type.GetTypeFromProgID(PROGID_MSDAENUM, true)!; return GetEnumeratorFromType(msdaenum); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbError.cs b/src/libraries/System.Data.OleDb/src/OleDbError.cs index d578a50..333cdb3 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbError.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbError.cs @@ -8,9 +8,9 @@ namespace System.Data.OleDb { public sealed class OleDbError { - private readonly string message; - private readonly string source; - private readonly string sqlState; + private readonly string? message; + private readonly string? source; + private readonly string? sqlState; private readonly int nativeError; internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) @@ -56,7 +56,7 @@ namespace System.Data.OleDb { this.source = ODB.FailedGetSource(hr); } - Marshal.ReleaseComObject(errorInfo); + Marshal.ReleaseComObject(errorInfo!); } } @@ -74,7 +74,7 @@ namespace System.Data.OleDb { get { - string message = this.message; + string? message = this.message; return ((null != message) ? message : string.Empty); } } @@ -91,7 +91,7 @@ namespace System.Data.OleDb { get { - string source = this.source; + string? source = this.source; return ((null != source) ? source : string.Empty); } } @@ -100,7 +100,7 @@ namespace System.Data.OleDb { get { - string sqlState = this.sqlState; + string? sqlState = this.sqlState; return ((null != sqlState) ? sqlState : string.Empty); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs b/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs index 72e47b7..d6a1644 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbErrorCollection.cs @@ -12,10 +12,10 @@ namespace System.Data.OleDb { private readonly ArrayList items; - internal OleDbErrorCollection(UnsafeNativeMethods.IErrorInfo errorInfo) + internal OleDbErrorCollection(UnsafeNativeMethods.IErrorInfo? errorInfo) { ArrayList items = new ArrayList(); - UnsafeNativeMethods.IErrorRecords errorRecords = (errorInfo as UnsafeNativeMethods.IErrorRecords); + UnsafeNativeMethods.IErrorRecords? errorRecords = (errorInfo as UnsafeNativeMethods.IErrorRecords); if (null != errorRecords) { int recordCount = errorRecords.GetRecordCount(); @@ -52,7 +52,7 @@ namespace System.Data.OleDb { get { - return (this.items[index] as OleDbError); + return (this.items[index] as OleDbError)!; } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbException.cs b/src/libraries/System.Data.OleDb/src/OleDbException.cs index 5630992..410e9cb 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbException.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbException.cs @@ -15,19 +15,19 @@ namespace System.Data.OleDb { private readonly OleDbErrorCollection oledbErrors; - internal OleDbException(string message, OleDbHResult errorCode, Exception inner) : base(message, inner) + internal OleDbException(string? message, OleDbHResult errorCode, Exception? inner) : base(message, inner) { HResult = (int)errorCode; this.oledbErrors = new OleDbErrorCollection(null); } - internal OleDbException(OleDbException previous, Exception inner) : base(previous.Message, inner) + internal OleDbException(OleDbException previous, Exception? inner) : base(previous.Message, inner) { HResult = previous.ErrorCode; this.oledbErrors = previous.oledbErrors; } - private OleDbException(string message, Exception inner, string source, OleDbHResult errorCode, OleDbErrorCollection errors) : base(message, inner) + private OleDbException(string? message, Exception? inner, string? source, OleDbHResult errorCode, OleDbErrorCollection errors) : base(message, inner) { Debug.Assert(null != errors, "OleDbException without OleDbErrorCollection"); Source = source; @@ -64,11 +64,11 @@ namespace System.Data.OleDb } } - internal static OleDbException CreateException(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode, Exception inner) + internal static OleDbException CreateException(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode, Exception? inner) { OleDbErrorCollection errors = new OleDbErrorCollection(errorInfo); - string message = null; - string source = null; + string? message = null; + string? source = null; OleDbHResult hr = 0; if (null != errorInfo) diff --git a/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs b/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs index c9f7444..e082c8f 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbInfoMessageEvent.cs @@ -39,7 +39,7 @@ namespace System.Data.OleDb } } - public string Source + public string? Source { get { diff --git a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs index d5d3287..e978419 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs @@ -33,7 +33,7 @@ namespace System.Data.OleDb internal OleDbMetaDataFactory(Stream XMLStream, string serverVersion, string serverVersionNormalized, - SchemaSupport[] schemaSupport) : + SchemaSupport[]? schemaSupport) : base(XMLStream, serverVersion, serverVersionNormalized) { // set up the colletion mane schema rowset guid mapping @@ -50,7 +50,7 @@ namespace System.Data.OleDb new SchemaRowsetName(OleDbMetaDataCollectionNames.Views, OleDbSchemaGuid.Views)}; // verify the existance of the table in the data set - DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; + DataTable? metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; if (metaDataCollectionsTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.MetaDataCollections); @@ -60,7 +60,7 @@ namespace System.Data.OleDb metaDataCollectionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.MetaDataCollections, null); // verify the existance of the table in the data set - DataTable restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; + DataTable? restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; if (restrictionsTable != null) { // copy the table filtering out any rows that don't apply to the current version of the provider @@ -72,17 +72,17 @@ namespace System.Data.OleDb // 2) it is in the collection to schema rowset mapping above // 3) the provider does not support the necessary schema rowset - DataColumn populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]; + DataColumn? populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism]; if ((null == populationMechanism) || (typeof(string) != populationMechanism.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, _populationMechanism); } - DataColumn collectionName = metaDataCollectionsTable.Columns[_collectionName]; + DataColumn? collectionName = metaDataCollectionsTable.Columns[_collectionName]; if ((null == collectionName) || (typeof(string) != collectionName.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, _collectionName); } - DataColumn restrictionCollectionName = null; + DataColumn? restrictionCollectionName = null; if (restrictionsTable != null) { restrictionCollectionName = restrictionsTable.Columns[_collectionName]; @@ -94,12 +94,12 @@ namespace System.Data.OleDb foreach (DataRow collection in metaDataCollectionsTable.Rows) { - string populationMechanismValue = collection[populationMechanism] as string; + string? populationMechanismValue = collection[populationMechanism] as string; if (ADP.IsEmpty(populationMechanismValue)) { throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections, _populationMechanism); } - string collectionNameValue = collection[collectionName] as string; + string? collectionNameValue = collection[collectionName] as string; if (ADP.IsEmpty(collectionNameValue)) { throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections, _collectionName); @@ -144,7 +144,7 @@ namespace System.Data.OleDb { foreach (DataRow restriction in restrictionsTable.Rows) { - string restrictionCollectionNameValue = restriction[restrictionCollectionName] as string; + string? restrictionCollectionNameValue = restriction[restrictionCollectionName!] as string; if (ADP.IsEmpty(restrictionCollectionNameValue)) { throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.Restrictions, _collectionName); @@ -164,12 +164,12 @@ namespace System.Data.OleDb // replace the original table with the updated one metaDataCollectionsTable.AcceptChanges(); - CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]); + CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!); CollectionDataSet.Tables.Add(metaDataCollectionsTable); if (restrictionsTable != null) { - CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]); + CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]!); CollectionDataSet.Tables.Add(restrictionsTable); } @@ -189,7 +189,7 @@ namespace System.Data.OleDb private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleDbConnectionInternal internalConnection) { // verify that the data source information table is in the data set - DataTable dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; + DataTable? dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation]; if (dataSourceInformationTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataSourceInformation); @@ -206,8 +206,8 @@ namespace System.Data.OleDb DataRow dataSourceInformation = dataSourceInformationTable.Rows[0]; // update the identifier separator - string catalogSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_CATALOG_SEPARATOR); - string schemaSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_SCHEMA_SEPARATOR); + string? catalogSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_CATALOG_SEPARATOR); + string? schemaSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_SCHEMA_SEPARATOR); if (catalogSeparatorPattern != null) { @@ -233,7 +233,7 @@ namespace System.Data.OleDb } // update the DataSourceProductName - object property; + object? property; property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSNAME); if (property != null) { @@ -283,7 +283,7 @@ namespace System.Data.OleDb dataSourceInformation[DbMetaDataColumnNames.OrderByColumnsInSelect] = (bool)property; } - DataTable infoLiterals = internalConnection.BuildInfoLiterals(); + DataTable? infoLiterals = internalConnection.BuildInfoLiterals(); if (infoLiterals != null) { DataRow[] tableNameRow = infoLiterals.Select("Literal = " + ODB.DBLITERAL_TABLE_NAME.ToString(CultureInfo.InvariantCulture)); @@ -353,7 +353,7 @@ namespace System.Data.OleDb private DataTable GetDataTypesTable(OleDbConnection connection) { // verify the existance of the table in the data set - DataTable dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; + DataTable? dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes]; if (dataTypesTable == null) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes); @@ -362,9 +362,9 @@ namespace System.Data.OleDb // copy the table filtering out any rows that don't apply to tho current version of the prrovider dataTypesTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataTypes, null); - DataTable providerTypesTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Provider_Types, null); + DataTable providerTypesTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Provider_Types, null)!; - DataColumn[] targetColumns = new DataColumn[] { + DataColumn?[] targetColumns = new DataColumn?[] { dataTypesTable.Columns[DbMetaDataColumnNames.TypeName], dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize], dataTypesTable.Columns[DbMetaDataColumnNames.CreateParameters], @@ -381,7 +381,7 @@ namespace System.Data.OleDb dataTypesTable.Columns[DbMetaDataColumnNames.LiteralSuffix], dataTypesTable.Columns[OleDbMetaDataColumnNames.NativeDataType]}; - DataColumn[] sourceColumns = new DataColumn[] { + DataColumn?[] sourceColumns = new DataColumn?[] { providerTypesTable.Columns["TYPE_NAME"], providerTypesTable.Columns["COLUMN_SIZE"], providerTypesTable.Columns["CREATE_PARAMS"], @@ -400,31 +400,31 @@ namespace System.Data.OleDb Debug.Assert(sourceColumns.Length == targetColumns.Length); - DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable]; - DataColumn isSearchableWithLike = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchableWithLike]; - DataColumn providerDbType = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType]; - DataColumn clrType = dataTypesTable.Columns[DbMetaDataColumnNames.DataType]; - DataColumn isLong = dataTypesTable.Columns[DbMetaDataColumnNames.IsLong]; - DataColumn isFixed = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength]; - DataColumn sourceOleDbType = providerTypesTable.Columns["DATA_TYPE"]; + DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable]!; + DataColumn isSearchableWithLike = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchableWithLike]!; + DataColumn providerDbType = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType]!; + DataColumn clrType = dataTypesTable.Columns[DbMetaDataColumnNames.DataType]!; + DataColumn isLong = dataTypesTable.Columns[DbMetaDataColumnNames.IsLong]!; + DataColumn isFixed = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength]!; + DataColumn sourceOleDbType = providerTypesTable.Columns["DATA_TYPE"]!; - DataColumn searchable = providerTypesTable.Columns["SEARCHABLE"]; + DataColumn searchable = providerTypesTable.Columns["SEARCHABLE"]!; foreach (DataRow sourceRow in providerTypesTable.Rows) { DataRow newRow = dataTypesTable.NewRow(); for (int i = 0; i < sourceColumns.Length; i++) { - if ((sourceColumns[i] != null) && (targetColumns[i] != null)) + if ((sourceColumns[i] is DataColumn sourceColumn) && (targetColumns[i] is DataColumn targetColumn)) { - newRow[targetColumns[i]] = sourceRow[sourceColumns[i]]; + newRow[targetColumn] = sourceRow[sourceColumn]; } } short nativeDataType = (short)Convert.ChangeType(sourceRow[sourceOleDbType], typeof(short), CultureInfo.InvariantCulture); NativeDBType nativeType = NativeDBType.FromDBType(nativeDataType, (bool)newRow[isLong], (bool)newRow[isFixed]); - newRow[clrType] = nativeType.dataType.FullName; + newRow[clrType] = nativeType.dataType!.FullName; newRow[providerDbType] = nativeType.enumOleDbType; // searchable has to be special cased becasue it is not an eaxct mapping @@ -472,7 +472,7 @@ namespace System.Data.OleDb private DataTable GetReservedWordsTable(OleDbConnectionInternal internalConnection) { // verify the existance of the table in the data set - DataTable reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; + DataTable? reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords]; if (null == reservedWordsTable) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); @@ -481,7 +481,7 @@ namespace System.Data.OleDb // copy the table filtering out any rows that don't apply to tho current version of the prrovider reservedWordsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.ReservedWords, null); - DataColumn reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; + DataColumn? reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord]; if (null == reservedWordColumn) { throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords); @@ -495,11 +495,11 @@ namespace System.Data.OleDb return reservedWordsTable; } - protected override DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection) + protected override DataTable PrepareCollection(string collectionName, string?[]? restrictions, DbConnection connection) { OleDbConnection oleDbConnection = (OleDbConnection)connection; OleDbConnectionInternal oleDbInternalConnection = (OleDbConnectionInternal)(oleDbConnection.InnerConnection); - DataTable resultTable = null; + DataTable? resultTable = null; if (collectionName == DbMetaDataCollectionNames.DataSourceInformation) { if (ADP.IsEmptyArray(restrictions) == false) @@ -532,12 +532,12 @@ namespace System.Data.OleDb { // need to special case the oledb schema rowset restrictions on columns that are not // string tpyes - object[] mungedRestrictions = restrictions; + object?[]? mungedRestrictions = restrictions; ; if (restrictions != null) { //verify that there are not too many restrictions - DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; + DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; int numberOfSupportedRestictions = -1; // prepare colletion is called with the exact collection name so // we can do an exact string comparision here @@ -595,7 +595,7 @@ namespace System.Data.OleDb } else { - throw ADP.InvalidRestrictionValue(collectionName, "TYPE", restrictions[indexRestrictionTypeSlot]); + throw ADP.InvalidRestrictionValue(collectionName, "TYPE", restrictions[indexRestrictionTypeSlot]!); } mungedRestrictions[indexRestrictionTypeSlot] = indexTypeValue; @@ -634,7 +634,7 @@ namespace System.Data.OleDb } else { - throw ADP.InvalidRestrictionValue(collectionName, "PROCEDURE_TYPE", restrictions[procedureRestrictionTypeSlot]); + throw ADP.InvalidRestrictionValue(collectionName, "PROCEDURE_TYPE", restrictions[procedureRestrictionTypeSlot]!); } mungedRestrictions[procedureRestrictionTypeSlot] = procedureTypeValue; @@ -658,7 +658,7 @@ namespace System.Data.OleDb private void SetIdentifierCase(string columnName, int propertyID, DataRow row, OleDbConnection connection) { - object property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, propertyID); + object? property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, propertyID); IdentifierCase identifierCase = IdentifierCase.Unknown; if (property != null) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs index 169c660..61053ad 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data.OleDb @@ -11,21 +12,21 @@ namespace System.Data.OleDb [TypeConverter(typeof(OleDbParameter.OleDbParameterConverter))] public sealed partial class OleDbParameter : DbParameter, ICloneable, IDbDataParameter { - private NativeDBType _metaType; + private NativeDBType? _metaType; private int _changeID; - private string _parameterName; + private string? _parameterName; private byte _precision; private byte _scale; private bool _hasScale; - private NativeDBType _coerceMetaType; + private NativeDBType? _coerceMetaType; public OleDbParameter() : base() { // V1.0 nothing } - public OleDbParameter(string name, object value) : this() + public OleDbParameter(string? name, object? value) : this() { Debug.Assert(!(value is OleDbType), "use OleDbParameter(string, OleDbType)"); Debug.Assert(!(value is SqlDbType), "use OleDbParameter(string, OleDbType)"); @@ -34,20 +35,20 @@ namespace System.Data.OleDb Value = value; } - public OleDbParameter(string name, OleDbType dataType) : this() + public OleDbParameter(string? name, OleDbType dataType) : this() { ParameterName = name; OleDbType = dataType; } - public OleDbParameter(string name, OleDbType dataType, int size) : this() + public OleDbParameter(string? name, OleDbType dataType, int size) : this() { ParameterName = name; OleDbType = dataType; Size = size; } - public OleDbParameter(string name, OleDbType dataType, int size, string srcColumn) : this() + public OleDbParameter(string? name, OleDbType dataType, int size, string? srcColumn) : this() { ParameterName = name; OleDbType = dataType; @@ -56,12 +57,12 @@ namespace System.Data.OleDb } [EditorBrowsable(EditorBrowsableState.Advanced)] - public OleDbParameter(string parameterName, + public OleDbParameter(string? parameterName, OleDbType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, - string srcColumn, DataRowVersion srcVersion, - object value) : this() + string? srcColumn, DataRowVersion srcVersion, + object? value) : this() { // V1.0 everything ParameterName = parameterName; OleDbType = dbType; @@ -76,12 +77,12 @@ namespace System.Data.OleDb } [EditorBrowsable(EditorBrowsableState.Advanced)] - public OleDbParameter(string parameterName, + public OleDbParameter(string? parameterName, OleDbType dbType, int size, ParameterDirection direction, byte precision, byte scale, - string sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, - object value) : this() + string? sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, + object? value) : this() { // V2.0 everything - round trip all browsable properties + precision/scale ParameterName = parameterName; OleDbType = dbType; @@ -111,7 +112,7 @@ namespace System.Data.OleDb } set { - NativeDBType dbtype = _metaType; + NativeDBType? dbtype = _metaType; if ((null == dbtype) || (dbtype.enumDbType != value)) { PropertyTypeChanging(); @@ -137,7 +138,7 @@ namespace System.Data.OleDb } set { - NativeDBType dbtype = _metaType; + NativeDBType? dbtype = _metaType; if ((null == dbtype) || (dbtype.enumOleDbType != value)) { PropertyTypeChanging(); @@ -160,11 +161,12 @@ namespace System.Data.OleDb } } + [AllowNull] public override string ParameterName { // V1.2.3300, XXXParameter V1.0.3300 get { - string parameterName = _parameterName; + string? parameterName = _parameterName; return ((null != parameterName) ? parameterName : string.Empty); } set @@ -289,7 +291,7 @@ namespace System.Data.OleDb internal bool BindParameter(int index, Bindings bindings) { int changeID = _changeID; - object value = Value; + object? value = Value; NativeDBType dbtype = GetBindType(value); if (OleDbType.Empty == dbtype.enumOleDbType) @@ -357,7 +359,7 @@ namespace System.Data.OleDb { // variable length data (varbinary, varchar, nvarchar) if (!ShouldSerializeSize() && ADP.IsDirection(this, ParameterDirection.Output)) { - throw ADP.UninitializedParameterSize(index, _coerceMetaType.dataType); + throw ADP.UninitializedParameterSize(index, _coerceMetaType.dataType!); } bool computedSize; @@ -460,7 +462,7 @@ namespace System.Data.OleDb return IsParameterComputed(); } - private static object CoerceValue(object value, NativeDBType destinationType) + private static object? CoerceValue(object? value, NativeDBType destinationType) { Debug.Assert(null != destinationType, "null destinationType"); if ((null != value) && (DBNull.Value != value) && (typeof(object) != destinationType.dataType)) @@ -475,11 +477,11 @@ namespace System.Data.OleDb } else if ((NativeDBType.CY == destinationType.dbType) && (typeof(string) == currentType)) { - value = decimal.Parse((string)value, NumberStyles.Currency, (IFormatProvider)null); + value = decimal.Parse((string)value, NumberStyles.Currency, null); } else { - value = Convert.ChangeType(value, destinationType.dataType, (IFormatProvider)null); + value = Convert.ChangeType(value, destinationType.dataType!, null); } } catch (Exception e) @@ -490,16 +492,16 @@ namespace System.Data.OleDb throw; } - throw ADP.ParameterConversionFailed(value, destinationType.dataType, e); + throw ADP.ParameterConversionFailed(value, destinationType.dataType!, e); } } } return value; } - private NativeDBType GetBindType(object value) + private NativeDBType GetBindType(object? value) { - NativeDBType dbtype = _metaType; + NativeDBType? dbtype = _metaType; if (null == dbtype) { if (ADP.IsNull(value)) @@ -514,12 +516,12 @@ namespace System.Data.OleDb return dbtype; } - internal object GetCoercedValue() + internal object? GetCoercedValue() { - object value = CoercedValue; // will also be set during binding, will rebind everytime if _metaType not set + object? value = CoercedValue; // will also be set during binding, will rebind everytime if _metaType not set if (null == value) { - value = CoerceValue(Value, _coerceMetaType); + value = CoerceValue(Value, _coerceMetaType!); CoercedValue = value; } return value; @@ -527,7 +529,7 @@ namespace System.Data.OleDb internal bool IsParameterComputed() { - NativeDBType metaType = _metaType; + NativeDBType? metaType = _metaType; return ((null == metaType) || (!ShouldSerializeSize() && metaType.IsVariableLength) || ((NativeDBType.DECIMAL == metaType.dbType) || (NativeDBType.NUMERIC == metaType.dbType) @@ -560,7 +562,7 @@ namespace System.Data.OleDb RefreshProperties(RefreshProperties.All), TypeConverter(typeof(StringConverter)), ] - public override object Value + public override object? Value { // V1.2.3300, XXXParameter V1.0.3300 get { @@ -573,17 +575,17 @@ namespace System.Data.OleDb } } - private byte ValuePrecision(object value) + private byte ValuePrecision(object? value) { return ValuePrecisionCore(value); } - private byte ValueScale(object value) + private byte ValueScale(object? value) { return ValueScaleCore(value); } - private int ValueSize(object value) + private int ValueSize(object? value) { return ValueSizeCore(value); } @@ -641,9 +643,9 @@ namespace System.Data.OleDb { throw ADP.ArgumentNull("destinationType"); } - if ((typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) && (value is OleDbParameter)) + if ((typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) && (value is OleDbParameter parameter)) { - return ConvertToInstanceDescriptor(value as OleDbParameter); + return ConvertToInstanceDescriptor(parameter); } return base.ConvertTo(context, culture, value, destinationType); } @@ -680,7 +682,7 @@ namespace System.Data.OleDb } Type[] ctorParams; - object[] ctorValues; + object?[] ctorValues; switch (flags) { case 0: // ParameterName @@ -702,7 +704,7 @@ namespace System.Data.OleDb break; case 8: // Value ctorParams = new Type[] { typeof(string), typeof(object) }; - ctorValues = new object[] { p.ParameterName, p.Value }; + ctorValues = new object?[] { p.ParameterName, p.Value }; break; default: // everything else if (0 == (32 & flags)) @@ -711,7 +713,7 @@ namespace System.Data.OleDb typeof(string), typeof(OleDbType), typeof(int), typeof(ParameterDirection), typeof(bool), typeof(byte), typeof(byte), typeof(string), typeof(DataRowVersion), typeof(object) }; - ctorValues = new object[] { + ctorValues = new object?[] { p.ParameterName, p.OleDbType, p.Size, p.Direction, p.IsNullable, p.PrecisionInternal, p.ScaleInternal, p.SourceColumn, p.SourceVersion, p.Value }; @@ -723,7 +725,7 @@ namespace System.Data.OleDb typeof(byte), typeof(byte), typeof(string), typeof(DataRowVersion), typeof(bool), typeof(object) }; - ctorValues = new object[] { + ctorValues = new object?[] { p.ParameterName, p.OleDbType, p.Size, p.Direction, p.PrecisionInternal, p.ScaleInternal, p.SourceColumn, p.SourceVersion, p.SourceColumnNullMapping, @@ -731,7 +733,7 @@ namespace System.Data.OleDb } break; } - System.Reflection.ConstructorInfo ctor = typeof(OleDbParameter).GetConstructor(ctorParams); + System.Reflection.ConstructorInfo ctor = typeof(OleDbParameter).GetConstructor(ctorParams)!; return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameterCollection.cs b/src/libraries/System.Data.OleDb/src/OleDbParameterCollection.cs index 393e1cc..3f54065 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameterCollection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameterCollection.cs @@ -64,27 +64,27 @@ namespace System.Data.OleDb [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). https://go.microsoft.com/fwlink/?linkid=14202", false)] - public OleDbParameter Add(string parameterName, object value) + public OleDbParameter Add(string? parameterName, object? value) { return Add(new OleDbParameter(parameterName, value)); } - public OleDbParameter AddWithValue(string parameterName, object value) + public OleDbParameter AddWithValue(string? parameterName, object? value) { return Add(new OleDbParameter(parameterName, value)); } - public OleDbParameter Add(string parameterName, OleDbType oleDbType) + public OleDbParameter Add(string? parameterName, OleDbType oleDbType) { return Add(new OleDbParameter(parameterName, oleDbType)); } - public OleDbParameter Add(string parameterName, OleDbType oleDbType, int size) + public OleDbParameter Add(string? parameterName, OleDbType oleDbType, int size) { return Add(new OleDbParameter(parameterName, oleDbType, size)); } - public OleDbParameter Add(string parameterName, OleDbType oleDbType, int size, string sourceColumn) + public OleDbParameter Add(string? parameterName, OleDbType oleDbType, int size, string? sourceColumn) { return Add(new OleDbParameter(parameterName, oleDbType, size, sourceColumn)); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs b/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs index 3470271..9f0f898 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameterCollectionHelper.cs @@ -11,7 +11,7 @@ namespace System.Data.OleDb { public sealed partial class OleDbParameterCollection : DbParameterCollection { - private List _items; + private List? _items; public override int Count { @@ -25,7 +25,7 @@ namespace System.Data.OleDb { get { - List items = _items; + List? items = _items; if (null == items) { @@ -298,7 +298,7 @@ namespace System.Data.OleDb throw ADP.ParameterNull(nameof(value), this, s_itemType); } - object parent = ((OleDbParameter)value).CompareExchangeParent(this, null); + object? parent = ((OleDbParameter)value).CompareExchangeParent(this, null); if (null != parent) { if (this != parent) diff --git a/src/libraries/System.Data.OleDb/src/OleDbRowUpdatedEvent.cs b/src/libraries/System.Data.OleDb/src/OleDbRowUpdatedEvent.cs index 07e5a44..99c2db0 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbRowUpdatedEvent.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbRowUpdatedEvent.cs @@ -7,16 +7,16 @@ namespace System.Data.OleDb { public sealed class OleDbRowUpdatedEventArgs : RowUpdatedEventArgs { - public OleDbRowUpdatedEventArgs(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + public OleDbRowUpdatedEventArgs(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) : base(dataRow, command, statementType, tableMapping) { } - public new OleDbCommand Command + public new OleDbCommand? Command { get { - return (OleDbCommand)base.Command; + return (OleDbCommand?)base.Command; } } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbRowUpdatingEvent.cs b/src/libraries/System.Data.OleDb/src/OleDbRowUpdatingEvent.cs index 6233b2f..d9f38dd 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbRowUpdatingEvent.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbRowUpdatingEvent.cs @@ -7,18 +7,18 @@ namespace System.Data.OleDb { public sealed class OleDbRowUpdatingEventArgs : RowUpdatingEventArgs { - public OleDbRowUpdatingEventArgs(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + public OleDbRowUpdatingEventArgs(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) : base(dataRow, command, statementType, tableMapping) { } - public new OleDbCommand Command + public new OleDbCommand? Command { get { return (base.Command as OleDbCommand); } set { base.Command = value; } } - protected override IDbCommand BaseCommand + protected override IDbCommand? BaseCommand { get { return base.BaseCommand; } set { base.BaseCommand = (value as OleDbCommand); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbStruct.cs b/src/libraries/System.Data.OleDb/src/OleDbStruct.cs index 638b097..69a0e48 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbStruct.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbStruct.cs @@ -248,13 +248,13 @@ namespace System.Data.OleDb internal sealed class tagDBLITERALINFO { [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszLiteralValue = null; + internal string? pwszLiteralValue = null; [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszInvalidChars = null; + internal string? pwszInvalidChars = null; [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszInvalidStartingChars = null; + internal string? pwszInvalidStartingChars = null; internal int it; @@ -309,7 +309,7 @@ namespace System.Data.OleDb internal interface ItagDBPROP { OleDbPropertyStatus dwStatus { get; } - object vValue { get; } + object? vValue { get; } int dwPropertyID { get; } } @@ -318,7 +318,7 @@ namespace System.Data.OleDb { OleDbPropertyStatus ItagDBPROP.dwStatus => this.dwStatus; - object ItagDBPROP.vValue => this.vValue; + object? ItagDBPROP.vValue => this.vValue; int ItagDBPROP.dwPropertyID => this.dwPropertyID; @@ -329,7 +329,7 @@ namespace System.Data.OleDb internal tagDBIDX columnid; // Variant - [MarshalAs(UnmanagedType.Struct)] internal object vValue; + [MarshalAs(UnmanagedType.Struct)] internal object? vValue; internal tagDBPROP_x86() { @@ -348,7 +348,7 @@ namespace System.Data.OleDb { OleDbPropertyStatus ItagDBPROP.dwStatus => this.dwStatus; - object ItagDBPROP.vValue => this.vValue; + object? ItagDBPROP.vValue => this.vValue; int ItagDBPROP.dwPropertyID => this.dwPropertyID; internal int dwPropertyID; @@ -358,7 +358,7 @@ namespace System.Data.OleDb internal tagDBIDX columnid; // Variant - [MarshalAs(UnmanagedType.Struct)] internal object vValue; + [MarshalAs(UnmanagedType.Struct)] internal object? vValue; internal tagDBPROP() { @@ -416,7 +416,7 @@ namespace System.Data.OleDb internal sealed class tagDBCOLUMNINFO { [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszName = null; + internal string? pwszName = null; //[MarshalAs(UnmanagedType.Interface)] internal IntPtr pTypeInfo = (IntPtr)0; @@ -493,8 +493,8 @@ namespace System.Data.OleDb int dwPropertyID { get; } int dwFlags { get; } int vtType { get; } - object vValue { get; } - string pwszDescription { get; } + object? vValue { get; } + string? pwszDescription { get; } } [StructLayout(LayoutKind.Sequential, Pack = 2)] @@ -506,18 +506,18 @@ namespace System.Data.OleDb int ItagDBPROPINFO.vtType => this.vtType; - object ItagDBPROPINFO.vValue => this.vValue; + object? ItagDBPROPINFO.vValue => this.vValue; - string ItagDBPROPINFO.pwszDescription => this.pwszDescription; + string? ItagDBPROPINFO.pwszDescription => this.pwszDescription; - [MarshalAs(UnmanagedType.LPWStr)] internal string pwszDescription; + [MarshalAs(UnmanagedType.LPWStr)] internal string? pwszDescription; internal int dwPropertyID; internal int dwFlags; internal short vtType; - [MarshalAs(UnmanagedType.Struct)] internal object vValue; + [MarshalAs(UnmanagedType.Struct)] internal object? vValue; internal tagDBPROPINFO_x86() { @@ -533,17 +533,17 @@ namespace System.Data.OleDb int ItagDBPROPINFO.vtType => this.vtType; - object ItagDBPROPINFO.vValue => this.vValue; + object? ItagDBPROPINFO.vValue => this.vValue; - string ItagDBPROPINFO.pwszDescription => this.pwszDescription; - [MarshalAs(UnmanagedType.LPWStr)] internal string pwszDescription; + string? ItagDBPROPINFO.pwszDescription => this.pwszDescription; + [MarshalAs(UnmanagedType.LPWStr)] internal string? pwszDescription; internal int dwPropertyID; internal int dwFlags; internal short vtType; - [MarshalAs(UnmanagedType.Struct)] internal object vValue; + [MarshalAs(UnmanagedType.Struct)] internal object? vValue; internal tagDBPROPINFO() { diff --git a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs index 9dbd11d..d871248 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs @@ -11,11 +11,11 @@ namespace System.Data.OleDb { public sealed class OleDbTransaction : DbTransaction { - private readonly OleDbTransaction _parentTransaction; // strong reference to keep parent alive + private readonly OleDbTransaction? _parentTransaction; // strong reference to keep parent alive private readonly System.Data.IsolationLevel _isolationLevel; - private WeakReference _nestedTransaction; // child transactions - private WrappedTransaction _transaction; + private WeakReference? _nestedTransaction; // child transactions + private WrappedTransaction? _transaction; internal OleDbConnection _parentConnection; @@ -114,7 +114,7 @@ namespace System.Data.OleDb } } - internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, IsolationLevel isolevel) + internal OleDbTransaction(OleDbConnection connection, OleDbTransaction? transaction, IsolationLevel isolevel) { _parentConnection = connection; _parentTransaction = transaction; @@ -165,7 +165,7 @@ namespace System.Data.OleDb } } - internal OleDbTransaction Parent + internal OleDbTransaction? Parent { get { @@ -188,7 +188,7 @@ namespace System.Data.OleDb OleDbTransaction transaction = new OleDbTransaction(_parentConnection, this, isolevel); _nestedTransaction = new WeakReference(transaction, false); - UnsafeNativeMethods.ITransactionLocal wrapper = null; + UnsafeNativeMethods.ITransactionLocal? wrapper = null; try { wrapper = (UnsafeNativeMethods.ITransactionLocal)_transaction.ComWrapper(); @@ -238,7 +238,7 @@ namespace System.Data.OleDb } if (null != _nestedTransaction) { - OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target; + OleDbTransaction? transaction = (OleDbTransaction?)_nestedTransaction.Target; if ((null != transaction) && _nestedTransaction.IsAlive) { transaction.CommitInternal(); @@ -291,12 +291,12 @@ namespace System.Data.OleDb { _parentConnection.LocalTransaction = null; } - _parentConnection = null; + _parentConnection = null!; } private void ProcessResults(OleDbHResult hr) { - Exception e = OleDbConnection.ProcessResults(hr, _parentConnection, this); + Exception? e = OleDbConnection.ProcessResults(hr, _parentConnection, this); if (null != e) { throw e; } } @@ -319,7 +319,7 @@ namespace System.Data.OleDb { if (null != _nestedTransaction) { - OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target; + OleDbTransaction? transaction = (OleDbTransaction?)_nestedTransaction.Target; if ((null != transaction) && _nestedTransaction.IsAlive) { hr = transaction.RollbackInternal(exceptionHandling); @@ -353,7 +353,7 @@ namespace System.Data.OleDb { if (null != head._nestedTransaction) { - OleDbTransaction current = (OleDbTransaction)head._nestedTransaction.Target; + OleDbTransaction? current = (OleDbTransaction?)head._nestedTransaction.Target; if ((null != current) && head._nestedTransaction.IsAlive) { return TransactionLast(current); @@ -362,7 +362,7 @@ namespace System.Data.OleDb return head; } - internal static OleDbTransaction TransactionUpdate(OleDbTransaction transaction) + internal static OleDbTransaction? TransactionUpdate(OleDbTransaction? transaction) { if ((null != transaction) && (null == transaction._transaction)) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs b/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs index 19e6680..23ef6c6 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbWrapper.cs @@ -17,10 +17,10 @@ namespace System.Data.OleDb // since we only have one DataLinks object, caching the delegate here is valid as long we // maintain an AddRef which is also the lifetime of this class instance - private readonly UnsafeNativeMethods.IDataInitializeGetDataSource DangerousIDataInitializeGetDataSource; + private readonly UnsafeNativeMethods.IDataInitializeGetDataSource? DangerousIDataInitializeGetDataSource; // DataLinks (the unknown parameter) is created via Activator.CreateInstance outside of the SafeHandle - internal OleDbServicesWrapper(object unknown) : base() + internal OleDbServicesWrapper(object? unknown) : base() { if (null != unknown) { @@ -44,7 +44,7 @@ namespace System.Data.OleDb internal void GetDataSource(OleDbConnectionString constr, ref DataSourceWrapper datasrcWrapper) { OleDbHResult hr; - UnsafeNativeMethods.IDataInitializeGetDataSource GetDataSource = DangerousIDataInitializeGetDataSource; + UnsafeNativeMethods.IDataInitializeGetDataSource GetDataSource = DangerousIDataInitializeGetDataSource!; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -52,7 +52,7 @@ namespace System.Data.OleDb DangerousAddRef(ref mustRelease); // this is the string that DataLinks / OLE DB Services will use to create the provider - string connectionString = constr.ActualConnectionString; + string connectionString = constr.ActualConnectionString!; // base.handle is the 'this' pointer for making the COM call to GetDataSource // the datasrcWrapper will store the IID_IDBInitialize pointer @@ -72,7 +72,7 @@ namespace System.Data.OleDb { throw ODB.ProviderUnavailable(constr.Provider, null); } - Exception e = OleDbConnection.ProcessResults(hr, null, null); + Exception? e = OleDbConnection.ProcessResults(hr, null, null); Debug.Assert(null != e, "CreateProviderError"); throw e; } @@ -113,7 +113,7 @@ namespace System.Data.OleDb IntPtr method = Marshal.ReadIntPtr(vtable, 0); // we cache the QueryInterface delegate to prevent recreating it on every call - UnsafeNativeMethods.IUnknownQueryInterface QueryInterface = constr.DangerousDataSourceIUnknownQueryInterface; + UnsafeNativeMethods.IUnknownQueryInterface? QueryInterface = constr.DangerousDataSourceIUnknownQueryInterface; // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer @@ -130,7 +130,7 @@ namespace System.Data.OleDb method = Marshal.ReadIntPtr(vtable, 3 * IntPtr.Size); // Initialize is the 4'th vtable entry // we cache the Initialize delegate to prevent recreating it on every call - UnsafeNativeMethods.IDBInitializeInitialize Initialize = constr.DangerousIDBInitializeInitialize; + UnsafeNativeMethods.IDBInitializeInitialize? Initialize = constr.DangerousIDBInitializeInitialize; // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer @@ -156,7 +156,7 @@ namespace System.Data.OleDb vtable = Marshal.ReadIntPtr(idbCreateSession, 0); method = Marshal.ReadIntPtr(vtable, 3 * IntPtr.Size); // CreateSession is the 4'th vtable entry - UnsafeNativeMethods.IDBCreateSessionCreateSession CreateSession = constr.DangerousIDBCreateSessionCreateSession; + UnsafeNativeMethods.IDBCreateSessionCreateSession? CreateSession = constr.DangerousIDBCreateSessionCreateSession; // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer @@ -227,7 +227,7 @@ namespace System.Data.OleDb // we cache the DangerousIDBCreateCommandCreateCommand (expecting base.handle to be IDBCreateCommand) // since we maintain an AddRef on IDBCreateCommand it is safe to use the delegate without rechecking its function pointer - private UnsafeNativeMethods.IDBCreateCommandCreateCommand DangerousIDBCreateCommandCreateCommand; + private UnsafeNativeMethods.IDBCreateCommandCreateCommand? DangerousIDBCreateCommandCreateCommand; internal SessionWrapper() : base() { @@ -319,11 +319,11 @@ namespace System.Data.OleDb DangerousIDBCreateCommandCreateCommand = CreateCommand; } - internal OleDbHResult CreateCommand(ref object icommandText) + internal OleDbHResult CreateCommand(ref object? icommandText) { // if (null == CreateCommand), the IDBCreateCommand isn't supported - aka E_NOINTERFACE OleDbHResult hr = OleDbHResult.E_NOINTERFACE; - UnsafeNativeMethods.IDBCreateCommandCreateCommand CreateCommand = DangerousIDBCreateCommandCreateCommand; + UnsafeNativeMethods.IDBCreateCommandCreateCommand? CreateCommand = DangerousIDBCreateCommandCreateCommand; if (null != CreateCommand) { bool mustRelease = false; @@ -362,7 +362,7 @@ namespace System.Data.OleDb } } - // unable to use generics bacause (unknown as T) doesn't compile + // unable to use generics because (unknown as T) doesn't compile internal struct IDBInfoWrapper : IDisposable { // _unknown must be tracked because the _value may not exist, @@ -373,7 +373,7 @@ namespace System.Data.OleDb internal IDBInfoWrapper(object unknown) { _unknown = unknown; - _value = (unknown as UnsafeNativeMethods.IDBInfo); + _value = (unknown as UnsafeNativeMethods.IDBInfo)!; } internal UnsafeNativeMethods.IDBInfo Value @@ -387,8 +387,8 @@ namespace System.Data.OleDb public void Dispose() { object unknown = _unknown; - _unknown = null; - _value = null; + _unknown = null!; + _value = null!; if (null != unknown) { Marshal.ReleaseComObject(unknown); @@ -404,7 +404,7 @@ namespace System.Data.OleDb internal IDBPropertiesWrapper(object unknown) { _unknown = unknown; - _value = (unknown as UnsafeNativeMethods.IDBProperties); + _value = (unknown as UnsafeNativeMethods.IDBProperties)!; Debug.Assert(null != _value, "null IDBProperties"); } @@ -420,8 +420,8 @@ namespace System.Data.OleDb public void Dispose() { object unknown = _unknown; - _unknown = null; - _value = null; + _unknown = null!; + _value = null!; if (null != unknown) { Marshal.ReleaseComObject(unknown); @@ -437,7 +437,7 @@ namespace System.Data.OleDb internal IDBSchemaRowsetWrapper(object unknown) { _unknown = unknown; - _value = (unknown as UnsafeNativeMethods.IDBSchemaRowset); + _value = (unknown as UnsafeNativeMethods.IDBSchemaRowset)!; } internal UnsafeNativeMethods.IDBSchemaRowset Value @@ -451,8 +451,8 @@ namespace System.Data.OleDb public void Dispose() { object unknown = _unknown; - _unknown = null; - _value = null; + _unknown = null!; + _value = null!; if (null != unknown) { Marshal.ReleaseComObject(unknown); @@ -468,7 +468,7 @@ namespace System.Data.OleDb internal IOpenRowsetWrapper(object unknown) { _unknown = unknown; - _value = (unknown as UnsafeNativeMethods.IOpenRowset); + _value = (unknown as UnsafeNativeMethods.IOpenRowset)!; Debug.Assert(null != _value, "null IOpenRowsetWrapper"); } @@ -484,8 +484,8 @@ namespace System.Data.OleDb public void Dispose() { object unknown = _unknown; - _unknown = null; - _value = null; + _unknown = null!; + _value = null!; if (null != unknown) { Marshal.ReleaseComObject(unknown); @@ -501,7 +501,7 @@ namespace System.Data.OleDb internal ITransactionJoinWrapper(object unknown) { _unknown = unknown; - _value = (unknown as NativeMethods.ITransactionJoin); + _value = (unknown as NativeMethods.ITransactionJoin)!; } internal NativeMethods.ITransactionJoin Value @@ -515,8 +515,8 @@ namespace System.Data.OleDb public void Dispose() { object unknown = _unknown; - _unknown = null; - _value = null; + _unknown = null!; + _value = null!; if (null != unknown) { Marshal.ReleaseComObject(unknown); diff --git a/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs b/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs index e2e4915..b1c7664 100644 --- a/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs +++ b/src/libraries/System.Data.OleDb/src/OleDb_Enum.cs @@ -178,7 +178,7 @@ namespace System.Data.OleDb internal readonly DbType enumDbType; // enum System.Data.DbType internal readonly short dbType; // OLE DB DBTYPE_ internal readonly short wType; // OLE DB DBTYPE_ we ask OleDB Provider to bind as - internal readonly Type dataType; // CLR Type + internal readonly Type? dataType; // CLR Type internal readonly int dbPart; // the DBPart w or w/out length internal readonly bool isfixed; // IsFixedLength @@ -189,7 +189,7 @@ namespace System.Data.OleDb internal readonly string dataSourceType; // ICommandWithParameters.SetParameterInfo standard type name internal readonly StringMemHandle dbString; // ptr to native allocated memory for dataSourceType string - private NativeDBType(byte maxpre, int fixlen, bool isfixed, bool islong, OleDbType enumOleDbType, short dbType, string dbstring, Type dataType, short wType, DbType enumDbType) + private NativeDBType(byte maxpre, int fixlen, bool isfixed, bool islong, OleDbType enumOleDbType, short dbType, string dbstring, Type? dataType, short wType, DbType enumDbType) { this.enumOleDbType = enumOleDbType; this.dbType = dbType; @@ -265,7 +265,7 @@ namespace System.Data.OleDb internal static NativeDBType FromSystemType(object value) { - IConvertible ic = (value as IConvertible); + IConvertible? ic = (value as IConvertible); if (null != ic) { return ic.GetTypeCode() switch diff --git a/src/libraries/System.Data.OleDb/src/OleDb_Util.cs b/src/libraries/System.Data.OleDb/src/OleDb_Util.cs index 5d12595..b0a39de 100644 --- a/src/libraries/System.Data.OleDb/src/OleDb_Util.cs +++ b/src/libraries/System.Data.OleDb/src/OleDb_Util.cs @@ -92,7 +92,7 @@ namespace System.Data.OleDb { return ADP.DataAdapter(SR.Format(SR.OleDb_BadStatus_ParamAcc, index.ToString(CultureInfo.InvariantCulture), status.ToString())); } - internal static Exception NoProviderSupportForParameters(string provider, Exception inner) + internal static Exception NoProviderSupportForParameters(string provider, Exception? inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_NoProviderSupportForParameters, provider), inner); } @@ -174,7 +174,7 @@ namespace System.Data.OleDb { return ADP.Argument(SR.Format(SR.OleDb_SchemaRowsetsNotSupported, "IDBSchemaRowset", provider)); } - internal static OleDbException NoErrorInformation(string provider, OleDbHResult hr, Exception inner) + internal static OleDbException NoErrorInformation(string? provider, OleDbHResult hr, Exception? inner) { OleDbException e; if (!ADP.IsEmpty(provider)) @@ -188,7 +188,7 @@ namespace System.Data.OleDb ADP.TraceExceptionAsReturnValue(e); return e; } - internal static InvalidOperationException MDACNotAvailable(Exception inner) + internal static InvalidOperationException MDACNotAvailable(Exception? inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_MDACNotAvailable), inner); } @@ -196,7 +196,7 @@ namespace System.Data.OleDb { return ADP.Argument(SR.Format(SR.OleDb_MSDASQLNotSupported)); } - internal static InvalidOperationException CommandTextNotSupported(string provider, Exception inner) + internal static InvalidOperationException CommandTextNotSupported(string provider, Exception? inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_CommandTextNotSupported, provider), inner); } @@ -204,12 +204,12 @@ namespace System.Data.OleDb { return ADP.DataAdapter(SR.Format(SR.OleDb_PossiblePromptNotUserInteractive)); } - internal static InvalidOperationException ProviderUnavailable(string provider, Exception inner) + internal static InvalidOperationException ProviderUnavailable(string provider, Exception? inner) { //return new OleDbException(SR.Format(SR.OleDb_ProviderUnavailable, provider), (int)OleDbHResult.CO_E_CLASSSTRING, inner); return ADP.DataAdapter(SR.Format(SR.OleDb_ProviderUnavailable, provider), inner); } - internal static InvalidOperationException TransactionsNotSupported(string provider, Exception inner) + internal static InvalidOperationException TransactionsNotSupported(string provider, Exception? inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_TransactionsNotSupported, provider), inner); } @@ -707,7 +707,7 @@ namespace System.Data.OleDb private static readonly Hashtable g_wlookpup = new Hashtable(); internal static string WLookup(short id) { - string value = (string)g_wlookpup[id]; + string? value = (string?)g_wlookpup[id]; if (null == value) { value = "0x" + ((short)id).ToString("X2", CultureInfo.InvariantCulture) + " " + ((short)id); diff --git a/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs b/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs index 60690d0..60b44ba 100644 --- a/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs +++ b/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs @@ -13,15 +13,15 @@ namespace System.Data.OleDb { public Guid _propertySet; public int _propertyID; - public string _description; - public string _lowercase; - public Type _type; + public string? _description; + public string? _lowercase; + public Type? _type; public int _flags; public int _vtype; - public object _supportedValues; + public object? _supportedValues; - public object _defaultValue; + public object? _defaultValue; } internal sealed class PropertyInfoSet : SafeHandle @@ -54,9 +54,9 @@ namespace System.Data.OleDb } } - internal Dictionary GetValues() + internal Dictionary? GetValues() { - Dictionary propertyLookup = null; + Dictionary? propertyLookup = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -88,7 +88,7 @@ namespace System.Data.OleDb propertyInfo._vtype = propinfo.vtType; propertyInfo._supportedValues = propinfo.vValue; propertyInfo._description = propinfo.pwszDescription; - propertyInfo._lowercase = propinfo.pwszDescription.ToLowerInvariant(); + propertyInfo._lowercase = propinfo.pwszDescription!.ToLowerInvariant(); propertyInfo._type = PropertyInfoSet.FromVtType(propinfo.vtType); propertyLookup[propertyInfo._lowercase] = propertyInfo; @@ -142,7 +142,7 @@ namespace System.Data.OleDb return true; } - internal static Type FromVtType(int vartype) => + internal static Type? FromVtType(int vartype) => (VarEnum)vartype switch { VarEnum.VT_EMPTY => null, diff --git a/src/libraries/System.Data.OleDb/src/RowBinding.cs b/src/libraries/System.Data.OleDb/src/RowBinding.cs index fbbd251..7f94bf5 100644 --- a/src/libraries/System.Data.OleDb/src/RowBinding.cs +++ b/src/libraries/System.Data.OleDb/src/RowBinding.cs @@ -15,7 +15,7 @@ namespace System.Data.OleDb private readonly int _dataLength; private readonly int _emptyStringOffset; - private UnsafeNativeMethods.IAccessor _iaccessor; + private UnsafeNativeMethods.IAccessor? _iaccessor; private IntPtr _accessorHandle; private readonly bool _needToReset; @@ -117,9 +117,9 @@ namespace System.Data.OleDb return hr; } - internal ColumnBinding[] SetBindings(OleDbDataReader dataReader, Bindings bindings, + internal ColumnBinding[] SetBindings(OleDbDataReader? dataReader, Bindings bindings, int indexStart, int indexForAccessor, - OleDbParameter[] parameters, tagDBBINDING[] dbbindings, bool ifIRowsetElseIRow) + OleDbParameter[]? parameters, tagDBBINDING[] dbbindings, bool ifIRowsetElseIRow) { Debug.Assert(null != bindings, "null bindings"); Debug.Assert(dbbindings.Length == BindingCount(), "count mismatch"); @@ -150,9 +150,9 @@ namespace System.Data.OleDb for (int indexWithinAccessor = 0; indexWithinAccessor < columns.Length; ++indexWithinAccessor) { int index = indexStart + indexWithinAccessor; - OleDbParameter parameter = ((null != parameters) ? parameters[index] : null); + OleDbParameter? parameter = ((null != parameters) ? parameters[index] : null); columns[indexWithinAccessor] = new ColumnBinding( - dataReader, index, indexForAccessor, indexWithinAccessor, + dataReader!, index, indexForAccessor, indexWithinAccessor, parameter, this, bindings, dbbindings[indexWithinAccessor], _headerLength, ifIRowsetElseIRow); } @@ -172,7 +172,7 @@ namespace System.Data.OleDb Debug.Assert(0 == offset % 8, "invalid alignment"); ValidateCheck(offset, 2 * ODB.SizeOf_Variant); - object value = null; + object? value = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -320,7 +320,7 @@ namespace System.Data.OleDb { ResetValues(); - UnsafeNativeMethods.IAccessor iaccessor = _iaccessor; + UnsafeNativeMethods.IAccessor? iaccessor = _iaccessor; IntPtr accessorHandle = _accessorHandle; _iaccessor = null; @@ -393,7 +393,7 @@ namespace System.Data.OleDb #endif } - private unsafe void ResetValues(IntPtr buffer, object iaccessor) + private unsafe void ResetValues(IntPtr buffer, object? iaccessor) { Debug.Assert(ADP.PtrZero != buffer && _needToReset && _haveData, "shouldn't be calling ResetValues"); for (int i = 0; i < _bindingCount; ++i) @@ -473,7 +473,7 @@ namespace System.Data.OleDb { Debug.Assert(0 == valueOffset % 8, "unexpected unaligned ptr offset"); - UnsafeNativeMethods.IChapteredRowset chapteredRowset = (iaccessor as UnsafeNativeMethods.IChapteredRowset); + UnsafeNativeMethods.IChapteredRowset chapteredRowset = (iaccessor as UnsafeNativeMethods.IChapteredRowset)!; IntPtr chapter = SafeNativeMethods.InterlockedExchangePointer(ADP.IntPtrOffset(buffer, valueOffset), ADP.PtrZero); if (ODB.DB_NULL_HCHAPTER != chapter) { diff --git a/src/libraries/System.Data.OleDb/src/SafeHandles.cs b/src/libraries/System.Data.OleDb/src/SafeHandles.cs index bd26b91..185712b 100644 --- a/src/libraries/System.Data.OleDb/src/SafeHandles.cs +++ b/src/libraries/System.Data.OleDb/src/SafeHandles.cs @@ -21,7 +21,7 @@ namespace System.Data.OleDb } // IDBInfo.GetLiteralInfo - internal DualCoTaskMem(UnsafeNativeMethods.IDBInfo dbInfo, int[] literals, out int literalCount, out IntPtr literalInfo, out OleDbHResult hr) : this() + internal DualCoTaskMem(UnsafeNativeMethods.IDBInfo dbInfo, int[]? literals, out int literalCount, out IntPtr literalInfo, out OleDbHResult hr) : this() { int count = (null != literals) ? literals.Length : 0; hr = dbInfo.GetLiteralInfo(count, literals, out literalCount, out base.handle, out this.handle2); @@ -93,7 +93,7 @@ namespace System.Data.OleDb internal sealed class StringMemHandle : DbBuffer { - internal StringMemHandle(string value) : base((null != value) ? checked(2 + 2 * value.Length) : 0) + internal StringMemHandle(string? value) : base((null != value) ? checked(2 + 2 * value.Length) : 0) { if (null != value) { @@ -128,7 +128,7 @@ namespace System.Data.OleDb } // from ADODBRecordSetConstruction we do not want to release the initial chapter handle - private ChapterHandle(IntPtr chapter) : base((object)null) + private ChapterHandle(IntPtr chapter) : base((object?)null) { _chapterHandle = chapter; } @@ -665,7 +665,7 @@ namespace System.Data.OleDb { OleDbHResult hr = OleDbHResult.E_UNEXPECTED; IntPtr hchapter = chapter; - System.Data.Common.UnsafeNativeMethods.IChapteredRowset chapteredRowset = null; + System.Data.Common.UnsafeNativeMethods.IChapteredRowset? chapteredRowset = null; RuntimeHelpers.PrepareConstrainedRegions(); try { } @@ -687,7 +687,7 @@ namespace System.Data.OleDb internal static unsafe OleDbHResult ITransactionAbort(System.IntPtr ptr) { OleDbHResult hr = OleDbHResult.E_UNEXPECTED; - ITransactionLocal transactionLocal = null; + ITransactionLocal? transactionLocal = null; RuntimeHelpers.PrepareConstrainedRegions(); try { } @@ -709,7 +709,7 @@ namespace System.Data.OleDb internal static unsafe OleDbHResult ITransactionCommit(System.IntPtr ptr) { OleDbHResult hr = OleDbHResult.E_UNEXPECTED; - ITransactionLocal transactionLocal = null; + ITransactionLocal? transactionLocal = null; RuntimeHelpers.PrepareConstrainedRegions(); try { } diff --git a/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj b/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj index 8159590..d3029f0 100644 --- a/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj +++ b/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj @@ -3,6 +3,7 @@ true netstandard2.0-Windows_NT;netstandard2.0;net461-Windows_NT true + enable diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs index 2bb8e85..f5bacfd 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Configuration; using System.Data.SqlTypes; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.Versioning; @@ -66,13 +67,13 @@ namespace System.Data.Common TraceExceptionAsReturnValue(e); return e; } - internal static ArgumentException Argument(string error, Exception inner) + 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) + internal static ArgumentException Argument(string error, string? parameter) { ArgumentException e = new ArgumentException(error, parameter); TraceExceptionAsReturnValue(e); @@ -118,7 +119,7 @@ namespace System.Data.Common { return InvalidCast(error, null); } - internal static InvalidCastException InvalidCast(string error, Exception inner) + internal static InvalidCastException InvalidCast(string error, Exception? inner) { InvalidCastException e = new InvalidCastException(error, inner); TraceExceptionAsReturnValue(e); @@ -136,7 +137,7 @@ namespace System.Data.Common TraceExceptionAsReturnValue(e); return e; } - internal static InvalidOperationException InvalidOperation(string error, Exception inner) + internal static InvalidOperationException InvalidOperation(string error, Exception? inner) { InvalidOperationException e = new InvalidOperationException(error, inner); TraceExceptionAsReturnValue(e); @@ -158,7 +159,7 @@ namespace System.Data.Common { return InvalidOperation(error); } - internal static InvalidOperationException DataAdapter(string error, Exception inner) + internal static InvalidOperationException DataAdapter(string error, Exception? inner) { return InvalidOperation(error, inner); } @@ -366,7 +367,7 @@ namespace System.Data.Common { return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidDataDirectory)); } - internal static ArgumentException InvalidKeyname(string parameterName) + internal static ArgumentException InvalidKeyname(string? parameterName) { return Argument(SR.GetString(SR.ADP_InvalidKey), parameterName); } @@ -376,7 +377,7 @@ namespace System.Data.Common } internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) { - return ADP.Argument(SR.GetString(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); + return ADP.Argument(SR.GetString(SR.SqlConvert_ConvertFailed, fromType.FullName!, toType.FullName!), innerException); } // @@ -424,7 +425,7 @@ namespace System.Data.Common { return InvalidConnectionOptionValue(key, null); } - internal static Exception InvalidConnectionOptionValue(string key, Exception inner) + internal static Exception InvalidConnectionOptionValue(string key, Exception? inner) { return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValue, key), inner); } @@ -509,7 +510,7 @@ namespace System.Data.Common return OpenReaderExists(null); } - internal static Exception OpenReaderExists(Exception e) + internal static Exception OpenReaderExists(Exception? e) { return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e); } @@ -698,7 +699,7 @@ namespace System.Data.Common } internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) { - return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); + return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName!)); } internal static ArgumentException InvalidOffsetValue(int value) { @@ -909,7 +910,7 @@ namespace System.Data.Common return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase)); } - internal static Delegate FindBuilder(MulticastDelegate mcd) + internal static Delegate? FindBuilder(MulticastDelegate? mcd) { // V1.2.3300 if (null != mcd) { @@ -927,20 +928,20 @@ namespace System.Data.Common internal static readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform); internal static readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5)); - internal static SysTx.Transaction GetCurrentTransaction() + internal static SysTx.Transaction? GetCurrentTransaction() { - SysTx.Transaction transaction = SysTx.Transaction.Current; + SysTx.Transaction? transaction = SysTx.Transaction.Current; return transaction; } - internal static void SetCurrentTransaction(SysTx.Transaction transaction) + internal static void SetCurrentTransaction(SysTx.Transaction? transaction) { SysTx.Transaction.Current = transaction; } - internal static SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction) + internal static SysTx.IDtcTransaction? GetOletxTransaction(SysTx.Transaction? transaction) { - SysTx.IDtcTransaction oleTxTransaction = null; + SysTx.IDtcTransaction? oleTxTransaction = null; if (null != transaction) { @@ -1092,11 +1093,11 @@ namespace System.Data.Common } - internal static object ClassesRootRegistryValue(string subkey, string queryvalue) + internal static object? ClassesRootRegistryValue(string subkey, string queryvalue) { try { - using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) + using (RegistryKey? key = Registry.ClassesRoot.OpenSubKey(subkey, false)) { return ((null != key) ? key.GetValue(queryvalue) : null); } @@ -1110,11 +1111,11 @@ namespace System.Data.Common } } - internal static object LocalMachineRegistryValue(string subkey, string queryvalue) + internal static object? LocalMachineRegistryValue(string subkey, string queryvalue) { try { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) + using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(subkey, false)) { return ((null != key) ? key.GetValue(queryvalue) : null); } @@ -1132,14 +1133,14 @@ namespace System.Data.Common internal static void CheckVersionMDAC(bool ifodbcelseoledb) { int major, minor, build; - string version; + string? version; try { - version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer"); + version = (string?)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer"); if (ADP.IsEmpty(version)) { - string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, string.Empty); + string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, string.Empty)!; FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); major = versionInfo.FileMajorPart; minor = versionInfo.FileMinorPart; @@ -1183,7 +1184,7 @@ namespace System.Data.Common // 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) + internal static bool RemoveStringQuotes(string? quotePrefix, string? quoteSuffix, string? quotedString, out string? unquotedString) { int prefixLength; if (quotePrefix == null) @@ -1229,7 +1230,7 @@ namespace System.Data.Common // is the prefix present? if (prefixLength > 0) { - if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false) + if (quotedString.StartsWith(quotePrefix!, StringComparison.Ordinal) == false) { unquotedString = quotedString; return false; @@ -1239,7 +1240,7 @@ namespace System.Data.Common // is the suffix present? if (suffixLength > 0) { - if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false) + if (quotedString.EndsWith(quoteSuffix!, StringComparison.Ordinal) == false) { unquotedString = quotedString; return false; @@ -1279,12 +1280,12 @@ namespace System.Data.Common } // TODO: are those names appropriate for common code? - internal static int SrcCompare(string strA, string strB) + internal static int SrcCompare(string? strA, string? strB) { // this is null safe return ((strA == strB) ? 0 : 1); } - internal static int DstCompare(string strA, string strB) + internal static int DstCompare(string? strA, string? strB) { // this is null safe return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions); } @@ -1312,23 +1313,23 @@ namespace System.Data.Common } #endif - internal static bool IsEmpty(string str) + internal static bool IsEmpty([NotNullWhen(false)] string? str) { return ((null == str) || (0 == str.Length)); } - internal static bool IsEmptyArray(string[] array) + internal static bool IsEmptyArray([NotNullWhen(false)] string?[]? array) { return ((null == array) || (0 == array.Length)); } - internal static bool IsNull(object value) + internal static bool IsNull([NotNullWhen(false)] object? value) { if ((null == value) || (DBNull.Value == value)) { return true; } - INullable nullable = (value as INullable); + INullable? nullable = (value as INullable); return ((null != nullable) && nullable.IsNull); } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs index 011e9d8..80252bd 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/DbConnectionPoolKey.cs @@ -10,9 +10,9 @@ namespace System.Data.Common // Only connection string is used as a key internal class DbConnectionPoolKey : ICloneable { - private string _connectionString; + private string? _connectionString; - internal DbConnectionPoolKey(string connectionString) + internal DbConnectionPoolKey(string? connectionString) { _connectionString = connectionString; } @@ -27,7 +27,7 @@ namespace System.Data.Common return new DbConnectionPoolKey(this); } - internal virtual string ConnectionString + internal virtual string? ConnectionString { get { @@ -40,14 +40,14 @@ namespace System.Data.Common } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null || obj.GetType() != typeof(DbConnectionPoolKey)) { return false; } - DbConnectionPoolKey key = obj as DbConnectionPoolKey; + DbConnectionPoolKey? key = obj as DbConnectionPoolKey; return (key != null && _connectionString == key._connectionString); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs index 32a4c27..918c330 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/FieldNameLookup.cs @@ -12,14 +12,14 @@ namespace System.Data.ProviderBase { // V1.2.3300 // hashtable stores the index into the _fieldNames, match via case-sensitive - private Hashtable _fieldNameLookup; + private Hashtable? _fieldNameLookup; // original names for linear searches when exact matches fail private readonly string[] _fieldNames; // if _defaultLocaleID is -1 then _compareInfo is initialized with InvariantCulture CompareInfo // otherwise it is specified by the server? for the correct compare info - private CompareInfo _compareInfo; + private CompareInfo? _compareInfo; private readonly int _defaultLocaleID; public FieldNameLookup(IDataRecord reader, int defaultLocaleID) @@ -57,7 +57,7 @@ namespace System.Data.ProviderBase GenerateLookup(); } // via case sensitive search, first match with lowest ordinal matches - object value = _fieldNameLookup[fieldName]; + object? value = _fieldNameLookup![fieldName]; return ((null != value) ? (int)value : -1); } @@ -68,7 +68,7 @@ namespace System.Data.ProviderBase GenerateLookup(); } int index; - object value = _fieldNameLookup[fieldName]; + object? value = _fieldNameLookup![fieldName]; if (null != value) { // via case sensitive search, first match with lowest ordinal matches @@ -89,7 +89,7 @@ namespace System.Data.ProviderBase private int LinearIndexOf(string fieldName, CompareOptions compareOptions) { - CompareInfo compareInfo = _compareInfo; + CompareInfo? compareInfo = _compareInfo; if (null == compareInfo) { if (-1 != _defaultLocaleID) @@ -107,7 +107,7 @@ namespace System.Data.ProviderBase { if (0 == compareInfo.Compare(fieldName, _fieldNames[i], compareOptions)) { - _fieldNameLookup[fieldName] = i; // add an exact match for the future + _fieldNameLookup![fieldName] = i; // add an exact match for the future return i; } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs index 6b78870..09ec226 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs @@ -8,11 +8,11 @@ namespace System.Data.Common internal sealed class NameValuePair { private readonly string _name; - private readonly string _value; + private readonly string? _value; private readonly int _length; - private NameValuePair _next; + private NameValuePair? _next; - internal NameValuePair(string name, string value, int length) + internal NameValuePair(string name, string? value, int length) { Debug.Assert(!string.IsNullOrEmpty(name), "empty keyname"); _name = name; @@ -30,9 +30,9 @@ namespace System.Data.Common } internal string Name => _name; - internal string Value => _value; + internal string? Value => _value; - internal NameValuePair Next + internal NameValuePair? Next { get { return _next; } set diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/SR.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/SR.cs index 4212e8d..b89c3c7 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/SR.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/SR.cs @@ -10,7 +10,7 @@ namespace System return value; } - internal static string GetString(string format, params object[] args) + internal static string GetString(string format, params object?[] args) { return SR.Format(format, args); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs index b849aa3..dc0db72 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs @@ -71,7 +71,7 @@ namespace System.Data.ProviderBase Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); - string value = null; + string? value = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs index 8fd14e2..0d89234 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionClosed.cs @@ -23,7 +23,7 @@ namespace System.Data.ProviderBase } } - protected override void Activate(SysTx.Transaction transaction) + protected override void Activate(SysTx.Transaction? transaction) { throw ADP.ClosedConnectionError(); } @@ -43,12 +43,12 @@ namespace System.Data.ProviderBase throw ADP.ClosedConnectionError(); } - public override void EnlistTransaction(SysTx.Transaction transaction) + public override void EnlistTransaction(SysTx.Transaction? transaction) { throw ADP.ClosedConnectionError(); } - protected internal override DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) + protected internal override DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string?[]? restrictions) { throw ADP.ClosedConnectionError(); } @@ -58,7 +58,7 @@ namespace System.Data.ProviderBase throw ADP.ClosedConnectionError(); } - internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { return base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions); } @@ -70,7 +70,7 @@ namespace System.Data.ProviderBase { } - internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { throw ADP.ConnectionAlreadyOpen(State); } @@ -111,7 +111,7 @@ namespace System.Data.ProviderBase connectionFactory.SetInnerConnectionTo(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance); } - internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { if (retry == null || !retry.Task.IsCompleted) { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs index 539ef47..d096b43 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -23,8 +23,8 @@ namespace System.Data.ProviderBase // s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to // a maximum of Environment.ProcessorCount at a time. private static int s_pendingOpenNonPooledNext; - private static readonly Task[] s_pendingOpenNonPooled = new Task[Environment.ProcessorCount]; - private static Task s_completedTask; + private static readonly Task[] s_pendingOpenNonPooled = new Task[Environment.ProcessorCount]; + private static Task? s_completedTask; protected DbConnectionFactory() : this(DbConnectionPoolCountersNoCounters.SingletonInstance) { } @@ -68,13 +68,13 @@ namespace System.Data.ProviderBase throw ADP.NotSupported(); } - internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) + internal DbConnectionInternal? CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions? userOptions) { Debug.Assert(null != owningConnection, "null owningConnection?"); Debug.Assert(null != poolGroup, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; - DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo; + DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo!; DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); @@ -86,10 +86,10 @@ namespace System.Data.ProviderBase return newConnection; } - internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) + internal DbConnectionInternal? CreatePooledConnection(DbConnectionPool pool, DbConnection? owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions? userOptions) { Debug.Assert(null != pool, "null pool?"); - DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; + DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo!; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); if (null != newConnection) @@ -100,7 +100,7 @@ namespace System.Data.ProviderBase return newConnection; } - internal virtual DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) + internal virtual DbConnectionPoolGroupProviderInfo? CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) { return null; } @@ -112,23 +112,23 @@ namespace System.Data.ProviderBase } // GetCompletedTask must be called from within s_pendingOpenPooled lock - private static Task GetCompletedTask() + private static Task GetCompletedTask() { if (s_completedTask == null) { - TaskCompletionSource source = new TaskCompletionSource(); + TaskCompletionSource source = new TaskCompletionSource(); source.SetResult(null); s_completedTask = source.Task; } return s_completedTask; } - internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) + internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource? retry, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection, out DbConnectionInternal? connection) { Debug.Assert(null != owningConnection, "null owningConnection?"); DbConnectionPoolGroup poolGroup; - DbConnectionPool connectionPool; + DbConnectionPool? connectionPool; connection = null; // Work around race condition with clearing the pool between GetConnectionPool obtaining pool @@ -145,7 +145,7 @@ namespace System.Data.ProviderBase do { - poolGroup = GetConnectionPoolGroup(owningConnection); + poolGroup = GetConnectionPoolGroup(owningConnection)!; // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); if (null == connectionPool) @@ -153,7 +153,7 @@ namespace System.Data.ProviderBase // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool // or have a disabled pool entry. - poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled + poolGroup = GetConnectionPoolGroup(owningConnection)!; // previous entry have been disabled if (retry != null) { @@ -190,7 +190,7 @@ namespace System.Data.ProviderBase // than intended. newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) => { - Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction(); + Transactions.Transaction? originalTransaction = ADP.GetCurrentTransaction(); try { ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction); @@ -206,10 +206,10 @@ namespace System.Data.ProviderBase { ADP.SetCurrentTransaction(originalTransaction); } - }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default); + }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default)!; // Place this new task in the slot so any future work will be queued behind it - s_pendingOpenNonPooled[idx] = newTask; + s_pendingOpenNonPooled[idx] = newTask!; } // Set up the timeout (if needed) @@ -229,7 +229,7 @@ namespace System.Data.ProviderBase } else if (task.IsFaulted) { - retry.TrySetException(task.Exception.InnerException); + retry.TrySetException(task.Exception!.InnerException!); } else { @@ -298,7 +298,7 @@ namespace System.Data.ProviderBase return true; } - private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) + private DbConnectionPool? GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) { // if poolgroup is disabled, it will be replaced with a new entry @@ -320,25 +320,25 @@ namespace System.Data.ProviderBase DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; // get the string to hash on again - DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions; + DbConnectionOptions? connectionOptions = connectionPoolGroup.ConnectionOptions; Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); - connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions); + connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions)!; Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } - DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this); + DbConnectionPool? connectionPool = connectionPoolGroup.GetConnectionPool(this); return connectionPool; } - internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions) + internal DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions? poolOptions, ref DbConnectionOptions? userConnectionOptions) { if (ADP.IsEmpty(key.ConnectionString)) { - return (DbConnectionPoolGroup)null; + return null; } - DbConnectionPoolGroup connectionPoolGroup; + DbConnectionPoolGroup? connectionPoolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) { @@ -389,7 +389,7 @@ namespace System.Data.ProviderBase connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { - DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions); + DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions!); newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions); // build new dictionary with space for new connection string @@ -426,7 +426,7 @@ namespace System.Data.ProviderBase // get the matadatafactory from the pool entry. If it does not already have one // create one and save it on the pool entry - DbMetaDataFactory metaDataFactory = connectionPoolGroup.MetaDataFactory; + DbMetaDataFactory? metaDataFactory = connectionPoolGroup.MetaDataFactory; // consider serializing this so we don't construct multiple metadata factories // if two threads happen to hit this at the same time. One will be GC'd @@ -442,7 +442,7 @@ namespace System.Data.ProviderBase return metaDataFactory; } - private void PruneConnectionPoolGroups(object state) + private void PruneConnectionPoolGroups(object? state) { // when debugging this method, expect multiple threads at the same time // First, walk the pool release list and attempt to clear each @@ -559,18 +559,18 @@ namespace System.Data.ProviderBase PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Increment(); } - protected virtual DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) + protected virtual DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningConnection, DbConnectionOptions? userOptions) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection); } - protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection); + protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningConnection); - protected abstract DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous); + protected abstract DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions? previous); - protected abstract DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options); + protected abstract DbConnectionPoolGroupOptions? CreateConnectionPoolGroupOptions(DbConnectionOptions options); - internal abstract DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection); + internal abstract DbConnectionPoolGroup? GetConnectionPoolGroup(DbConnection connection); internal abstract void PermissionDemand(DbConnection outerConnection); internal abstract void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs index 51a21ee..c7cacda 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs @@ -14,8 +14,8 @@ namespace System.Data.OleDb { private static readonly DbConnectionFactory _connectionFactory = OleDbConnectionFactory.SingletonInstance; - private DbConnectionOptions _userConnectionOptions; - private DbConnectionPoolGroup _poolGroup; + private DbConnectionOptions? _userConnectionOptions; + private DbConnectionPoolGroup? _poolGroup; private DbConnectionInternal _innerConnection; private int _closeCount; // used to distinguish between different uses of this object, so we don't have to maintain a list of it's children @@ -52,11 +52,11 @@ namespace System.Data.OleDb } } - internal DbConnectionOptions ConnectionOptions + internal DbConnectionOptions? ConnectionOptions { get { - System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; + System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); } } @@ -64,11 +64,11 @@ namespace System.Data.OleDb private string ConnectionString_Get() { bool hidePassword = InnerConnection.ShouldHidePassword; - DbConnectionOptions connectionOptions = UserConnectionOptions; + DbConnectionOptions? connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); } - private void ConnectionString_Set(string value) + private void ConnectionString_Set(string? value) { DbConnectionPoolKey key = new DbConnectionPoolKey(value); @@ -77,8 +77,8 @@ namespace System.Data.OleDb private void ConnectionString_Set(DbConnectionPoolKey key) { - DbConnectionOptions connectionOptions = null; - System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions); + DbConnectionOptions? connectionOptions = null; + System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions); DbConnectionInternal connectionInternal = InnerConnection; bool flag = connectionInternal.AllowSetConnectionString; if (flag) @@ -115,7 +115,7 @@ namespace System.Data.OleDb } } - internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup + internal System.Data.ProviderBase.DbConnectionPoolGroup? PoolGroup { get { @@ -129,7 +129,7 @@ namespace System.Data.OleDb } } - internal DbConnectionOptions UserConnectionOptions + internal DbConnectionOptions? UserConnectionOptions { get { @@ -144,10 +144,10 @@ namespace System.Data.OleDb protected override DbCommand CreateDbCommand() { - DbCommand command = null; + DbCommand? command = null; DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; - command = providerFactory.CreateCommand(); + command = providerFactory.CreateCommand()!; command.Connection = this; return command; } @@ -189,7 +189,7 @@ namespace System.Data.OleDb // GC.KeepAlive(this); //} - public override void EnlistTransaction(SysTx.Transaction transaction) + public override void EnlistTransaction(SysTx.Transaction? transaction) { // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to @@ -200,7 +200,7 @@ namespace System.Data.OleDb // NOTE: since transaction enlistment involves round trips to the // server, we don't want to lock here, we'll handle the race conditions // elsewhere. - SysTx.Transaction enlistedTransaction = innerConnection.EnlistedTransaction; + SysTx.Transaction? enlistedTransaction = innerConnection.EnlistedTransaction; if (enlistedTransaction != null) { // Allow calling enlist if already enlisted (no-op) @@ -235,11 +235,11 @@ namespace System.Data.OleDb return this.GetSchema(collectionName, null); } - public override DataTable GetSchema(string collectionName, string[] restrictionValues) + public override DataTable GetSchema(string collectionName, string?[]? restrictionValues) { // NOTE: This is virtual because not all providers may choose to support // returning schema data - return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues); + return InnerConnection.GetSchema(ConnectionFactory, PoolGroup!, this, collectionName, restrictionValues); } internal void NotifyWeakReference(int message) @@ -251,14 +251,14 @@ namespace System.Data.OleDb { Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); - System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; - DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + System.Data.ProviderBase.DbConnectionPoolGroup? poolGroup = PoolGroup; + DbConnectionOptions? connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); if ((null == connectionOptions) || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } - DbConnectionOptions userConnectionOptions = UserConnectionOptions; + DbConnectionOptions? userConnectionOptions = UserConnectionOptions; Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs index 802248c..7aa55a9 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs @@ -20,9 +20,9 @@ namespace System.Data.ProviderBase private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections) - private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only) - private DbConnectionPoolCounters _performanceCounters; // the performance counters we're supposed to update - private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated + private DbConnectionPool? _connectionPool; // the pooler that the connection came from (Pooled connections only) + private DbConnectionPoolCounters? _performanceCounters; // the performance counters we're supposed to update + private DbReferenceCollection? _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool) private bool _connectionIsDoomed; // true when the connection should no longer be used. @@ -31,13 +31,13 @@ namespace System.Data.ProviderBase private DateTime _createTime; // when the connection was created. - private SysTx.Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically + private SysTx.Transaction? _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically // _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed. // However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here. // This field should only be assigned a value at the same time _enlistedTransaction is updated. // Also, this reference should not be disposed, since we aren't taking ownership of it. - private SysTx.Transaction _enlistedTransactionOriginal; + private SysTx.Transaction? _enlistedTransactionOriginal; #if DEBUG private int _activateCount; // debug only counter to verify activate/deactivates are in sync. @@ -72,7 +72,7 @@ namespace System.Data.ProviderBase } } - protected internal SysTx.Transaction EnlistedTransaction + protected internal SysTx.Transaction? EnlistedTransaction { get { @@ -80,7 +80,7 @@ namespace System.Data.ProviderBase } set { - SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction; + SysTx.Transaction? currentEnlistedTransaction = _enlistedTransaction; if (((null == currentEnlistedTransaction) && (null != value)) || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) { @@ -92,8 +92,8 @@ namespace System.Data.ProviderBase // we need to use a clone of the transaction // when we store it, or we'll end up keeping it past the // duration of the using block of the TransactionScope - SysTx.Transaction valueClone = null; - SysTx.Transaction previousTransactionClone = null; + SysTx.Transaction? valueClone = null; + SysTx.Transaction? previousTransactionClone = null; try { if (null != value) @@ -231,17 +231,17 @@ namespace System.Data.ProviderBase } } - protected internal object Owner + protected internal object? Owner { // We use a weak reference to the owning object so we can identify when - // it has been garbage collected without thowing exceptions. + // it has been garbage collected without throwing exceptions. get { return _owningObject.Target; } } - internal DbConnectionPool Pool + internal DbConnectionPool? Pool { get { @@ -249,14 +249,14 @@ namespace System.Data.ProviderBase } } - protected DbConnectionPoolCounters PerformanceCounters + protected DbConnectionPoolCounters? PerformanceCounters { get { return _performanceCounters; } } - protected internal DbReferenceCollection ReferenceCollection + protected internal DbReferenceCollection? ReferenceCollection { get { @@ -285,7 +285,7 @@ namespace System.Data.ProviderBase } } - protected abstract void Activate(SysTx.Transaction transaction); + protected abstract void Activate(SysTx.Transaction? transaction); internal void AddWeakReference(object value, int tag) { @@ -312,12 +312,12 @@ namespace System.Data.ProviderBase // By default, there is no preperation required } - protected virtual object ObtainAdditionalLocksForClose() + protected virtual object? ObtainAdditionalLocksForClose() { return null; // no additional locks in default implementation } - protected virtual void ReleaseAdditionalLocksForClose(object lockToken) + protected virtual void ReleaseAdditionalLocksForClose(object? lockToken) { // no additional locks in default implementation } @@ -343,7 +343,7 @@ namespace System.Data.ProviderBase PerformanceCounters.NumberOfActiveConnections.Decrement(); } - if (!_connectionIsDoomed && Pool.UseLoadBalancing) + if (!_connectionIsDoomed && Pool!.UseLoadBalancing) { // If we're not already doomed, check the connection's lifetime and // doom it if it's lifetime has elapsed. @@ -377,7 +377,7 @@ namespace System.Data.ProviderBase Deactivate(); // call it one more time just in case - DbConnectionPool pool = Pool; + DbConnectionPool? pool = Pool; if (null == pool) { @@ -399,7 +399,7 @@ namespace System.Data.ProviderBase // once and for all, or the server will have fits about us // leaving connections open until the client-side GC kicks // in. - PerformanceCounters.NumberOfNonPooledConnections.Decrement(); + PerformanceCounters!.NumberOfNonPooledConnections.Decrement(); Dispose(); } // When _pooledCount is 0, the connection is a pooled connection @@ -419,9 +419,9 @@ namespace System.Data.ProviderBase _connectionIsDoomed = true; } - public abstract void EnlistTransaction(SysTx.Transaction transaction); + public abstract void EnlistTransaction(SysTx.Transaction? transaction); - protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) + protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string?[]? restrictions) { Debug.Assert(outerConnection != null, "outerConnection may not be null."); @@ -456,7 +456,7 @@ namespace System.Data.ProviderBase internal void NotifyWeakReference(int message) { - DbReferenceCollection referenceCollection = ReferenceCollection; + DbReferenceCollection? referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Notify(message); @@ -476,17 +476,17 @@ namespace System.Data.ProviderBase /// override this and do the correct thing. // User code should either override DbConnectionInternal.Activate when it comes out of the pool // or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections - internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { throw ADP.ConnectionAlreadyOpen(State); } - protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) + protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource? retry, DbConnectionOptions? userOptions) { // ?->Connecting: prevent set_ConnectionString during Open if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) { - DbConnectionInternal openConnection = null; + DbConnectionInternal? openConnection = null; try { connectionFactory.PermissionDemand(outerConnection); @@ -512,7 +512,7 @@ namespace System.Data.ProviderBase return true; } - internal void PrePush(object expectedOwner) + internal void PrePush(object? expectedOwner) { // Called by DbConnectionPool when we're about to be put into it's pool, we // take this opportunity to ensure ownership and pool counts are legit. @@ -581,7 +581,7 @@ namespace System.Data.ProviderBase internal void RemoveWeakReference(object value) { - DbReferenceCollection referenceCollection = ReferenceCollection; + DbReferenceCollection? referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Remove(value); @@ -590,7 +590,7 @@ namespace System.Data.ProviderBase internal void DetachCurrentTransactionIfEnded() { - SysTx.Transaction enlistedTransaction = EnlistedTransaction; + SysTx.Transaction? enlistedTransaction = EnlistedTransaction; if (enlistedTransaction != null) { bool transactionIsDead; @@ -619,10 +619,10 @@ namespace System.Data.ProviderBase lock (this) { // Detach if detach-on-end behavior, or if outer connection was closed - DbConnection owner = (DbConnection)Owner; + DbConnection? owner = (DbConnection?)Owner; if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) { - SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction; + SysTx.Transaction? currentEnlistedTransaction = _enlistedTransaction; if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) { EnlistedTransaction = null; @@ -639,12 +639,12 @@ namespace System.Data.ProviderBase internal void SetInStasis() { _isInStasis = true; - PerformanceCounters.NumberOfStasisConnections.Increment(); + PerformanceCounters!.NumberOfStasisConnections.Increment(); } private void TerminateStasis(bool returningToPool) { - PerformanceCounters.NumberOfStasisConnections.Decrement(); + PerformanceCounters!.NumberOfStasisConnections.Decrement(); _isInStasis = false; } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs index 2f63a7a..f98d94b 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs @@ -11,7 +11,7 @@ namespace System.Data.ProviderBase { internal abstract partial class DbConnectionInternal { - internal void ActivateConnection(SysTx.Transaction transaction) + internal void ActivateConnection(SysTx.Transaction? transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. @@ -22,7 +22,7 @@ namespace System.Data.ProviderBase Activate(transaction); - PerformanceCounters.NumberOfActiveConnections.Increment(); + PerformanceCounters!.NumberOfActiveConnections.Increment(); } internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) @@ -76,12 +76,12 @@ namespace System.Data.ProviderBase // Lock to prevent race condition with cancellation lock (this) { - object lockToken = ObtainAdditionalLocksForClose(); + object? lockToken = ObtainAdditionalLocksForClose(); try { PrepareForCloseConnection(); - DbConnectionPool connectionPool = Pool; + DbConnectionPool? connectionPool = Pool; // Detach from enlisted transactions that are no longer active on close DetachCurrentTransactionIfEnded(); @@ -100,7 +100,7 @@ namespace System.Data.ProviderBase { Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up... - PerformanceCounters.HardDisconnectsPerSecond.Increment(); + PerformanceCounters!.HardDisconnectsPerSecond.Increment(); // To prevent an endless recursion, we need to clear // the owning object before we call dispose so that @@ -143,7 +143,7 @@ namespace System.Data.ProviderBase // Dispose of the _enlistedTransaction since it is a clone // of the original reference. // _enlistedTransaction can be changed by another thread (TX end event) - SysTx.Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null); + SysTx.Transaction? enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null); if (enlistedTransaction != null) { enlistedTransaction.Dispose(); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs index 5809fc7..e411fc5 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs @@ -47,7 +47,7 @@ namespace System.Data.ProviderBase private sealed class PendingGetConnection { - public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions userOptions) + public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions? userOptions) { DueTime = dueTime; Owner = owner; @@ -56,7 +56,7 @@ namespace System.Data.ProviderBase public long DueTime { get; private set; } public DbConnection Owner { get; private set; } public TaskCompletionSource Completion { get; private set; } - public DbConnectionOptions UserOptions { get; private set; } + public DbConnectionOptions? UserOptions { get; private set; } } private sealed class TransactedConnectionPool @@ -81,13 +81,13 @@ namespace System.Data.ProviderBase } } - internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) + internal DbConnectionInternal? GetTransactedObject(SysTx.Transaction transaction) { Debug.Assert(null != transaction, "null transaction?"); - DbConnectionInternal transactedObject = null; + DbConnectionInternal? transactedObject = null; - TransactedConnectionList connections; + TransactedConnectionList? connections; bool txnFound = false; lock (_transactedCxns) @@ -126,7 +126,7 @@ namespace System.Data.ProviderBase Debug.Assert(null != transaction, "null transaction?"); Debug.Assert(null != transactedObject, "null transactedObject?"); - TransactedConnectionList connections; + TransactedConnectionList? connections; bool txnFound = false; // NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee @@ -155,8 +155,8 @@ namespace System.Data.ProviderBase { // create the transacted pool, making sure to clone the associated transaction // for use as a key in our internal dictionary of transactions and connections - SysTx.Transaction transactionClone = null; - TransactedConnectionList newConnections = null; + SysTx.Transaction? transactionClone = null; + TransactedConnectionList? newConnections = null; try { @@ -339,7 +339,7 @@ namespace System.Data.ProviderBase private static readonly Random _random = new Random(5101977); // Value obtained from Dave Driver private readonly int _cleanupWait; - private readonly DbConnectionPoolIdentity _identity; + private readonly DbConnectionPoolIdentity? _identity; private readonly DbConnectionFactory _connectionFactory; private readonly DbConnectionPoolGroup _connectionPoolGroup; @@ -357,15 +357,15 @@ namespace System.Data.ProviderBase private int _waitCount; private readonly PoolWaitHandles _waitHandles; - private Exception _resError; + private Exception? _resError; private volatile bool _errorOccurred; private int _errorWait; - private Timer _errorTimer; + private Timer? _errorTimer; - private Timer _cleanupTimer; + private Timer? _cleanupTimer; - private readonly TransactedConnectionPool _transactedConnectionPool; + private readonly TransactedConnectionPool? _transactedConnectionPool; private readonly List _objectList; private int _totalObjects; @@ -508,7 +508,7 @@ namespace System.Data.ProviderBase get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); } } - private void CleanupCallback(object state) + private void CleanupCallback(object? state) { // Called when the cleanup-timer ticks over. @@ -536,7 +536,7 @@ namespace System.Data.ProviderBase if (_waitHandles.PoolSemaphore.WaitOne(0, false) /* != WAIT_TIMEOUT */) { // We obtained a objects from the semaphore. - DbConnectionInternal obj; + DbConnectionInternal? obj; if (_stackOld.TryPop(out obj)) { @@ -595,7 +595,7 @@ namespace System.Data.ProviderBase { while (true) { - DbConnectionInternal obj; + DbConnectionInternal? obj; if (!_stackNew.TryPop(out obj)) break; @@ -616,7 +616,7 @@ namespace System.Data.ProviderBase internal void Clear() { - DbConnectionInternal obj; + DbConnectionInternal? obj; // First, quickly doom everything. lock (_objectList) @@ -660,9 +660,9 @@ namespace System.Data.ProviderBase private bool IsBlockingPeriodEnabled() => true; - private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) + private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection) { - DbConnectionInternal newObj = null; + DbConnectionInternal? newObj = null; try { @@ -821,7 +821,7 @@ namespace System.Data.ProviderBase // the transaction asyncronously completing on a second // thread. - SysTx.Transaction transaction = obj.EnlistedTransaction; + SysTx.Transaction? transaction = obj.EnlistedTransaction; if (null != transaction) { // NOTE: we're not locking on _state, so it's possible that its @@ -921,13 +921,13 @@ namespace System.Data.ProviderBase } } - private void ErrorCallback(object state) + private void ErrorCallback(object? state) { _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); // the error state is cleaned, destroy the timer to avoid periodic invocation - Timer t = _errorTimer; + Timer? t = _errorTimer; _errorTimer = null; if (t != null) { @@ -937,7 +937,7 @@ namespace System.Data.ProviderBase // TODO: move this to src/Common and integrate with SqlClient // Note: OleDb connections are not passing through this code - private Exception TryCloneCachedException() + private Exception? TryCloneCachedException() { return _resError; } @@ -946,7 +946,7 @@ namespace System.Data.ProviderBase { Debug.Assert(!Thread.CurrentThread.IsThreadPoolThread, "This thread may block for a long time. Threadpool threads should not be used."); - PendingGetConnection next; + PendingGetConnection? next; do { @@ -985,9 +985,9 @@ namespace System.Data.ProviderBase delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0); } - DbConnectionInternal connection = null; + DbConnectionInternal? connection = null; bool timeout = false; - Exception caughtException = null; + Exception? caughtException = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1050,7 +1050,7 @@ namespace System.Data.ProviderBase } while (_pendingOpens.TryPeek(out next)); } - internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource retry, DbConnectionOptions userOptions, out DbConnectionInternal connection) + internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource? retry, DbConnectionOptions? userOptions, out DbConnectionInternal? connection) { uint waitForMultipleObjectsTimeout = 0; bool allowCreate = false; @@ -1103,10 +1103,10 @@ namespace System.Data.ProviderBase return false; } - private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection) + private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions? userOptions, out DbConnectionInternal? connection) { - DbConnectionInternal obj = null; - SysTx.Transaction transaction = null; + DbConnectionInternal? obj = null; + SysTx.Transaction? transaction = null; PerformanceCounters.SoftConnectsPerSecond.Increment(); @@ -1168,7 +1168,7 @@ namespace System.Data.ProviderBase case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. Interlocked.Decrement(ref _waitCount); - throw TryCloneCachedException(); + throw TryCloneCachedException()!; case CREATION_HANDLE: @@ -1301,7 +1301,7 @@ namespace System.Data.ProviderBase return true; } - private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, SysTx.Transaction transaction) + private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, SysTx.Transaction? transaction) { lock (obj) { // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop @@ -1327,15 +1327,15 @@ namespace System.Data.ProviderBase /// Options used to create the new connection /// Inner connection that will be replaced /// A new inner connection that is attached to the - internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) + internal DbConnectionInternal? ReplaceConnection(DbConnection owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); + DbConnectionInternal? newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) { - PrepareConnection(owningObject, newConnection, oldConnection.EnlistedTransaction); + PrepareConnection(owningObject, newConnection, oldConnection!.EnlistedTransaction); oldConnection.PrepareForReplaceConnection(); oldConnection.DeactivateConnection(); oldConnection.Dispose(); @@ -1344,9 +1344,9 @@ namespace System.Data.ProviderBase return newConnection; } - private DbConnectionInternal GetFromGeneralPool() + private DbConnectionInternal? GetFromGeneralPool() { - DbConnectionInternal obj = null; + DbConnectionInternal? obj = null; if (!_stackNew.TryPop(out obj)) { @@ -1377,10 +1377,10 @@ namespace System.Data.ProviderBase return (obj); } - private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transaction) + private DbConnectionInternal? GetFromTransactedPool(out SysTx.Transaction? transaction) { transaction = ADP.GetCurrentTransaction(); - DbConnectionInternal obj = null; + DbConnectionInternal? obj = null; if (null != transaction && null != _transactedConnectionPool) { @@ -1412,7 +1412,7 @@ namespace System.Data.ProviderBase return obj; } - private void PoolCreateRequest(object state) + private void PoolCreateRequest(object? state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained @@ -1442,7 +1442,7 @@ namespace System.Data.ProviderBase // since either Open will fail or we will open a object for this pool that does // not belong in this pool. The side effect of this is that if using integrated // security min pool size cannot be guaranteed. - if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent())) + if (UsingIntegrateSecurity && !_identity!.Equals(DbConnectionPoolIdentity.GetCurrent())) { return; } @@ -1686,7 +1686,7 @@ namespace System.Data.ProviderBase _state = State.ShuttingDown; // deactivate timer callbacks - Timer t = _cleanupTimer; + Timer? t = _cleanupTimer; _cleanupTimer = null; if (null != t) { @@ -1694,15 +1694,15 @@ namespace System.Data.ProviderBase } } - private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null) + private DbConnectionInternal? UserCreateRequest(DbConnection owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection = null) { // called by user when they were not able to obtain a free object but // instead obtained creation mutex - DbConnectionInternal obj = null; + DbConnectionInternal? obj = null; if (ErrorOccurred) { - throw TryCloneCachedException(); + throw TryCloneCachedException()!; } else { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs index df6f363..e1c2f3b 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs @@ -90,9 +90,9 @@ namespace System.Data.ProviderBase internal sealed class Counter { - private PerformanceCounter _instance; + private PerformanceCounter? _instance; - internal Counter(string categoryName, string instanceName, string counterName, PerformanceCounterType counterType) + internal Counter(string? categoryName, string? instanceName, string counterName, PerformanceCounterType counterType) { if (ADP.IsPlatformNT5) { @@ -120,7 +120,7 @@ namespace System.Data.ProviderBase internal void Decrement() { - PerformanceCounter instance = _instance; + PerformanceCounter? instance = _instance; if (null != instance) { instance.Decrement(); @@ -129,7 +129,7 @@ namespace System.Data.ProviderBase internal void Dispose() { // TODO: race condition, Dispose at the same time as Increment/Decrement - PerformanceCounter instance = _instance; + PerformanceCounter? instance = _instance; _instance = null; if (null != instance) { @@ -142,7 +142,7 @@ namespace System.Data.ProviderBase internal void Increment() { - PerformanceCounter instance = _instance; + PerformanceCounter? instance = _instance; if (null != instance) { instance.Increment(); @@ -171,13 +171,13 @@ namespace System.Data.ProviderBase { } - protected DbConnectionPoolCounters(string categoryName, string categoryHelp) + protected DbConnectionPoolCounters(string? categoryName, string? categoryHelp) { AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler); AppDomain.CurrentDomain.ProcessExit += new EventHandler(this.ExitEventHandler); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler); - string instanceName = null; + string? instanceName = null; if (!ADP.IsEmpty(categoryName)) { @@ -188,7 +188,7 @@ namespace System.Data.ProviderBase } // level 0-3: hard connects/disconnects, plus basic pool/pool entry statistics - string basicCategoryName = categoryName; + string? basicCategoryName = categoryName; HardConnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardConnectsPerSecond.CounterName, CreationData.HardConnectsPerSecond.CounterType); HardDisconnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardDisconnectsPerSecond.CounterName, CreationData.HardDisconnectsPerSecond.CounterType); NumberOfNonPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfNonPooledConnections.CounterName, CreationData.NumberOfNonPooledConnections.CounterType); @@ -201,7 +201,7 @@ namespace System.Data.ProviderBase NumberOfReclaimedConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfReclaimedConnections.CounterName, CreationData.NumberOfReclaimedConnections.CounterType); // level 4: expensive stuff - string verboseCategoryName = null; + string? verboseCategoryName = null; if (!ADP.IsEmpty(categoryName)) { // don't load TraceSwitch if no categoryName so that Odbc/OleDb have a chance of not loading TraceSwitch @@ -217,12 +217,12 @@ namespace System.Data.ProviderBase NumberOfActiveConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfActiveConnections.CounterName, CreationData.NumberOfActiveConnections.CounterType); NumberOfFreeConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType); } - private string GetAssemblyName() + private string? GetAssemblyName() { - string result = null; + string? result = null; // First try GetEntryAssembly name, then AppDomain.FriendlyName. - Assembly assembly = Assembly.GetEntryAssembly(); + Assembly? assembly = Assembly.GetEntryAssembly(); if (null != assembly) { @@ -239,9 +239,9 @@ namespace System.Data.ProviderBase // TODO: remove the Resource* attributes if you do not use GetCurrentProcessId after the fix private string GetInstanceName() { - string result = null; + string? result = null; - string instanceName = GetAssemblyName(); // instance perfcounter name + string? instanceName = GetAssemblyName(); // instance perfcounter name if (ADP.IsEmpty(instanceName)) { @@ -259,7 +259,7 @@ namespace System.Data.ProviderBase // to PERFMON. They recommend that we translate them as shown below, to // prevent problems. - result = string.Format((IFormatProvider)null, "{0}[{1}]", instanceName, pid); + result = string.Format(null, "{0}[{1}]", instanceName, pid); result = result.Replace('(', '[').Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_'); // counter instance name cannot be greater than 127 @@ -272,13 +272,13 @@ namespace System.Data.ProviderBase const string insertString = "[...]"; int firstPartLength = (CounterInstanceNameMaxLength - insertString.Length) / 2; int lastPartLength = CounterInstanceNameMaxLength - firstPartLength - insertString.Length; - result = string.Format((IFormatProvider)null, "{0}{1}{2}", + result = string.Format(null, "{0}{1}{2}", result.Substring(0, firstPartLength), insertString, result.Substring(result.Length - lastPartLength, lastPartLength)); Debug.Assert(result.Length == CounterInstanceNameMaxLength, - string.Format((IFormatProvider)null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length)); + string.Format(null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length)); } return result; @@ -319,12 +319,12 @@ namespace System.Data.ProviderBase } } - private void ExitEventHandler(object sender, EventArgs e) + private void ExitEventHandler(object? sender, EventArgs e) { Dispose(); } - private void UnloadEventHandler(object sender, EventArgs e) + private void UnloadEventHandler(object? sender, EventArgs e) { Dispose(); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs index 0f9320b..792f6e7 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -33,8 +33,8 @@ namespace System.Data.ProviderBase private int _state; // see PoolGroupState* below - private DbConnectionPoolGroupProviderInfo _providerInfo; - private DbMetaDataFactory _metaDataFactory; + private DbConnectionPoolGroupProviderInfo? _providerInfo; + private DbMetaDataFactory? _metaDataFactory; // always lock this before changing _state, we don't want to move out of the 'Disabled' state // PoolGroupStateUninitialized = 0; @@ -49,7 +49,7 @@ namespace System.Data.ProviderBase _connectionOptions = connectionOptions; _poolKey = key; - _poolGroupOptions = poolGroupOptions; + _poolGroupOptions = poolGroupOptions!; // always lock this object before changing state // HybridDictionary does not create any sub-objects until add @@ -75,7 +75,7 @@ namespace System.Data.ProviderBase } } - internal DbConnectionPoolGroupProviderInfo ProviderInfo + internal DbConnectionPoolGroupProviderInfo? ProviderInfo { get { @@ -86,7 +86,7 @@ namespace System.Data.ProviderBase _providerInfo = value; if (null != value) { - _providerInfo.PoolGroup = this; + _providerInfo!.PoolGroup = this; } } } @@ -107,7 +107,7 @@ namespace System.Data.ProviderBase } } - internal DbMetaDataFactory MetaDataFactory + internal DbMetaDataFactory? MetaDataFactory { get { @@ -126,7 +126,7 @@ namespace System.Data.ProviderBase // will return the number of connections in the group after clearing has finished // First, note the old collection and create a new collection to be used - ConcurrentDictionary oldPoolCollection = null; + ConcurrentDictionary? oldPoolCollection = null; lock (this) { if (_poolCollection.Count > 0) @@ -162,7 +162,7 @@ namespace System.Data.ProviderBase return _poolCollection.Count; } - internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory) + internal DbConnectionPool? GetConnectionPool(DbConnectionFactory connectionFactory) { // When this method returns null it indicates that the connection // factory should not use pooling. @@ -171,12 +171,12 @@ namespace System.Data.ProviderBase // many of the APIs we require. // PoolGroupOptions will only be null when we're not supposed to pool // connections. - DbConnectionPool pool = null; + DbConnectionPool? pool = null; if (null != _poolGroupOptions) { Debug.Assert(ADP.IsWindowsNT, "should not be pooling on Win9x"); - DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity; + DbConnectionPoolIdentity? currentIdentity = DbConnectionPoolIdentity.NoIdentity; if (_poolGroupOptions.PoolByIdentity) { // if we're pooling by identity (because integrated security is diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs index 9117202..44c2fd1 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs @@ -5,9 +5,9 @@ namespace System.Data.ProviderBase { internal class DbConnectionPoolGroupProviderInfo { - private DbConnectionPoolGroup _poolGroup; + private DbConnectionPoolGroup? _poolGroup; - internal DbConnectionPoolGroup PoolGroup + internal DbConnectionPoolGroup? PoolGroup { get { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs index a7d839b..9fe3910 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs @@ -58,7 +58,7 @@ namespace System.Data.ProviderBase return resultSid; } - public override bool Equals(object value) + public override bool Equals(object? value) { bool result = ((this == NoIdentity) || (this == value)); if (!result && (null != value)) diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 24e6650..68892d6 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -38,7 +38,8 @@ namespace System.Data.ProviderBase ADP.CheckArgumentNull(serverVersion, "serverVersion"); ADP.CheckArgumentNull(normalizedServerVersion, "normalizedServerVersion"); - LoadDataSetFromXml(xmlStream); + _metaDataCollectionsDataSet = new DataSet { Locale = CultureInfo.InvariantCulture }; + _metaDataCollectionsDataSet.ReadXml(xmlStream); _serverVersionString = serverVersion; _normalizedServerVersion = normalizedServerVersion; @@ -68,9 +69,9 @@ namespace System.Data.ProviderBase } } - protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames) + protected DataTable CloneAndFilterCollection(string collectionName, string[]? hiddenColumnNames) { - DataTable sourceTable; + DataTable? sourceTable; DataTable destinationTable; DataColumn[] filteredSourceColumns; DataColumnCollection destinationColumns; @@ -115,28 +116,28 @@ namespace System.Data.ProviderBase { if (disposing) { - _normalizedServerVersion = null; - _serverVersionString = null; + _normalizedServerVersion = null!; + _serverVersionString = null!; _metaDataCollectionsDataSet.Dispose(); } } - private DataTable ExecuteCommand(DataRow requestedCollectionRow, string[] restrictions, DbConnection connection) + private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? restrictions, DbConnection connection) { - DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString]; - DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions]; - DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName]; + DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; + DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString]!; + DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions]!; + DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName]!; //DataColumn restrictionNameColumn = metaDataCollectionsTable.Columns[_restrictionName]; - DataTable resultTable = null; - DbCommand command = null; - DataTable schemaTable = null; + DataTable? resultTable = null; + DbCommand? command = null; + DataTable? schemaTable = null; Debug.Assert(requestedCollectionRow != null); - string sqlCommand = requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string; + string sqlCommand = (requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string)!; int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn, DataRowVersion.Current]; - string collectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string; + string collectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; if ((restrictions != null) && (restrictions.Length > numberOfRestrictions)) { @@ -167,7 +168,7 @@ namespace System.Data.ProviderBase command.Parameters.Add(restrictionParameter); } - DbDataReader reader = null; + DbDataReader? reader = null; try { try @@ -212,11 +213,11 @@ namespace System.Data.ProviderBase return resultTable; } - private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns) + private DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumnNames, DataColumnCollection destinationColumns) { DataColumn newDestinationColumn; int currentColumn; - DataColumn[] filteredSourceColumns = null; + DataColumn[]? filteredSourceColumns = null; int columnCount = 0; foreach (DataColumn sourceColumn in sourceTable.Columns) @@ -253,23 +254,23 @@ namespace System.Data.ProviderBase bool versionFailure; bool haveExactMatch; bool haveMultipleInexactMatches; - string candidateCollectionName; + string? candidateCollectionName; - DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; + DataTable? metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; if (metaDataCollectionsTable == null) { throw ADP.InvalidXml(); } - DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; + DataColumn? collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName); } - DataRow requestedCollectionRow = null; - string exactCollectionName = null; + DataRow? requestedCollectionRow = null; + string? exactCollectionName = null; // find the requested collection versionFailure = false; @@ -341,8 +342,8 @@ namespace System.Data.ProviderBase private void FixUpVersion(DataTable dataSourceInfoTable) { Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation); - DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion]; - DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized]; + DataColumn? versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion]; + DataColumn? normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized]; if ((versionColumn == null) || (normalizedVersionColumn == null)) { @@ -363,14 +364,14 @@ namespace System.Data.ProviderBase private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) { - DataTable restrictionsTable = null; - DataColumnCollection restrictionColumns = null; - DataColumn collectionName = null; - DataColumn parameterName = null; - DataColumn restrictionName = null; - DataColumn restrictionNumber = null; + DataTable? restrictionsTable = null; + DataColumnCollection? restrictionColumns = null; + DataColumn? collectionName = null; + DataColumn? parameterName = null; + DataColumn? restrictionName = null; + DataColumn? restrictionNumber = null; ; - string result = null; + string? result = null; restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; if (restrictionsTable != null) @@ -390,7 +391,7 @@ namespace System.Data.ProviderBase throw ADP.MissingRestrictionColumn(); } - foreach (DataRow restriction in restrictionsTable.Rows) + foreach (DataRow restriction in restrictionsTable!.Rows) { if (((string)restriction[collectionName] == neededCollectionName) && ((int)restriction[restrictionNumber] == neededRestrictionNumber) && @@ -410,26 +411,26 @@ namespace System.Data.ProviderBase } - public virtual DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions) + public virtual DataTable GetSchema(DbConnection connection, string collectionName, string?[]? restrictions) { Debug.Assert(_metaDataCollectionsDataSet != null); - DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; - DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]; - DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; - DataRow requestedCollectionRow = null; - DataTable requestedSchema = null; - string[] hiddenColumns; - string exactCollectionName = null; + DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; + DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]!; + DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]!; + DataRow? requestedCollectionRow = null; + DataTable? requestedSchema = null; + string[]? hiddenColumns; + string? exactCollectionName = null; requestedCollectionRow = FindMetaDataCollectionRow(collectionName); - exactCollectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string; + exactCollectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; if (ADP.IsEmptyArray(restrictions) == false) { - for (int i = 0; i < restrictions.Length; i++) + for (int i = 0; i < restrictions!.Length; i++) { - if ((restrictions[i] != null) && (restrictions[i].Length > 4096)) + if ((restrictions[i]?.Length > 4096)) { // use a non-specific error because no new beta 2 error messages are allowed // TODO: will add a more descriptive error in RTM @@ -438,7 +439,7 @@ namespace System.Data.ProviderBase } } - string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string; + string populationMechanism = (requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string)!; switch (populationMechanism) { case _dataTable: @@ -485,7 +486,7 @@ namespace System.Data.ProviderBase return requestedSchema; } - private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames) + private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames) { bool result = true; string sourceColumnName = sourceColumn.ColumnName; @@ -516,14 +517,7 @@ namespace System.Data.ProviderBase return result; } - private void LoadDataSetFromXml(Stream XmlStream) - { - _metaDataCollectionsDataSet = new DataSet(); - _metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture; - _metaDataCollectionsDataSet.ReadXml(XmlStream); - } - - protected virtual DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection) + protected virtual DataTable PrepareCollection(string collectionName, string?[]? restrictions, DbConnection connection) { throw ADP.NotSupported(); } @@ -532,7 +526,7 @@ namespace System.Data.ProviderBase { bool result = true; DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns; - DataColumn versionColumn; + DataColumn? versionColumn; object version; // check the minimum version first diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs index c08b343..8cf24c8 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbReferenceCollection.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Data.ProviderBase @@ -51,7 +52,7 @@ namespace System.Data.ProviderBase } } - public object Target + public object? Target { get { @@ -132,6 +133,7 @@ namespace System.Data.ProviderBase } } + [return: MaybeNull] internal T FindItem(int tag, Func filterMethod) where T : class { bool lockObtained = false; @@ -150,11 +152,11 @@ namespace System.Data.ProviderBase { // NOTE: Check if the returned value is null twice may seem wasteful, but this if for performance // Since checking for null twice is cheaper than calling both HasTarget and Target OR always attempting to typecast - object value = _items[counter].Target; + object? value = _items[counter].Target; if (value != null) { // Make sure the item has the correct type and passes the filtering - T tempItem = value as T; + T? tempItem = value as T; if ((tempItem != null) && (filterMethod(tempItem))) { return tempItem; @@ -191,7 +193,7 @@ namespace System.Data.ProviderBase { for (int index = 0; index <= _lastItemIndex; ++index) { - object value = _items[index].Target; // checks tag & gets target + object? value = _items[index].Target; // checks tag & gets target if (null != value) { NotifyItem(message, _items[index].Tag, value); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs index 66ba0d1..a45f38e 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/WrappedIUnknown.cs @@ -18,7 +18,7 @@ namespace System.Data.ProviderBase { } - internal WrappedIUnknown(object unknown) : this() + internal WrappedIUnknown(object? unknown) : this() { if (null != unknown) { @@ -44,7 +44,7 @@ namespace System.Data.ProviderBase { // NOTE: Method, instead of property, to avoid being evaluated at // runtime in the debugger. - object value = null; + object? value = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try diff --git a/src/libraries/System.Data.OleDb/src/UnsafeNativeMethods.cs b/src/libraries/System.Data.OleDb/src/UnsafeNativeMethods.cs index b6e203b..4f67170 100644 --- a/src/libraries/System.Data.OleDb/src/UnsafeNativeMethods.cs +++ b/src/libraries/System.Data.OleDb/src/UnsafeNativeMethods.cs @@ -337,7 +337,7 @@ namespace System.Data.Common [PreserveSig] System.Data.OleDb.OleDbHResult GetProperties( [In] int cPropertyIDSets, - [In] SafeHandle rgPropertyIDSets, + [In] SafeHandle? rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertySets); @@ -372,7 +372,7 @@ namespace System.Data.Common System.Data.OleDb.OleDbHResult Execute( [In] IntPtr pUnkOuter, [In] ref Guid riid, - [In] System.Data.OleDb.tagDBPARAMS pDBParams, + [In] System.Data.OleDb.tagDBPARAMS? pDBParams, [Out] out IntPtr pcRowsAffected, [Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset); @@ -436,7 +436,7 @@ namespace System.Data.Common [PreserveSig] System.Data.OleDb.OleDbHResult GetLiteralInfo( [In] int cLiterals, - [In, MarshalAs(UnmanagedType.LPArray)] int[] rgLiterals, + [In, MarshalAs(UnmanagedType.LPArray)] int[]? rgLiterals, [Out] out int pcLiteralInfo, [Out] out IntPtr prgLiteralInfo, [Out] out IntPtr ppCharBuffer); @@ -455,7 +455,7 @@ namespace System.Data.Common [PreserveSig] System.Data.OleDb.OleDbHResult GetProperties( [In] int cPropertyIDSets, - [In] SafeHandle rgPropertyIDSets, + [In] SafeHandle? rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertySets); @@ -492,7 +492,7 @@ namespace System.Data.Common [In] IntPtr pUnkOuter, [In] ref Guid rguidSchema, [In] int cRestrictions, - [In, MarshalAs(UnmanagedType.LPArray)] object[] rgRestrictions, + [In, MarshalAs(UnmanagedType.LPArray)] object?[] rgRestrictions, [In] ref Guid riid, [In] int cPropertySets, [In] IntPtr rgPropertySets, @@ -715,7 +715,7 @@ namespace System.Data.Common [PreserveSig] System.Data.OleDb.OleDbHResult GetProperties( [In] int cPropertyIDSets, - [In] SafeHandle rgPropertyIDSets, + [In] SafeHandle? rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertySets); @@ -811,7 +811,7 @@ namespace System.Data.Common IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI IntPtr pUnkOuter, ref Guid riid, - [MarshalAs(UnmanagedType.Interface)] ref object ppCommand); + [MarshalAs(UnmanagedType.Interface)] ref object? ppCommand); // // Advapi32.dll Integrated security functions @@ -840,7 +840,7 @@ namespace System.Data.Common [DllImport(Interop.Libraries.Advapi32, EntryPoint = "CreateWellKnownSid", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int CreateWellKnownSid( int sidType, - byte[] domainSid, + byte[]? domainSid, [Out] byte[] resultSid, ref uint resultSidLength); } -- 2.7.4