[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);
[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)]
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,
[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,
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
// 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;
{
// 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<bool> _trueTask;
- internal static Task<bool> TrueTask => _trueTask ?? (_trueTask = Task.FromResult(true));
+ private static Task<bool>? _trueTask;
+ internal static Task<bool> TrueTask => _trueTask ??= Task.FromResult(true);
- private static Task<bool> _falseTask;
- internal static Task<bool> FalseTask => _falseTask ?? (_falseTask = Task.FromResult(false));
+ private static Task<bool>? _falseTask;
+ internal static Task<bool> FalseTask => _falseTask ??= Task.FromResult(false);
internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
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);
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);
// 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;
// is the prefix present?
if (prefixLength > 0)
{
- if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal))
+ if (!quotedString.StartsWith(quotePrefix!, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
// is the suffix present?
if (suffixLength > 0)
{
- if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal))
+ if (!quotedString.EndsWith(quoteSuffix!, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
return e;
}
- internal static void CheckArgumentNull(object value, string parameterName)
+ internal static void CheckArgumentNull([NotNull] object? value, string parameterName)
{
if (null == value)
{
{
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);
}
{
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);
}
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);
}
internal class BasicFieldNameLookup
{
// Dictionary stores the index into the _fieldNames, match via case-sensitive
- private Dictionary<string, int> _fieldNameLookup;
+ private Dictionary<string, int>? _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)
{
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)
}
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);
{
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;
}
}
// 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;
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)
{
// 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;
}
return new DbConnectionPoolKey(this);
}
- internal virtual string ConnectionString
+ internal virtual string? ConnectionString
{
get
{
//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);
// 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;
// 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
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<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
=> base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions);
}
{
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
=> throw ADP.ConnectionAlreadyOpen(State);
}
connectionFactory.SetInnerConnectionTo(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
- internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
=> TryOpenConnection(outerConnection, connectionFactory, retry, userOptions);
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
if (retry == null || !retry.Task.IsCompleted)
{
{
}
- internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
=> TryOpenConnection(outerConnection, connectionFactory, retry, userOptions);
}
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Common;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
// 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<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
- private static Task<DbConnectionInternal> s_completedTask;
+ private static readonly Task<DbConnectionInternal?>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal?>[Environment.ProcessorCount];
+ private static Task<DbConnectionInternal?>? s_completedTask;
protected DbConnectionFactory()
{
{
ADP.CheckArgumentNull(connection, nameof(connection));
- DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection);
+ DbConnectionPoolGroup? poolGroup = GetConnectionPoolGroup(connection);
if (null != poolGroup)
{
poolGroup.Clear();
Debug.Assert(key != null, "key cannot be null");
ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString));
- DbConnectionPoolGroup poolGroup;
+ DbConnectionPoolGroup? poolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out poolGroup))
{
}
}
- 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);
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);
return newConnection;
}
- internal virtual DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
+ internal virtual DbConnectionPoolGroupProviderInfo? CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
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<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
return null;
}
- private static Task<DbConnectionInternal> GetCompletedTask()
+ private static Task<DbConnectionInternal?> GetCompletedTask()
{
Debug.Assert(Monitor.IsEntered(s_pendingOpenNonPooled), $"Expected {nameof(s_pendingOpenNonPooled)} lock to be held.");
- return s_completedTask ?? (s_completedTask = Task.FromResult<DbConnectionInternal>(null));
+ return s_completedTask ?? (s_completedTask = Task.FromResult<DbConnectionInternal?>(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
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<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
{
// 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);
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
}
- 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
}
}
- 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);
}
// 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
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);
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.
}
- 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
{
}
}
- protected internal DbReferenceCollection ReferenceCollection
+ protected internal DbReferenceCollection? ReferenceCollection
{
get
{
// 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
}
internal void DeactivateConnection()
{
+ Debug.Assert(Pool != null);
+
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
_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.");
internal void NotifyWeakReference(int message)
{
- DbReferenceCollection referenceCollection = ReferenceCollection;
+ DbReferenceCollection? referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Notify(message);
/// override this and do the correct thing.</devdoc>
// 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<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
throw ADP.ConnectionAlreadyOpen(State);
}
- internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
throw ADP.MethodNotImplemented();
}
- protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? 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);
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.
internal void RemoveWeakReference(object value)
{
- DbReferenceCollection referenceCollection = ReferenceCollection;
+ DbReferenceCollection? referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Remove(value);
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;
internal DbConnectionPoolKey PoolKey => _poolKey;
- internal DbConnectionPoolGroupProviderInfo ProviderInfo
+ internal DbConnectionPoolGroupProviderInfo? ProviderInfo
{
get
{
_providerInfo = value;
if (null != value)
{
- _providerInfo.PoolGroup = this;
+ _providerInfo!.PoolGroup = this;
}
}
}
internal DbConnectionPoolGroupOptions PoolGroupOptions => _poolGroupOptions;
- internal DbMetaDataFactory MetaDataFactory
+ internal DbMetaDataFactory? MetaDataFactory
{
get
{
// 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<DbConnectionPoolIdentity, DbConnectionPool> oldPoolCollection = null;
+ ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>? oldPoolCollection = null;
lock (this)
{
if (_poolCollection.Count > 0)
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.
// 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)
{
// 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())
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;
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))
{
{
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))
{
command.Parameters.Add(restrictionParameter);
}
- DbDataReader reader = null;
+ DbDataReader? reader = null;
try
{
try
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)
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;
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))
{
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)
throw ADP.MissingRestrictionColumn();
}
- foreach (DataRow restriction in restrictionsTable.Rows)
+ foreach (DataRow restriction in restrictionsTable!.Rows)
{
if (((string)restriction[collectionName] == neededCollectionName) &&
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
}
}
- string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string;
+ string populationMechanism = (requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string)!;
switch (populationMechanism)
{
-
case _dataTable:
if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections)
{
return requestedSchema;
}
- private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames)
+ private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames)
{
bool result = true;
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();
}
{
bool result = true;
DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns;
- DataColumn versionColumn;
+ DataColumn? versionColumn;
object version;
// check the minimum version first
//------------------------------------------------------------------------------
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Data.ProviderBase
}
}
- public object Target
+ public object? Target
{
get
{
}
}
+ [return: MaybeNull]
internal T FindItem<T>(int tag, Func<T, bool> filterMethod) where T : class
{
bool lockObtained = false;
{
// 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;
}
{
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);
<Import Project="..\..\Directory.Build.targets" />
<PropertyGroup>
- <NoWarn Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework' or '$(TargetFrameworkIdentifier)' == '.NETStandard' or '$(TargetFramework)' == 'netcoreapp2.1'">$(NoWarn);nullable</NoWarn>
+ <NoWarn Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework' or '$(TargetFrameworkIdentifier)' == '.NETStandard' or ('$(TargetFrameworkIdentifier)' == '.NETCoreApp' and $([MSBuild]::VersionLessThan($(TargetFrameworkVersion), '3.0')))">$(NoWarn);nullable</NoWarn>
<NoWarn Condition="'$(GeneratePlatformNotSupportedAssembly)' == 'true' or '$(GeneratePlatformNotSupportedAssemblyMessage)' != ''">$(NoWarn);nullable</NoWarn>
<!-- Ignore Obsolete errors within the generated shims that type-forward types.
SYSLIB0003 is for CAS. SYSLIB0004 is the obsoletion of CER. -->
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; }
}
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; } }
}
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 { } }
{
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);
}
_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();
}
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;
}
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);
}
// 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
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;
}
// 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
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
{
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))
public class RowUpdatedEventArgs : EventArgs
{
- private readonly IDbCommand _command;
+ private readonly IDbCommand? _command;
private StatementType _statementType;
private readonly DataTableMapping _tableMapping;
private Exception? _errors;
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)
{
_tableMapping = tableMapping;
}
- public IDbCommand Command
+ public IDbCommand? Command
{
get
{
}
// 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);
}
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];
{
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;
}
}
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)
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);
{
for (int i = 0; i < value.Length; i++)
{
- if (value[i] is { } v)
+ if (value[i] is object v)
{
_columnCollection[i][record] = v;
}
for (int i = 0; i < mapped.Length; ++i)
{
- if (mapped[i] is { } m)
+ if (mapped[i] is object m)
{
dataRow[i] = m;
}
_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);
{
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));
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Data.DataSetExtensions.Forwards.cs" />
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
<IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
</PropertyGroup>
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)]
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() { }
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; }
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; }
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 { } }
[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; }
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; }
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; }
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; }
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; }
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; }
}
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) { }
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. -->
<PropertyGroup>
<ItemGroup>
<Compile Include="System.Data.Odbc.cs" />
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
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);
}
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);
{
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);
}
return OpenReaderExists(null);
}
- internal static Exception OpenReaderExists(Exception e)
+ internal static Exception OpenReaderExists(Exception? e)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
}
//
// : ConnectionUtil
//
- internal static Exception ConnectionIsDisabled(Exception InnerException)
+ internal static Exception ConnectionIsDisabled(Exception? InnerException)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionIsDisabled), InnerException);
}
}
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)
{
}
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)
{
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));
}
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)
{
return Path.GetFullPath(filename);
}
- internal static int StringLength(string inputString)
+ internal static int StringLength(string? inputString)
{
return ((null != inputString) ? inputString.Length : 0);
}
private readonly string _encryptedUsersConnectionString;
// hash of unique keys to values
- private readonly Dictionary<string, string> _parsetable;
+ private readonly Dictionary<string, string?> _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;
#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
}
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<string, string> synonyms, bool mustCloneDictionary)
+ private DBConnectionString(DbConnectionOptions connectionOptions, string? restrictions, KeyRestrictionBehavior behavior, Dictionary<string, string>? synonyms, bool mustCloneDictionary)
{ // used by DBDataPermission
Debug.Assert(null != connectionOptions, "null connectionOptions");
switch (behavior)
{
// 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<string, string>(_parsetable);
+ _parsetable = new Dictionary<string, string?>(_parsetable);
}
// different than Everett in that instead of removing password/pwd from
}
}
- 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;
get { return (null == _keychain); }
}
- internal NameValuePair KeyChain
+ internal NameValuePair? KeyChain
{
get { return _keychain; }
}
{
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();
}
}
- internal string this[string keyword]
+ internal string? this[string keyword]
{
- get { return (string)_parsetable[keyword]; }
+ get { return _parsetable[keyword]; }
}
internal bool ContainsKey(string keyword)
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)
{
}
[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))
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))
{
return true;
}
- private static string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage)
+ private static string[]? NewRestrictionAllowOnly(string[] allowonly, string[] preventusage)
{
- List<string> newlist = null;
+ List<string>? newlist = null;
for (int i = 0; i < allowonly.Length; ++i)
{
if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal))
newlist.Add(allowonly[i]);
}
}
- string[] restrictionValues = null;
+ string[]? restrictionValues = null;
if (null != newlist)
{
restrictionValues = newlist.ToArray();
return restrictionValues;
}
- private static string[] NewRestrictionIntersect(string[] a, string[] b)
+ private static string[]? NewRestrictionIntersect(string[] a, string[] b)
{
- List<string> newlist = null;
+ List<string>? newlist = null;
for (int i = 0; i < a.Length; ++i)
{
if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal))
newlist.Add(a[i]);
}
}
- string[] restrictionValues = null;
+ string[]? restrictionValues = null;
if (newlist != null)
{
restrictionValues = newlist.ToArray();
return restrictionValues;
}
- private static string[] ParseRestrictions(string restrictions, Dictionary<string, string> synonyms)
+ private static string[]? ParseRestrictions(string restrictions, Dictionary<string, string>? synonyms)
{
List<string> restrictionValues = new List<string>();
StringBuilder buffer = new StringBuilder(restrictions.Length);
{
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))
{
return RemoveDuplicates(restrictionValues.ToArray());
}
- internal static string[] RemoveDuplicates(string[] restrictions)
+ internal static string[] RemoveDuplicates(string?[] restrictions)
{
int count = restrictions.Length;
if (0 < count)
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--;
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)
{
// synonyms hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
- public DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms, bool useOdbcRules)
+ public DbConnectionOptions(string connectionString, Dictionary<string, string>? synonyms, bool useOdbcRules)
{
_useOdbcRules = useOdbcRules;
- _parsetable = new Dictionary<string, string>();
+ _parsetable = new Dictionary<string, string?>();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
{
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;
get { return (null == _keyChain); }
}
- internal Dictionary<string, string> Parsetable
+ internal Dictionary<string, string?> Parsetable
{
get { return _parsetable; }
}
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));
// 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;
public int ConvertValueToInt32(string keyName, int defaultValue)
{
- object value = _parsetable[keyName];
+ object? value = _parsetable[keyName];
if (null == value)
{
return defaultValue;
public string ConvertValueToString(string keyName, string defaultValue)
{
- string value = (string)_parsetable[keyName];
+ string? value = _parsetable[keyName];
return ((null != value) ? value : defaultValue);
}
// * 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))
{
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;
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]))
{
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"))
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"))
// 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;
_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])
}
}
- 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)
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)
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)
}
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");
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;
}
}
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);
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
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
// 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
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)
Validate(offset, 2);
Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
- string value = null;
+ string? value = null;
bool mustRelease = false;
try
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
value = Marshal.PtrToStringUni(ptr);
- Validate(offset, (2 * (value.Length + 1)));
+ Validate(offset, (2 * (value!.Length + 1)));
}
finally
{
Validate(offset, 2 * length);
Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
- string value = null;
+ string? value = null;
bool mustRelease = false;
try
{
internal abstract partial class DbConnectionFactory
{
- internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
+ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal>? 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
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)
// 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)
{
// 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);
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)
}
else if (task.IsFaulted)
{
- retry.TrySetException(task.Exception.InnerException);
+ retry.TrySetException(task.Exception!.InnerException!);
}
else
{
// 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
private sealed class PendingGetConnection
{
- public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions)
+ public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions? userOptions)
{
DueTime = dueTime;
Owner = owner;
public long DueTime { get; private set; }
public DbConnection Owner { get; private set; }
public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; }
- public DbConnectionOptions UserOptions { get; private set; }
+ public DbConnectionOptions? UserOptions { get; private set; }
}
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;
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<DbConnectionInternal> _objectList;
DbConnectionFactory connectionFactory,
DbConnectionPoolGroup connectionPoolGroup,
DbConnectionPoolIdentity identity,
- DbConnectionPoolProviderInfo connectionPoolProviderInfo)
+ DbConnectionPoolProviderInfo? connectionPoolProviderInfo)
{
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup");
}
}
- internal DbConnectionPoolIdentity Identity
+ internal DbConnectionPoolIdentity? Identity
{
get { return _identity; }
}
get { return _connectionPoolGroupOptions; }
}
- internal DbConnectionPoolProviderInfo ProviderInfo
+ internal DbConnectionPoolProviderInfo? ProviderInfo
{
get { return _connectionPoolProviderInfo; }
}
get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); }
}
- private void CleanupCallback(object state)
+ private void CleanupCallback(object? state)
{
// Called when the cleanup-timer ticks over.
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
// We obtained a objects from the semaphore.
- DbConnectionInternal obj;
+ DbConnectionInternal? obj;
if (_stackOld.TryPop(out obj))
{
{
while (true)
{
- DbConnectionInternal obj;
+ DbConnectionInternal? obj;
if (!_stackNew.TryPop(out obj))
break;
internal void Clear()
{
- DbConnectionInternal obj;
+ DbConnectionInternal? obj;
// First, quickly doom everything.
lock (_objectList)
_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
{
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)
{
// 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
{
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
{
} while (!_pendingOpens.IsEmpty);
}
- internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
+ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions, out DbConnectionInternal? connection)
{
uint waitForMultipleObjectsTimeout = 0;
bool allowCreate = false;
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);
case ERROR_HANDLE:
// Throw the error that PoolCreateRequest stashed.
Interlocked.Decrement(ref _waitCount);
- throw TryCloneCachedException();
+ throw TryCloneCachedException()!;
case CREATION_HANDLE:
/// <param name="userOptions">Options used to create the new connection</param>
/// <param name="oldConnection">Inner connection that will be replaced</param>
/// <returns>A new inner connection that is attached to the <paramref name="owningObject"/></returns>
- 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)
{
return newConnection;
}
- private DbConnectionInternal GetFromGeneralPool()
+ private DbConnectionInternal? GetFromGeneralPool()
{
- DbConnectionInternal obj = null;
+ DbConnectionInternal? obj = null;
if (!_stackNew.TryPop(out obj))
{
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
// 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;
}
_state = State.ShuttingDown;
// deactivate timer callbacks
- Timer t = _cleanupTimer;
+ Timer? t = _cleanupTimer;
_cleanupTimer = null;
if (null != t)
{
}
- 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
{
{
internal class DbConnectionPoolGroupProviderInfo
{
- private DbConnectionPoolGroup _poolGroup;
+ private DbConnectionPoolGroup? _poolGroup;
- internal DbConnectionPoolGroup PoolGroup
+ internal DbConnectionPoolGroup? PoolGroup
{
get
{
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))
<TargetFrameworks>$(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</TargetFrameworks>
<ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
<NoWarn>$(NoWarn);CA2249</NoWarn>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. -->
<PropertyGroup>
{
}
- internal string _name;
- internal string _typename;
- internal Type _type;
+ internal string? _name;
+ internal string? _typename;
+ internal Type? _type;
internal ODBC32.SQL_TYPE? _dbtype;
}
// 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))
//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;
}
//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];
_isBadValue[i] = true;
}
- internal object[] Values
+ internal object?[] Values
{
get
{
}
}
- 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
// ....
// return cache[i];
- object[] values = this.Values;
+ object?[] values = this.Values;
if (_randomaccess)
{
//Random
{
_schema = new DbSchemaInfo[Count];
}
- if (_schema[i] == null)
- {
- _schema[i] = new DbSchemaInfo();
- }
- return _schema[i];
+
+ return _schema[i] ??= new DbSchemaInfo();
}
internal void FlushValues()
{
}
- internal static short ShortStringLength(string inputString)
+ internal static short ShortStringLength(string? inputString)
{
return checked((short)ADP.StringLength(inputString));
}
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)
using System.ComponentModel; //Component
using System.Data.Common;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
// todo:
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;
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;
{
if (null != _weakDataReaderReference)
{
- IDisposable reader = (IDisposable)_weakDataReaderReference.Target;
+ IDisposable? reader = (IDisposable?)_weakDataReaderReference.Target;
if ((null != reader) && _weakDataReaderReference.IsAlive)
{
((IDisposable)reader).Dispose();
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;
{
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
}
}
- public new OdbcConnection Connection
+ public new OdbcConnection? Connection
{
get
{
}
}
- protected override DbConnection DbConnection
+ protected override DbConnection? DbConnection
{ // V1.2.3300
get
{
}
set
{
- Connection = (OdbcConnection)value;
+ Connection = (OdbcConnection?)value;
}
}
}
}
- protected override DbTransaction DbTransaction
+ protected override DbTransaction? DbTransaction
{ // V1.2.3300
get
{
}
set
{
- Transaction = (OdbcTransaction)value;
+ Transaction = (OdbcTransaction?)value;
}
}
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
- public new OdbcTransaction Transaction
+ public new OdbcTransaction? Transaction
{
get
{
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
- return _cmdWrapper.GetDescriptorHandle(attribute);
+ return _cmdWrapper!.GetDescriptorHandle(attribute);
}
//
if (_cmdWrapper == null)
{
- _cmdWrapper = new CMDWrapper(_connection);
+ _cmdWrapper = new CMDWrapper(_connection!);
Debug.Assert(null != _connection, "GetStatementHandle without connection?");
_connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag);
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)
// don't fire info message events on cancel
break;
default:
- throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode);
+ throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode)!;
}
}
}
private void CloseCommandWrapper()
{
- CMDWrapper wrapper = _cmdWrapper;
+ CMDWrapper? wrapper = _cmdWrapper;
if (null != wrapper)
{
try
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);
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
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)
//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,
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
{
else
{
// any other returncode indicates an error
- _connection.HandleError(stmt, retcode);
+ _connection!.HandleError(stmt, retcode);
}
}
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:
//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
}
{
if (mustRelease)
{
- parameterBuffer.DangerousRelease();
+ parameterBuffer!.DangerousRelease();
}
}
}
}
}
- 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))
internal string GetDiagSqlState()
{
- return _cmdWrapper.GetDiagSqlState();
+ return _cmdWrapper!.GetDiagSqlState();
}
private void PropertyChanging()
ValidateOpenConnection(ADP.Prepare);
- if (0 != (ConnectionState.Fetching & _connection.InternalState))
+ if (0 != (ConnectionState.Fetching & _connection!.InternalState))
{
throw ADP.OpenReaderExists();
}
DisposeDeadDataReader();
GetStatementHandle();
- OdbcStatementHandle stmt = _cmdWrapper.StatementHandle;
+ OdbcStatementHandle stmt = _cmdWrapper!.StatementHandle!;
retcode = stmt.Prepare(CommandText);
if ((sqlState == "HYC00") || (sqlState == "HY092"))
{
- Connection.FlagUnsupportedStmtAttr(stmtAttribute);
+ Connection!.FlagUnsupportedStmtAttr(stmtAttribute);
}
else
{
private void ValidateOpenConnection(string methodName)
{
// see if we have a connection
- OdbcConnection connection = Connection;
+ OdbcConnection? connection = Connection;
if (null == connection)
{
}
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
}
}
- internal OdbcStatementHandle StatementHandle
+ internal OdbcStatementHandle? StatementHandle
{
get { return _stmt; }
}
- internal OdbcStatementHandle KeyInfoStatement
+ internal OdbcStatementHandle? KeyInfoStatement
{
get
{
}
DisposeStatementHandle();
- CNativeBuffer buffer = _nativeParameterBuffer;
+ CNativeBuffer? buffer = _nativeParameterBuffer;
_nativeParameterBuffer = null;
if (null != buffer)
{
private void DisposeDescriptorHandle()
{
- OdbcDescriptorHandle handle = _hdesc;
+ OdbcDescriptorHandle? handle = _hdesc;
if (null != handle)
{
_hdesc = null;
DisposeKeyInfoStatementHandle();
DisposeDescriptorHandle();
- OdbcStatementHandle handle = _stmt;
+ OdbcStatementHandle? handle = _stmt;
if (null != handle)
{
_stmt = null;
internal void DisposeKeyInfoStatementHandle()
{
- OdbcStatementHandle handle = _keyinfostmt;
+ OdbcStatementHandle? handle = _keyinfostmt;
if (null != handle)
{
_keyinfostmt = null;
{
DisposeDescriptorHandle();
- OdbcStatementHandle handle = _stmt;
+ OdbcStatementHandle? handle = _stmt;
if (null != handle)
{
try
internal void FreeKeyInfoStatementHandle(ODBC32.STMT stmt)
{
- OdbcStatementHandle handle = _keyinfostmt;
+ OdbcStatementHandle? handle = _keyinfostmt;
if (null != handle)
{
try
//
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;
}
internal string GetDiagSqlState()
{
string sqlstate;
- _stmt.GetDiagnosticField(out sqlstate);
+ _stmt!.GetDiagnosticField(out sqlstate);
return sqlstate;
}
{
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)!;
}
}
GC.SuppressFinalize(this);
}
- public OdbcCommandBuilder(OdbcDataAdapter adapter) : this()
+ public OdbcCommandBuilder(OdbcDataAdapter? adapter) : this()
{
DataAdapter = adapter;
}
- public new OdbcDataAdapter DataAdapter
+ public new OdbcDataAdapter? DataAdapter
{
get
{
throw ADP.CommandTextRequired(ADP.DeriveParameters);
}
- OdbcConnection connection = command.Connection;
+ OdbcConnection? connection = command.Connection;
if (null == connection)
{
// 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
// 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;
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));
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;
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
{
unquotedIdentifier = quotedIdentifier;
}
- return unquotedIdentifier;
+ return unquotedIdentifier!;
}
}
}
{
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;
}
_connectionTimeout = connection._connectionTimeout;
}
- internal OdbcConnectionHandle ConnectionHandle
+ internal OdbcConnectionHandle? ConnectionHandle
{
get
{
}
}
+ [AllowNull]
public override string ConnectionString
{
get
// 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;
}
get
{
Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo");
- return (OdbcConnectionPoolGroupProviderInfo)this.PoolGroup.ProviderInfo;
+ return (OdbcConnectionPoolGroupProviderInfo)this.PoolGroup.ProviderInfo!;
}
}
}
}
- 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;
}
{
if (ProviderInfo.DriverName == null)
{
- ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME);
+ ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME)!;
}
return ProviderInfo.DriverName;
}
}
}
- public event OdbcInfoMessageEventHandler InfoMessage
+ public event OdbcInfoMessageEventHandler? InfoMessage
{
add
{
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];
}
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";
}
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);
}
}
return clone;
}
- internal bool ConnectionIsAlive(Exception innerException)
+ internal bool ConnectionIsAlive(Exception? innerException)
{
if (IsOpen)
{
{
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();
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);
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);
private string GetDiagSqlState()
{
- OdbcConnectionHandle connectionHandle = ConnectionHandle;
+ OdbcConnectionHandle connectionHandle = ConnectionHandle!;
string sqlstate;
connectionHandle.GetDiagnosticField(out sqlstate);
return sqlstate;
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;
}
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;
}
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);
}
else if (handleError)
{
- this.HandleError(ConnectionHandle, retcode);
+ this.HandleError(connectionHandle, retcode);
}
}
else if (handleError)
}
// 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");
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:
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)
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);
};
//Start the transaction
- OdbcConnectionHandle connectionHandle = ConnectionHandle;
+ OdbcConnectionHandle connectionHandle = ConnectionHandle!;
ODBC32.RetCode retcode = connectionHandle.BeginTransaction(ref isolevel);
if (retcode == ODBC32.RetCode.ERROR)
{
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)
}
}
- internal string Open_GetServerVersion()
+ internal string? Open_GetServerVersion()
{
//SQLGetInfo - SQL_DBMS_VER
return GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER, true);
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
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.
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,
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;
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;
internal override void PermissionDemand(DbConnection outerConnection)
{
- OdbcConnection c = (outerConnection as OdbcConnection);
+ OdbcConnection? c = (outerConnection as OdbcConnection);
if (null != c)
{
c.PermissionDemand();
internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup)
{
- OdbcConnection c = (outerConnection as OdbcConnection);
+ OdbcConnection? c = (outerConnection as OdbcConnection);
if (null != c)
{
c.PoolGroup = poolGroup;
internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to)
{
- OdbcConnection c = (owningObject as OdbcConnection);
+ OdbcConnection? c = (owningObject as OdbcConnection);
if (null != c)
{
c.SetInnerConnectionEvent(to);
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);
internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to)
{
- OdbcConnection c = (owningObject as OdbcConnection);
+ OdbcConnection? c = (owningObject as OdbcConnection);
if (null != c)
{
c.SetInnerConnectionTo(to);
{
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;
}
}
- 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);
}
}
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);
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)
}
}
- internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup
+ internal System.Data.ProviderBase.DbConnectionPoolGroup? PoolGroup
{
get
{
}
- internal DbConnectionOptions UserConnectionOptions
+ internal DbConnectionOptions? UserConnectionOptions
{
get
{
protected override DbCommand CreateDbCommand()
{
- DbCommand command = null;
DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory;
- command = providerFactory.CreateCommand();
+ DbCommand command = providerFactory.CreateCommand()!;
command.Connection = this;
return command;
}
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)
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");
}
{
get
{
- OdbcConnection outerConnection = (OdbcConnection)Owner;
+ OdbcConnection? outerConnection = (OdbcConnection?)Owner;
if (null == outerConnection)
throw ODBC.OpenConnectionNoOwner();
{
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()!;
}
}
// 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;
// flags for unsupported Functions
private bool _noSqlPrimaryKeys;
- internal string DriverName
+ internal string? DriverName
{
get
{
}
}
- internal string DriverVersion
+ internal string? DriverVersion
{
get
{
{
get
{
+ Debug.Assert(_quoteChar != null, "QuoteChar getter called but no quote char was set");
return _quoteChar;
}
set
// 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);
}
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
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))
{
}
}
+ [AllowNull]
public override object this[string keyword]
{
get
{
get
{
- string[] knownKeywords = _knownKeywords;
+ string[]? knownKeywords = _knownKeywords;
if (null == knownKeywords)
{
knownKeywords = s_validKeywords;
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;
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);
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
{
}
}
- 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);
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);
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);
{
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,
// 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)
{
{
get
{
- CNativeBuffer value = _cmdWrapper._dataReaderBuf;
+ CNativeBuffer? value = _cmdWrapper!._dataReaderBuf;
if (null == value)
{
Debug.Fail("object is disposed");
}
}
- private OdbcConnection Connection
+ private OdbcConnection? Connection
{
get
{
}
}
- internal OdbcCommand Command
+ internal OdbcCommand? Command
{
get
{
{
get
{
- return _cmdWrapper.StatementHandle;
+ return _cmdWrapper!.StatementHandle!;
}
}
private OdbcStatementHandle KeyInfoStatementHandle
{
- get { return _cmdWrapper.KeyInfoStatement; }
+ get { return _cmdWrapper!.KeyInfoStatement!; }
}
internal bool IsBehavior(CommandBehavior behavior)
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);
{
// 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++)
{
private void Close(bool disposing)
{
- Exception error = null;
+ Exception? error = null;
- CMDWrapper wrapper = _cmdWrapper;
+ CMDWrapper? wrapper = _cmdWrapper;
if (null != wrapper && wrapper.StatementHandle != null)
{
// disposing
{
// 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();
{
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();
}
//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);
return GetValue(i, TypeMap.FromSqlType(subtype));
}
}
- return _dataCache[i];
+ return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
{
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();
}
//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));
{
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.
// 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
{
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();
}
{
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();
}
{
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();
}
{
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();
}
{
if (_isRead)
{
- if (_dataCache.AccessIndex(i) == null)
+ if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.WCHAR))
{
_dataCache[i] = long.Parse(value, CultureInfo.InvariantCulture);
}
}
- return _dataCache[i];
+ return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
{
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();
}
{
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();
}
{
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();
}
{
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();
}
{
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);
}
}
}
- return _dataCache[i];
+ return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
{
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();
}
{
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();
}
{
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
_dataCache[i] = builder.ToString();
}
}
- return _dataCache[i];
+ return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
{
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();
}
}
}
- 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)
{
// 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);
// 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");
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).
_dataCache[i] = rgBytes;
}
}
- return _dataCache[i];
+ return _dataCache[i]!;
}
// GetColAttribute
ODBC32.RetCode retcode;
// protect against dead connection, dead or canceling command.
- if ((Connection == null) || _cmdWrapper.Canceling)
+ if ((Connection == null) || _cmdWrapper!.Canceling)
{
return -1;
}
{
if (retcode == ODBC32.RetCode.ERROR)
{
- if ("HY091" == Command.GetDiagSqlState())
+ if ("HY091" == Command!.GetDiagSqlState())
{
Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId);
}
// 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;
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 "";
}
{
if (retcode == ODBC32.RetCode.ERROR)
{
- if ("HY091" == Command.GetDiagSqlState())
+ if ("HY091" == Command!.GetDiagSqlState())
{
Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId);
}
// 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 "";
}
{
if (retcode == ODBC32.RetCode.ERROR)
{
- if ("HY091" == Command.GetDiagSqlState())
+ if ("HY091" == Command!.GetDiagSqlState())
{
Connection.FlagUnsupportedColAttr(attribute, (ODBC32.SQL_COLUMN)0);
}
// 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)
break;
default:
- Connection.HandleError(StatementHandle, retcode);
+ Connection!.HandleError(StatementHandle, retcode);
break;
}
// 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;
switch (retcode)
{
case ODBC32.RetCode.SUCCESS_WITH_INFO:
- Connection.HandleErrorNoThrow(StatementHandle, retcode);
+ Connection!.HandleErrorNoThrow(StatementHandle, retcode);
_hasRows = HasRowsStatus.HasRows;
_isRead = true;
break;
}
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))
_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;
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))
{
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;
{
int count = FieldCount;
MetaData[] metaInfos = new MetaData[count];
- List<string> qrytables;
+ List<string>? qrytables;
bool needkeyinfo = IsCommandBehavior(CommandBehavior.KeyInfo);
bool isKeyColumn;
bool isHidden;
// 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)
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);
}
}
// 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++)
{
}
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)
{
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)
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
internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTableName, bool quoted)
{
+ Debug.Assert(_metadata != null);
+
ODBC32.RetCode retcode;
string columnname;
int ordinal;
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))
{
}
else
{
- if ("IM001" == Command.GetDiagSqlState())
+ if ("IM001" == Command!.GetDiagSqlState())
{
Connection.ProviderInfo.NoSqlPrimaryKeys = true;
}
}
// 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))
{
// 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;
// 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);
}
}
// Unbind the columns
- _cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.UNBIND);
+ _cmdWrapper!.FreeKeyInfoStatementHandle(ODBC32.STMT.UNBIND);
}
finally
{
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))
{
// we can't handle multiple tablenames (JOIN)
// only the first tablename will be returned
- internal string GetTableNameFromCommandText()
+ internal string? GetTableNameFromCommandText()
{
if (_command == null)
{
}
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)
{
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;
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
{
}
}
- internal string Schema
+ internal string? Schema
{
get
{
}
}
- internal string Table
+ internal string? Table
{
get
{
_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);
}
{
_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))
{
// 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
//
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);
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)
private sealed class MetaData
{
internal int ordinal;
- internal TypeMap typemap;
+ internal TypeMap typemap = null!; // Lazy-initialized
internal SQLLEN size;
internal byte precision;
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;
}
}
}
{
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)
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
}
}
}
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;
{
get
{
- return (OdbcError)_items[i];
+ return (OdbcError)_items[i]!;
}
}
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;
}
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;
else
{
// without a handle, ReleaseHandle may not be called
- parentHandle.DangerousRelease();
+ parentHandle!.DangerousRelease();
}
break;
}
// 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)
{
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);
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
// 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)
{
// 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);
}
}
private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcDataReader dataReader, OdbcConnection connection)
{
- DataTable schemaTable = null;
+ DataTable? schemaTable = null;
//
// Build a DataTable from the reader
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;
const int SQL_DATE_V2 = 9;
const int SQL_TIME_V2 = 10;
- TypeMap typeMap;
+ TypeMap? typeMap;
while (dataReader.Read())
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)
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;
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);
}
- 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
}
- private DataTable GetDataSourceInformationCollection(string[] restrictions,
+ private DataTable GetDataSourceInformationCollection(string?[]? restrictions,
OdbcConnection connection)
{
if (ADP.IsEmptyArray(restrictions) == false)
}
// 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);
}
DataRow dataSourceInformation = dataSourceInformationTable.Rows[0];
- string stringValue;
+ string? stringValue;
short int16Value;
int int32Value;
ODBC32.RetCode retcode;
}
// 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)
// 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)
{
}
- private DataTable GetDataTypesCollection(string[] restrictions, OdbcConnection connection)
+ private DataTable GetDataTypesCollection(string?[]? restrictions, OdbcConnection connection)
{
if (ADP.IsEmptyArray(restrictions) == false)
{
// 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);
// 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;
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;
dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLSTATISTICS);
- string indexName = null;
+ string? indexName = null;
if (restrictions != null)
{
if (restrictions.Length >= indexOfIndexName + 1)
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
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);
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;
return resultTable;
}
- private DataTable GetReservedWordsCollection(string[] restrictions, OdbcConnection connection)
+ private DataTable GetReservedWordsCollection(string?[]? restrictions, OdbcConnection connection)
{
if (ADP.IsEmptyArray(restrictions) == false)
{
}
// 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);
// 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)
{
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";
}
private bool IncludeIndexRow(object rowIndexName,
- string restrictionIndexName,
+ string? restrictionIndexName,
short rowIndexType)
{
// never include table statictics rows
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)
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;
// 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;
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;
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;
// 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;
[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;
}
[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;
{
if (_userSpecifiedType)
{
- return _typemap._dbType;
+ return _typemap!._dbType;
}
return TypeMap._NVarChar._dbType; // default type
}
{
if (_userSpecifiedType)
{
- return _typemap._odbcType;
+ return _typemap!._odbcType;
}
return TypeMap._NVarChar._odbcType; // default type
}
}
}
+ [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
}
// 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
}
// 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);
}
// 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
}
return ccb;
}
- private byte GetParameterPrecision(object value)
+ private byte GetParameterPrecision(object? value)
{
if (0 != _internalPrecision && value is decimal)
{
}
- private byte GetParameterScale(object value)
+ private byte GetParameterScale(object? value)
{
// For any value that is not decimal simply return the Scale
//
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;
// 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:
case ODBC32.SQL_TYPE.WLONGVARCHAR:
if (value is char)
{
- value = value.ToString();
+ value = value.ToString()!;
size = ((string)value).Length;
offset = 0;
}
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;
}
}
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);
if (!_hasChanged
&& (_boundSqlCType == sql_c_type)
- && (_boundParameterType == _bindtype._sql_type)
+ && (_boundParameterType == _bindtype!._sql_type)
&& (_boundSize == cchSize)
&& (_boundScale == scale)
&& (_boundBuffer == valueBuffer.Handle)
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
}
}
- 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);
}
}
- private object ProcessAndGetParameterValue()
+ private object? ProcessAndGetParameterValue()
{
- object value = _internalValue;
+ object? value = _internalValue;
if (_internalUserSpecifiedType)
{
if ((null != value) && !Convert.IsDBNull(value))
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)
{
//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))
{
}
}
- public override object Value
+ public override object? Value
{ // V1.2.3300, XXXParameter V1.0.3300
get
{
}
}
- 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);
}
[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));
}
{
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;
}
// 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);
{
public sealed partial class OdbcParameterCollection : DbParameterCollection
{
- private List<OdbcParameter> _items;
+ private List<OdbcParameter>? _items;
public override int Count
{
{
get
{
- List<OdbcParameter> items = _items;
+ List<OdbcParameter>? items = _items;
if (null == items)
{
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)
// 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
{
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
{
return (0 != _size);
}
+ [AllowNull]
public override string SourceColumn
{
get
{
- string sourceColumn = _sourceColumn;
+ string? sourceColumn = _sourceColumn;
return ((null != sourceColumn) ? sourceColumn : string.Empty);
}
set
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;
return ParameterName;
}
- private byte ValuePrecisionCore(object value)
+ private byte ValuePrecisionCore(object? value)
{
if (value is decimal)
{
return 0;
}
- private byte ValueScaleCore(object value)
+ private byte ValueScaleCore(object? value)
{
if (value is decimal)
{
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;
}
/////////////////////////////////////////////////////////////////////////
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
}
}
- protected override IDbCommand BaseCommand
+ protected override IDbCommand? BaseCommand
{
get { return base.BaseCommand; }
set { base.BaseCommand = (value as OdbcCommand); }
/////////////////////////////////////////////////////////////////////////
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; }
}
}
}
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)
{
}
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
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,
return retcode;
}
- internal ODBC32.RetCode Statistics(string tableCatalog,
- string tableSchema,
+ internal ODBC32.RetCode Statistics(string? tableCatalog,
+ string? tableSchema,
string tableName,
short unique,
short accuracy)
{
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)
{
_handle = handle;
}
- public new OdbcConnection Connection
+ public new OdbcConnection? Connection
{ // MDAC 66655
get
{
}
}
- protected override DbConnection DbConnection
+ protected override DbConnection? DbConnection
{ // MDAC 66655
get
{
{
get
{
- OdbcConnection connection = _connection;
+ OdbcConnection? connection = _connection;
if (null == connection)
{
throw ADP.TransactionZombied(this);
public override void Commit()
{
- OdbcConnection connection = _connection;
+ OdbcConnection? connection = _connection;
if (null == connection)
{
throw ADP.TransactionZombied(this);
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();
{
if (disposing)
{
- OdbcConnectionHandle handle = _handle;
+ OdbcConnectionHandle? handle = _handle;
_handle = null;
if (null != handle)
{
//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);
}
}
public override void Rollback()
{
- OdbcConnection connection = _connection;
+ OdbcConnection? connection = _connection;
if (null == connection)
{
throw ADP.TransactionZombied(this);
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();
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)]
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() { }
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; }
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; }
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; } }
[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; }
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() { }
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")]
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; }
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; }
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);
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 { } }
[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; }
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; }
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
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; }
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<NoWarn>$(NoWarn);0618</NoWarn>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. -->
<PropertyGroup>
{
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.");
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<object, IntPtr> s_getIDispatchForObject;
+ private static Func<object, IntPtr>? s_getIDispatchForObject;
private readonly int _ordinal;
private readonly int _maxLen;
// 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");
private Type ExpectedType
{
- get { return NativeDBType.FromDBType(DbType, false, false).dataType; }
+ get { return NativeDBType.FromDBType(DbType, false, false).dataType!; }
}
internal int Index
{
_value = null;
- StringMemHandle sptr = _sptr;
+ StringMemHandle? sptr = _sptr;
_sptr = null;
if (null != sptr)
internal object Value()
{
- object value = _value;
- if (null == value)
+ object value;
+ if (null == _value)
{
switch (StatusValue())
{
}
_value = value;
}
- return value;
+ return _value!;
}
- internal void Value(object value)
+ internal void Value(object? value)
{
if (null == value)
{
{
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();
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()
// 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<object, IntPtr>)));
s_getIDispatchForObject = delegateInstance as Func<object, IntPtr>;
- ptr = s_getIDispatchForObject(value);
+ ptr = s_getIDispatchForObject!(value);
}
RowBinding.WriteIntPtr(ValueOffset, ptr);
}
internal byte[] ValueByteArray()
{
- byte[] value = (byte[])_value;
+ byte[]? value = (byte[]?)_value;
if (null == value)
{
switch (StatusValue())
internal OleDbDataReader ValueChapter()
{
- OleDbDataReader value = (OleDbDataReader)_value;
+ OleDbDataReader? value = (OleDbDataReader?)_value;
if (null == value)
{
switch (StatusValue())
internal string ValueString()
{
- string value = (string)_value;
+ string? value = (string?)_value;
if (null == value)
{
switch (StatusValue())
private object ValueVariant()
{
- object value = _value;
+ object? value = _value;
if (null == value)
{
value = Value_VARIANT();
{
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;
_ifIRowsetElseIRow = ifIRowsetElseIRow;
}
- internal tagDBPARAMBINDINFO[] BindInfo
+ internal tagDBPARAMBINDINFO[]? BindInfo
{
get { return _bindInfo; }
}
return _parameters;
}
- internal RowBinding RowBinding()
+ internal RowBinding? RowBinding()
{
//Debug.Assert(null != _rowBinding, "null RowBinding");
return _rowBinding;
//get { return _bindInfo[_index].pwszDataSourceType; }
set
{
- _bindInfo[_index].pwszDataSourceType = value;
+ _bindInfo![_index].pwszDataSourceType = value;
}
}
internal IntPtr Name
//get { return _bindInfo[_index].pwszName; }
set
{
- _bindInfo[_index].pwszName = value;
+ _bindInfo![_index].pwszName = value;
}
}
internal IntPtr ParamSize
}
set
{
- _bindInfo[_index].ulParamSize = value;
+ _bindInfo![_index].ulParamSize = value;
}
}
internal int Flags
//get { return _bindInfo[_index].dwFlag; }
set
{
- _bindInfo[_index].dwFlags = value;
+ _bindInfo![_index].dwFlags = value;
}
}
}
}
- 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");
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))
internal void CleanupBindings()
{
- RowBinding rowBinding = this.RowBinding();
+ RowBinding? rowBinding = this.RowBinding();
if (null != rowBinding)
{
rowBinding.ResetValues();
_dataReader = null;
_columnBindings = null;
- RowBinding rowBinding = _rowBinding;
+ RowBinding? rowBinding = _rowBinding;
_rowBinding = null;
if (null != rowBinding)
{
using System.Collections;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Versioning;
using System.Text;
private readonly string _usersConnectionString;
private readonly Hashtable _parsetable;
- internal readonly NameValuePair KeyChain;
+ internal readonly NameValuePair? KeyChain;
internal readonly bool HasPasswordKeyword;
internal readonly bool HasUserIdKeyword;
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();
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");
public bool ConvertValueToBoolean(string keyName, bool defaultValue)
{
- object value = _parsetable[keyName];
+ object? value = _parsetable[keyName];
if (null == value)
{
return defaultValue;
public int ConvertValueToInt32(string keyName, int defaultValue)
{
- object value = _parsetable[keyName];
+ object? value = _parsetable[keyName];
if (null == value)
{
return defaultValue;
}
}
- 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);
}
// * 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))
{
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;
}
[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)
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;
return currentPosition;
}
- private static bool IsValueValidInternal(string keyvalue)
+ private static bool IsValueValidInternal(string? keyvalue)
{
if (null != keyvalue)
{
return true;
}
- private static bool IsKeyNameValid(string keyname)
+ private static bool IsKeyNameValid([NotNullWhen(true)] string? keyname)
{
if (null != keyname)
{
}
#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);
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)
}
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);
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
{
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 + ">");
}
}
}
#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
{
{
int startPosition = nextStartPosition;
- string keyname, keyvalue;
+ string? keyname, keyvalue;
nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
if (ADP.IsEmpty(keyname))
{
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);
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))
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.Data.Common
}
}
- object System.Collections.IEnumerator.Current
+ object? System.Collections.IEnumerator.Current
{
get
{
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"))
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
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
{
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
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;
return ParameterName;
}
- private byte ValuePrecisionCore(object value)
+ private byte ValuePrecisionCore(object? value)
{ // V1.2.3300
if (value is decimal)
{
return 0;
}
- private byte ValueScaleCore(object value)
+ private byte ValueScaleCore(object? value)
{ // V1.2.3300
if (value is decimal)
{
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;
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)
{
}
}
- 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");
}
}
- 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");
}
}
- 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");
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
}
tagDBPROPSET propset = new tagDBPROPSET();
- ItagDBPROP[] properties = null;
+ ItagDBPROP[]? properties = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
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);
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;
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;
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;
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
{
}
set
{
- Bindings bindings = _dbBindings;
+ Bindings? bindings = _dbBindings;
_dbBindings = value;
if ((null != bindings) && (value != bindings))
{
[DefaultValue("")]
[RefreshProperties(RefreshProperties.All)]
+ [AllowNull]
public override string CommandText
{
get
{
- string value = _commandText;
+ string? value = _commandText;
return ((null != value) ? value : string.Empty);
}
set
}
[DefaultValue(null)]
- public new OleDbConnection Connection
+ public new OleDbConnection? Connection
{
get
{
}
set
{
- OleDbConnection connection = _connection;
+ OleDbConnection? connection = _connection;
if (value != connection)
{
PropertyChanging();
private void ResetConnection()
{
- OleDbConnection connection = _connection;
+ OleDbConnection? connection = _connection;
if (null != connection)
{
PropertyChanging();
_connection = null;
}
- protected override DbConnection DbConnection
+ protected override DbConnection? DbConnection
{ // V1.2.3300
get
{
}
set
{
- Connection = (OleDbConnection)value;
+ Connection = (OleDbConnection?)value;
}
}
}
}
- protected override DbTransaction DbTransaction
+ protected override DbTransaction? DbTransaction
{ // V1.2.3300
get
{
}
set
{
- Transaction = (OleDbTransaction)value;
+ Transaction = (OleDbTransaction?)value;
}
}
{
get
{
- OleDbParameterCollection value = _parameters;
+ OleDbParameterCollection? value = _parameters;
if (null == value)
{
// delay the creation of the OleDbParameterCollection
private bool HasParameters()
{
- OleDbParameterCollection value = _parameters;
+ OleDbParameterCollection? value = _parameters;
return (null != value) && (0 < value.Count);
}
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;
}
// 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;
}
// 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);
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);
unchecked
{ _changeID++; }
- UnsafeNativeMethods.ICommandText icmdtxt = _icommandText;
+ UnsafeNativeMethods.ICommandText? icmdtxt = _icommandText;
if (null != icmdtxt)
{
OleDbHResult hr = OleDbHResult.S_OK;
// 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)
{
this.commandBehavior = CommandBehavior.Default;
_isPrepared = false;
- UnsafeNativeMethods.ICommandText ict = Interlocked.Exchange<UnsafeNativeMethods.ICommandText>(ref _icommandText, null);
+ UnsafeNativeMethods.ICommandText? ict = Interlocked.Exchange(ref _icommandText, null);
if (null != ict)
{
lock (ict)
private void CloseInternalParameters()
{
Debug.Assert(null != _connection, "no connection, CloseInternalParameters");
- Bindings bindings = _dbBindings;
+ Bindings? bindings = _dbBindings;
_dbBindings = null;
if (null != bindings)
{
public new OleDbDataReader ExecuteReader(CommandBehavior behavior)
{
_executeQuery = true;
- return ExecuteReaderInternal(behavior, ADP.ExecuteReader);
+ return ExecuteReaderInternal(behavior, ADP.ExecuteReader)!;
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)
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
{
behavior |= CommandBehavior.SingleResult;
}
- object executeResult;
+ object? executeResult;
int resultType;
switch (CommandType)
{
try
{
- dataReader = new OleDbDataReader(_connection, this, 0, this.commandBehavior);
+ dataReader = new OleDbDataReader(_connection!, this, 0, this.commandBehavior);
switch (resultType)
{
{
PrepareCommandText(2);
}
- OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText, behavior);
+ OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText!, behavior);
break;
default:
Debug.Assert(false, "ExecuteReaderInternal: unknown result type");
}
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
{
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
return dataReader;
}
- private int ExecuteCommand(CommandBehavior behavior, out object executeResult)
+ private int ExecuteCommand(CommandBehavior behavior, out object? executeResult)
{
if (InitializeCommand(behavior, false))
{
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
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;
{
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)
{
// (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;
{
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)
{
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);
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;
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))
{
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();
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)
{
{
if (mustReleaseStringHandle)
{
- sptr.DangerousRelease();
+ sptr!.DangerousRelease();
}
}
ProcessResults(hr);
private void ParameterCleanup()
{
- Bindings bindings = ParameterBindings;
+ Bindings? bindings = ParameterBindings;
if (null != bindings)
{
bindings.CleanupBindings();
return false;
}
- if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters))
+ if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters!))
{
CloseInternalParameters();
}
string commandText = ExpandCommandText();
- hr = _icommandText.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText);
+ hr = _icommandText!.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText);
if (hr < 0)
{
private void PrepareCommandText(int expectedExecutionCount)
{
- OleDbParameterCollection parameters = _parameters;
+ OleDbParameterCollection? parameters = _parameters;
if (null != parameters)
{
foreach (OleDbParameter parameter in parameters)
}
}
}
- UnsafeNativeMethods.ICommandPrepare icommandPrepare = ICommandPrepare();
+ UnsafeNativeMethods.ICommandPrepare? icommandPrepare = ICommandPrepare();
if (null != icommandPrepare)
{
OleDbHResult hr;
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)
{
private bool PropertiesOnCommand(bool throwNotSupported)
{
+ Debug.Assert(_connection != null);
+
if (null != _icommandText)
{
return true;
Debug.Assert(!_isPrepared, "null command isPrepared");
OleDbConnection connection = _connection;
- if (null == connection)
- {
- connection.CheckStateOpen(ODB.Properties);
- }
+ connection.CheckStateOpen(ODB.Properties);
if (!_trackingForClose)
{
_trackingForClose = true;
return false;
}
- using (DBPropSet propSet = CommandPropertySets())
+ using (DBPropSet? propSet = CommandPropertySets())
{
if (null != propSet)
{
return true;
}
- private DBPropSet CommandPropertySets()
+ private DBPropSet? CommandPropertySets()
{
- DBPropSet propSet = null;
+ DBPropSet? propSet = null;
bool keyInfo = (0 != (CommandBehavior.KeyInfo & this.commandBehavior));
return propSet;
}
- internal Bindings TakeBindingOwnerShip()
+ internal Bindings? TakeBindingOwnerShip()
{
- Bindings bindings = _dbBindings;
+ Bindings? bindings = _dbBindings;
_dbBindings = null;
return bindings;
}
private void ValidateConnectionAndTransaction(string method)
{
ValidateConnection(method);
- _transaction = _connection.ValidateTransaction(Transaction, method);
+ _transaction = _connection!.ValidateTransaction(Transaction, method);
this.canceling = false;
}
}
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
{
{
throw ADP.CommandTextRequired(ADP.DeriveParameters);
}
- OleDbConnection connection = command.Connection;
+ OleDbConnection? connection = command.Connection;
if (null == connection)
{
throw ADP.ConnectionRequired(ADP.DeriveParameters);
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
//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)
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))
{
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();
}
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);
}
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);
{
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");
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");
}
}
- 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!;
}
-
}
}
{
private static readonly object EventInfoMessage = new object();
- public OleDbConnection(string connectionString) : this()
+ public OleDbConnection(string? connectionString) : this()
{
ConnectionString = connectionString;
}
#pragma warning restore 618
SettingsBindable(true),
RefreshProperties(RefreshProperties.All),
+ AllowNull
]
public override string ConnectionString
{
}
}
- private OleDbConnectionString OleDbConnectionStringValue
+ private OleDbConnectionString? OleDbConnectionStringValue
{
- get { return (OleDbConnectionString)ConnectionOptions; }
+ get { return (OleDbConnectionString?)ConnectionOptions; }
}
[
{
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)
{
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();
value = (null != constr) ? constr.InitialCatalog : string.Empty;
}
}
- return Convert.ToString(value, CultureInfo.InvariantCulture);
+ return Convert.ToString(value, CultureInfo.InvariantCulture)!;
}
}
{
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);
}
value = (null != constr) ? constr.DataSource : string.Empty;
}
}
- return Convert.ToString(value, CultureInfo.InvariantCulture);
+ return Convert.ToString(value, CultureInfo.InvariantCulture)!;
}
}
get { return (null != GetOpenConnection()); }
}
- internal OleDbTransaction LocalTransaction
+ internal OleDbTransaction? LocalTransaction
{
set
{
{
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);
}
}
{
get
{
- return (OleDbConnectionPoolGroupProviderInfo)PoolGroup.ProviderInfo;
+ Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo");
+ return (OleDbConnectionPoolGroupProviderInfo)PoolGroup!.ProviderInfo!;
}
}
{
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;
}
}
- public event OleDbInfoMessageEventHandler InfoMessage
+ public event OleDbInfoMessageEventHandler? InfoMessage
{
add
{
}
}
- internal UnsafeNativeMethods.ICommandText ICommandText()
+ internal UnsafeNativeMethods.ICommandText? ICommandText()
{
Debug.Assert(null != GetOpenConnection(), "ICommandText closed");
return GetOpenConnection().ICommandText();
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;
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;
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)
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();
}
}
- 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);
internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode)
{
- OleDbInfoMessageEventHandler handler = (OleDbInfoMessageEventHandler)Events[EventInfoMessage];
+ OleDbInfoMessageEventHandler? handler = (OleDbInfoMessageEventHandler?)Events[EventInfoMessage];
if (null != handler)
{
try
// 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);
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();
ODB.PropsetSetFailure(builder, description, dbprops[0].dwStatus);
- e = ODB.PropsetSetFailure(builder.ToString(), e);
+ e = ODB.PropsetSetFailure(builder.ToString(), e!);
}
if (null != e)
{
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])))
{
}
// 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))
{
OleDbConnectionFactory.SingletonInstance.ClearAllPools();
}
- private static void ResetState(OleDbConnection connection)
+ private static void ResetState(OleDbConnection? connection)
{
if (null != connection)
{
}
}
- 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));
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
// If there is new XML get it
if (values != null)
{
- XMLStream = ADP.GetXmlStreamFromValues(values, metaDataXML);
+ XMLStream = ADP.GetXmlStreamFromValues(values, metaDataXML!);
}
}
oleDbInternalConnection.GetSchemaRowsetInformation());
}
- protected override DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions)
+ protected override DbConnectionPoolGroupOptions? CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions)
{
return null;
}
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;
internal override void PermissionDemand(DbConnection outerConnection)
{
- OleDbConnection c = (outerConnection as OleDbConnection);
+ OleDbConnection? c = (outerConnection as OleDbConnection);
if (null != c)
{
c.PermissionDemand();
internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup)
{
- OleDbConnection c = (outerConnection as OleDbConnection);
+ OleDbConnection? c = (outerConnection as OleDbConnection);
if (null != c)
{
c.PoolGroup = poolGroup;
internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to)
{
- OleDbConnection c = (owningObject as OleDbConnection);
+ OleDbConnection? c = (owningObject as OleDbConnection);
if (null != c)
{
c.SetInnerConnectionEvent(to);
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);
internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to)
{
- OleDbConnection c = (owningObject as OleDbConnection);
+ OleDbConnection? c = (owningObject as OleDbConnection);
if (null != c)
{
c.SetInnerConnectionTo(to);
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
// 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;
}
else
{
- Exception e = OleDbConnection.ProcessResults(hr, null, null);
+ Exception? e = OleDbConnection.ProcessResults(hr, null, null);
Debug.Assert(null != e, "CreateSessionError");
throw e;
}
}
}
- internal OleDbConnection Connection
+ internal OleDbConnection? Connection
{
get
{
- return (OleDbConnection)Owner;
+ return (OleDbConnection?)Owner;
}
}
}
}
- 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;
}
// 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)!;
}
}
}
// 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");
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
{
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);
}
// 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;
base.Dispose();
}
- public override void EnlistTransaction(SysTx.Transaction transaction)
+ public override void EnlistTransaction(SysTx.Transaction? transaction)
{
if (null != LocalTransaction)
{
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);
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;
return value;
}
- internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID)
+ internal object? GetDataSourcePropertyValue(Guid propertySet, int propertyID)
{
OleDbHResult hr;
ItagDBPROP[] dbprops;
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;
}
}
- 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);
table.Columns.Add(schemaGuid);
table.Columns.Add(restrictionSupport);
- SchemaSupport[] supportedSchemas = GetSchemaRowsetInformation();
+ SchemaSupport[]? supportedSchemas = GetSchemaRowsetInformation();
if (null != supportedSchemas)
{
return table;
}
- internal string GetLiteralInfo(int literal)
+ internal string? GetLiteralInfo(int literal)
{
using (IDBInfoWrapper wrapper = IDBInfo())
{
{
return null;
}
- string literalValue = null;
+ string? literalValue = null;
IntPtr literalInfo = ADP.PtrZero;
int literalCount = 0;
OleDbHResult hr;
}
}
- 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
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)
}
}
- internal DataTable GetSchemaRowset(Guid schema, object[] restrictions)
+ internal DataTable? GetSchemaRowset(Guid schema, object?[]? restrictions)
{
if (null == restrictions)
{
restrictions = Array.Empty<object>();
}
- DataTable dataTable = null;
+ DataTable? dataTable = null;
using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset())
{
UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value;
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);
// 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)
{
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)
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,
// 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)
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);
return null;
}
- internal Dictionary<string, OleDbPropertyInfo> GetPropertyInfo(Guid[] propertySets)
+ internal Dictionary<string, OleDbPropertyInfo>? GetPropertyInfo(Guid[] propertySets)
{
- Dictionary<string, OleDbPropertyInfo> properties = null;
+ Dictionary<string, OleDbPropertyInfo>? properties = null;
if (null == propertySets)
{
internal sealed class OleDbConnectionPoolGroupProviderInfo : DbConnectionPoolGroupProviderInfo
{
private bool _hasQuoteFix;
- private string _quotePrefix, _quoteSuffix;
+ private string? _quotePrefix, _quoteSuffix;
internal OleDbConnectionPoolGroupProviderInfo()
{
{
get { return _hasQuoteFix; }
}
- internal string QuotePrefix
+ internal string? QuotePrefix
{
get { return _quotePrefix; }
}
- internal string QuoteSuffix
+ internal string? QuoteSuffix
{
get { return _quoteSuffix; }
}
internal static volatile bool _PoolSizeInit;
internal static int _PoolSize;
- internal static volatile Dictionary<string, string> _Pool;
+ internal static volatile Dictionary<string, string>? _Pool;
internal static object _PoolLock = new object();
}
// 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;
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
// 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))
if (!ADP.IsEmpty(udlConnectionString))
{
- _expandedConnectionString = _expandedConnectionString.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position);
+ _expandedConnectionString = _expandedConnectionString!.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position);
}
}
}
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
get
{
Debug.Assert(!ADP.IsEmpty(this[KEY.Provider]), "no Provider");
- return this[KEY.Provider];
+ return this[KEY.Provider]!;
}
}
}
}
- internal SchemaSupport[] SchemaSupport
+ internal SchemaSupport[]? SchemaSupport
{ // OleDbConnection.GetSchemaRowsetInformation
get { return _schemaSupport; }
set { _schemaSupport = value; }
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;
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);
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);
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;
}
}
- private static string LoadStringFromStorage(string udlfilename)
+ private static string? LoadStringFromStorage(string udlfilename)
{
- string udlConnectionString = null;
- Dictionary<string, string> udlcache = UDL._Pool;
+ string? udlConnectionString = null;
+ Dictionary<string, string>? udlcache = UDL._Pool;
if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString))
{
// [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;
{
throw failure;
}
- return connectionString.Trim();
+ return connectionString!.Trim();
}
private string ValidateConnectionString(string connectionString)
throw ADP.InvalidConnectTimeoutValue();
}
- string progid = ConvertValueToString(KEY.Data_Provider, null);
+ string? progid = ConvertValueToString(KEY.Data_Provider, null);
if (null != progid)
{
progid = progid.Trim();
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
// 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'
{
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
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
{ DbConnectionStringKeywords.OleDbServices, Keywords.OleDbServices },
};
- private string[] _knownKeywords;
- private Dictionary<string, OleDbPropertyInfo> _propertyInfo;
+ private string[]? _knownKeywords;
+ private Dictionary<string, OleDbPropertyInfo>? _propertyInfo;
private string _fileName = DbConnectionStringDefaults.FileName;
_knownKeywords = s_validKeywords;
}
- public OleDbConnectionStringBuilder(string connectionString) : base()
+ public OleDbConnectionStringBuilder(string? connectionString) : base()
{
if (!ADP.IsEmpty(connectionString))
{
}
}
+ [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))
{
{
Dictionary<string, OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
OleDbPropertyInfo info = dynamic[keyword];
- value = info._defaultValue;
+ value = info._defaultValue!;
}
return value;
}
{
get
{
- string[] knownKeywords = _knownKeywords;
+ string[]? knownKeywords = _knownKeywords;
if (null == knownKeywords)
{
Dictionary<string, OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
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)
{
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;
else if (!base.TryGetValue(keyword, out value))
{
Dictionary<string, OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
- OleDbPropertyInfo info;
+ OleDbPropertyInfo? info;
if (dynamic.TryGetValue(keyword, out info))
{
- value = info._defaultValue;
+ value = info._defaultValue!;
return true;
}
return false;
private Dictionary<string, OleDbPropertyInfo> GetProviderInfo(string provider)
{
- Dictionary<string, OleDbPropertyInfo> providerInfo = _propertyInfo;
+ Dictionary<string, OleDbPropertyInfo>? providerInfo = _propertyInfo;
if (null == providerInfo)
{
providerInfo = new Dictionary<string, OleDbPropertyInfo>(StringComparer.OrdinalIgnoreCase);
if (!ADP.IsEmpty(provider))
{
- Dictionary<string, OleDbPropertyInfo> hash = null;
+ Dictionary<string, OleDbPropertyInfo>? hash = null;
try
{
StringBuilder builder = new StringBuilder();
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<string, OleDbPropertyInfo> 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) ||
{
continue; // skip this keyword
}
- providerInfo[info._description] = info;
+ providerInfo[info._description!] = info;
}
}
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()
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<string> providerNames = new System.Collections.Generic.List<string>(table.Rows.Count);
internal sealed class OleDbServicesConverter : TypeConverter
{
- private StandardValuesCollection _standardValues;
+ private StandardValuesCollection? _standardValues;
// converter classes should have public ctor
public OleDbServicesConverter() : base()
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;
convertedValue |= (int)(OleDbServiceValues)Enum.Parse(typeof(OleDbServiceValues), v, true);
}
return (int)convertedValue;
- ;
}
else
{
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
- StandardValuesCollection standardValues = _standardValues;
+ StandardValuesCollection? standardValues = _standardValues;
if (null == standardValues)
{
Array objValues = Enum.GetValues(typeof(OleDbServiceValues));
}
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType)
{
- OleDbConnectionStringBuilder obj = (value as OleDbConnectionStringBuilder);
+ OleDbConnectionStringBuilder? obj = (value as OleDbConnectionStringBuilder);
if (null != obj)
{
return ConvertToInstanceDescriptor(obj);
{
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);
}
}
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);
}
[
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);
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);
}
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");
*/
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)
{
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);
// 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;
}
else if (null != record)
{
- results = FillFromRecord(data, record, srcTable);
+ results = FillFromRecord(data, record, srcTable!);
if (closeRecordset)
{
FillClose(false, record);
// 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();
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
}
else
{
- return base.Fill((DataSet)data, srcTable, dataReader, 0, 0);
+ return base.Fill((DataSet)data, srcTable!, dataReader, 0, 0);
}
}
}
private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstruction record, string srcTable)
{
- object result = null;
+ object? result = null;
try
{
result = record.get_Row();
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);
}
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);
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);
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);
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;
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;
// 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;
}
}
- 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))
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
{
{
throw ADP.DataReaderClosed("FieldCount");
}
- MetaData[] metadata = MetaData;
+ MetaData[]? metadata = MetaData;
return ((null != metadata) ? metadata.Length : 0);
}
}
}
}
- private MetaData[] MetaData
+ private MetaData[]? MetaData
{
get { return _metadata; }
}
private UnsafeNativeMethods.IRowset IRowset()
{
- UnsafeNativeMethods.IRowset irowset = _irowset;
+ UnsafeNativeMethods.IRowset? irowset = _irowset;
if (null == irowset)
{
Debug.Assert(false, "object is disposed");
private UnsafeNativeMethods.IRow IRow()
{
- UnsafeNativeMethods.IRow irow = _irow;
+ UnsafeNativeMethods.IRow? irow = _irow;
if (null == irow)
{
Debug.Assert(false, "object is disposed");
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))
//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()
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;
{
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;
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;
}
else
{
- UnsafeNativeMethods.IMultipleResults multipleResults = _imultipleResults;
+ UnsafeNativeMethods.IMultipleResults? multipleResults = _imultipleResults;
_imultipleResults = null;
if (null != multipleResults)
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)
{
}
// release unmanaged objects
- RowHandleBuffer rowHandleNativeBuffer = _rowHandleNativeBuffer;
+ RowHandleBuffer? rowHandleNativeBuffer = _rowHandleNativeBuffer;
_rowHandleNativeBuffer = null;
if (null != rowHandleNativeBuffer)
{
// called from the connection which will remove this from its ReferenceCollection
// we want the NextResult behavior, but no errors
- _connection = null;
+ _connection = null!;
Close();
}
_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();
}
}
}
private void DisposeNativeMultipleResults()
{
- UnsafeNativeMethods.IMultipleResults imultipleResults = _imultipleResults;
+ UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults;
_imultipleResults = null;
if (null != imultipleResults)
private void DisposeNativeRowset()
{
- UnsafeNativeMethods.IRowset irowset = _irowset;
+ UnsafeNativeMethods.IRowset? irowset = _irowset;
_irowset = null;
ChapterHandle chapter = _chapterHandle;
private void DisposeNativeRow()
{
- UnsafeNativeMethods.IRow irow = _irow;
+ UnsafeNativeMethods.IRow? irow = _irow;
_irow = null;
if (null != irow)
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();
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();
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
{
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();
}
throw ADP.NonSequentialColumnAccess(ordinal, _nextValueForRetrieval);
}
// @usernote: user may encounter the IndexOutOfRangeException
- MetaData info = _metadata[ordinal];
+ MetaData info = _metadata![ordinal];
return info;
}
{
if (_nextValueForRetrieval != binding.Index)
{ // release old value
- _metadata[_nextValueForRetrieval].columnBinding.ResetValue();
+ _metadata![_nextValueForRetrieval].columnBinding.ResetValue();
}
_nextAccessorForRetrieval = binding.IndexForAccessor;
}
}
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();
private void ProcessResults(OleDbHResult hr)
{
- Exception e;
+ Exception? e;
if (null != _command)
{
e = OleDbConnection.ProcessResults(hr, _connection, _command);
_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<OleDbException> exceptions = null;
+ List<OleDbException>? exceptions = null;
if (null != imultipleResults)
{
object result;
}
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)
}
_fieldNameLookup = null;
- OleDbCommand command = _command;
- UnsafeNativeMethods.IMultipleResults imultipleResults = _imultipleResults;
+ OleDbCommand? command = _command;
+ UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults;
if (null != imultipleResults)
{
DisposeOpenResults();
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;
public override bool Read()
{
bool retflag = false;
- OleDbCommand command = _command;
+ OleDbCommand? command = _command;
if ((null != command) && command.canceling)
{
DisposeOpenResults();
else
{
_isRead = true;
- return (0 < _metadata.Length);
+ return (0 < _metadata!.Length);
}
return false;
}
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
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;
{
_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);
int bindingCount = 0;
int currentBindingIndex = 0;
- MetaData[] metadata = _metadata;
+ MetaData[] metadata = _metadata!;
int[] indexToBinding = new int[metadata.Length];
int[] indexWithinBinding = new int[metadata.Length];
OleDbHResult hr = 0;
- RowHandleBuffer rowHandleBuffer = _rowHandleNativeBuffer;
+ RowHandleBuffer rowHandleBuffer = _rowHandleNativeBuffer!;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
IntPtr rowHandle = _rowHandleNativeBuffer.GetRowHandle(_currentRow);
- RowBinding rowBinding = _bindings[_nextAccessorForRetrieval].RowBinding();
+ RowBinding rowBinding = _bindings[_nextAccessorForRetrieval]!.RowBinding()!;
IntPtr accessorHandle = rowBinding.DangerousGetAccessorHandle();
bool mustRelease = false;
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)
{
_isRead = false;
}
- private object GetPropertyValue(int propertyId)
+ private object? GetPropertyValue(int propertyId)
{
if (null != _irowset)
{
return OleDbPropertyStatus.NotSupported;
}
- private object GetPropertyOnRowset(Guid propertySet, int propertyID)
+ private object? GetPropertyOnRowset(Guid propertySet, int propertyID)
{
OleDbHResult hr;
ItagDBPROP[] dbprops;
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
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);
}
{
if (mustRelease[i])
{
- sptr[i].DangerousRelease();
+ sptr[i]!.DangerousRelease();
}
}
}
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
}
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];
{
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)
{
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;
}
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();
}
// 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)
// 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)
{
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++;
}
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;
}
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)
{
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)
}
}
- 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<MetaData> metainfo = new List<MetaData>();
- 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)
// 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
#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;
{
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);
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;
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));
}
}
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)
{
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;
//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);
}
}
{
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)
{
this.source = ODB.FailedGetSource(hr);
}
- Marshal.ReleaseComObject(errorInfo);
+ Marshal.ReleaseComObject(errorInfo!);
}
}
{
get
{
- string message = this.message;
+ string? message = this.message;
return ((null != message) ? message : string.Empty);
}
}
{
get
{
- string source = this.source;
+ string? source = this.source;
return ((null != source) ? source : string.Empty);
}
}
{
get
{
- string sqlState = this.sqlState;
+ string? sqlState = this.sqlState;
return ((null != sqlState) ? sqlState : string.Empty);
}
}
{
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();
{
get
{
- return (this.items[index] as OleDbError);
+ return (this.items[index] as OleDbError)!;
}
}
{
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;
}
}
- 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)
}
}
- public string Source
+ public string? Source
{
get
{
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
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);
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
// 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];
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);
{
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);
// 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);
}
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);
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)
{
}
// update the DataSourceProductName
- object property;
+ object? property;
property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSNAME);
if (property != null)
{
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));
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);
// 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],
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"],
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
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);
// 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);
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)
{
// 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
}
else
{
- throw ADP.InvalidRestrictionValue(collectionName, "TYPE", restrictions[indexRestrictionTypeSlot]);
+ throw ADP.InvalidRestrictionValue(collectionName, "TYPE", restrictions[indexRestrictionTypeSlot]!);
}
mungedRestrictions[indexRestrictionTypeSlot] = indexTypeValue;
}
else
{
- throw ADP.InvalidRestrictionValue(collectionName, "PROCEDURE_TYPE", restrictions[procedureRestrictionTypeSlot]);
+ throw ADP.InvalidRestrictionValue(collectionName, "PROCEDURE_TYPE", restrictions[procedureRestrictionTypeSlot]!);
}
mungedRestrictions[procedureRestrictionTypeSlot] = procedureTypeValue;
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)
{
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
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)");
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;
}
[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;
}
[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;
}
set
{
- NativeDBType dbtype = _metaType;
+ NativeDBType? dbtype = _metaType;
if ((null == dbtype) || (dbtype.enumDbType != value))
{
PropertyTypeChanging();
}
set
{
- NativeDBType dbtype = _metaType;
+ NativeDBType? dbtype = _metaType;
if ((null == dbtype) || (dbtype.enumOleDbType != value))
{
PropertyTypeChanging();
}
}
+ [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
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)
{ // 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;
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))
}
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)
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))
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;
internal bool IsParameterComputed()
{
- NativeDBType metaType = _metaType;
+ NativeDBType? metaType = _metaType;
return ((null == metaType)
|| (!ShouldSerializeSize() && metaType.IsVariableLength)
|| ((NativeDBType.DECIMAL == metaType.dbType) || (NativeDBType.NUMERIC == metaType.dbType)
RefreshProperties(RefreshProperties.All),
TypeConverter(typeof(StringConverter)),
]
- public override object Value
+ public override object? Value
{ // V1.2.3300, XXXParameter V1.0.3300
get
{
}
}
- 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);
}
{
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);
}
}
Type[] ctorParams;
- object[] ctorValues;
+ object?[] ctorValues;
switch (flags)
{
case 0: // ParameterName
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))
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 };
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,
}
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);
}
}
[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));
}
{
public sealed partial class OleDbParameterCollection : DbParameterCollection
{
- private List<OleDbParameter> _items;
+ private List<OleDbParameter>? _items;
public override int Count
{
{
get
{
- List<OleDbParameter> items = _items;
+ List<OleDbParameter>? items = _items;
if (null == items)
{
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)
{
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;
}
}
}
{
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); }
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;
internal interface ItagDBPROP
{
OleDbPropertyStatus dwStatus { get; }
- object vValue { get; }
+ object? vValue { get; }
int dwPropertyID { get; }
}
{
OleDbPropertyStatus ItagDBPROP.dwStatus => this.dwStatus;
- object ItagDBPROP.vValue => this.vValue;
+ object? ItagDBPROP.vValue => this.vValue;
int ItagDBPROP.dwPropertyID => this.dwPropertyID;
internal tagDBIDX columnid;
// Variant
- [MarshalAs(UnmanagedType.Struct)] internal object vValue;
+ [MarshalAs(UnmanagedType.Struct)] internal object? vValue;
internal tagDBPROP_x86()
{
{
OleDbPropertyStatus ItagDBPROP.dwStatus => this.dwStatus;
- object ItagDBPROP.vValue => this.vValue;
+ object? ItagDBPROP.vValue => this.vValue;
int ItagDBPROP.dwPropertyID => this.dwPropertyID;
internal int dwPropertyID;
internal tagDBIDX columnid;
// Variant
- [MarshalAs(UnmanagedType.Struct)] internal object vValue;
+ [MarshalAs(UnmanagedType.Struct)] internal object? vValue;
internal tagDBPROP()
{
internal sealed class tagDBCOLUMNINFO
{
[MarshalAs(UnmanagedType.LPWStr)]
- internal string pwszName = null;
+ internal string? pwszName = null;
//[MarshalAs(UnmanagedType.Interface)]
internal IntPtr pTypeInfo = (IntPtr)0;
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)]
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()
{
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()
{
{
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;
}
}
- internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, IsolationLevel isolevel)
+ internal OleDbTransaction(OleDbConnection connection, OleDbTransaction? transaction, IsolationLevel isolevel)
{
_parentConnection = connection;
_parentTransaction = transaction;
}
}
- internal OleDbTransaction Parent
+ internal OleDbTransaction? Parent
{
get
{
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();
}
if (null != _nestedTransaction)
{
- OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target;
+ OleDbTransaction? transaction = (OleDbTransaction?)_nestedTransaction.Target;
if ((null != transaction) && _nestedTransaction.IsAlive)
{
transaction.CommitInternal();
{
_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; }
}
{
if (null != _nestedTransaction)
{
- OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target;
+ OleDbTransaction? transaction = (OleDbTransaction?)_nestedTransaction.Target;
if ((null != transaction) && _nestedTransaction.IsAlive)
{
hr = transaction.RollbackInternal(exceptionHandling);
{
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);
return head;
}
- internal static OleDbTransaction TransactionUpdate(OleDbTransaction transaction)
+ internal static OleDbTransaction? TransactionUpdate(OleDbTransaction? transaction)
{
if ((null != transaction) && (null == transaction._transaction))
{
// 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)
{
internal void GetDataSource(OleDbConnectionString constr, ref DataSourceWrapper datasrcWrapper)
{
OleDbHResult hr;
- UnsafeNativeMethods.IDataInitializeGetDataSource GetDataSource = DangerousIDataInitializeGetDataSource;
+ UnsafeNativeMethods.IDataInitializeGetDataSource GetDataSource = DangerousIDataInitializeGetDataSource!;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
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
{
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;
}
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
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
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
// 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()
{
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;
}
}
- // 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,
internal IDBInfoWrapper(object unknown)
{
_unknown = unknown;
- _value = (unknown as UnsafeNativeMethods.IDBInfo);
+ _value = (unknown as UnsafeNativeMethods.IDBInfo)!;
}
internal UnsafeNativeMethods.IDBInfo Value
public void Dispose()
{
object unknown = _unknown;
- _unknown = null;
- _value = null;
+ _unknown = null!;
+ _value = null!;
if (null != unknown)
{
Marshal.ReleaseComObject(unknown);
internal IDBPropertiesWrapper(object unknown)
{
_unknown = unknown;
- _value = (unknown as UnsafeNativeMethods.IDBProperties);
+ _value = (unknown as UnsafeNativeMethods.IDBProperties)!;
Debug.Assert(null != _value, "null IDBProperties");
}
public void Dispose()
{
object unknown = _unknown;
- _unknown = null;
- _value = null;
+ _unknown = null!;
+ _value = null!;
if (null != unknown)
{
Marshal.ReleaseComObject(unknown);
internal IDBSchemaRowsetWrapper(object unknown)
{
_unknown = unknown;
- _value = (unknown as UnsafeNativeMethods.IDBSchemaRowset);
+ _value = (unknown as UnsafeNativeMethods.IDBSchemaRowset)!;
}
internal UnsafeNativeMethods.IDBSchemaRowset Value
public void Dispose()
{
object unknown = _unknown;
- _unknown = null;
- _value = null;
+ _unknown = null!;
+ _value = null!;
if (null != unknown)
{
Marshal.ReleaseComObject(unknown);
internal IOpenRowsetWrapper(object unknown)
{
_unknown = unknown;
- _value = (unknown as UnsafeNativeMethods.IOpenRowset);
+ _value = (unknown as UnsafeNativeMethods.IOpenRowset)!;
Debug.Assert(null != _value, "null IOpenRowsetWrapper");
}
public void Dispose()
{
object unknown = _unknown;
- _unknown = null;
- _value = null;
+ _unknown = null!;
+ _value = null!;
if (null != unknown)
{
Marshal.ReleaseComObject(unknown);
internal ITransactionJoinWrapper(object unknown)
{
_unknown = unknown;
- _value = (unknown as NativeMethods.ITransactionJoin);
+ _value = (unknown as NativeMethods.ITransactionJoin)!;
}
internal NativeMethods.ITransactionJoin Value
public void Dispose()
{
object unknown = _unknown;
- _unknown = null;
- _value = null;
+ _unknown = null!;
+ _value = null!;
if (null != unknown)
{
Marshal.ReleaseComObject(unknown);
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
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;
internal static NativeDBType FromSystemType(object value)
{
- IConvertible ic = (value as IConvertible);
+ IConvertible? ic = (value as IConvertible);
if (null != ic)
{
return ic.GetTypeCode() switch
{
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);
}
{
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))
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);
}
{
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);
}
{
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);
}
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);
{
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
}
}
- internal Dictionary<string, OleDbPropertyInfo> GetValues()
+ internal Dictionary<string, OleDbPropertyInfo>? GetValues()
{
- Dictionary<string, OleDbPropertyInfo> propertyLookup = null;
+ Dictionary<string, OleDbPropertyInfo>? propertyLookup = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
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;
return true;
}
- internal static Type FromVtType(int vartype) =>
+ internal static Type? FromVtType(int vartype) =>
(VarEnum)vartype switch
{
VarEnum.VT_EMPTY => null,
private readonly int _dataLength;
private readonly int _emptyStringOffset;
- private UnsafeNativeMethods.IAccessor _iaccessor;
+ private UnsafeNativeMethods.IAccessor? _iaccessor;
private IntPtr _accessorHandle;
private readonly bool _needToReset;
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");
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);
}
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
{
ResetValues();
- UnsafeNativeMethods.IAccessor iaccessor = _iaccessor;
+ UnsafeNativeMethods.IAccessor? iaccessor = _iaccessor;
IntPtr accessorHandle = _accessorHandle;
_iaccessor = null;
#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)
{
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)
{
}
// 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);
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)
{
}
// 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;
}
{
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
{ }
internal static unsafe OleDbHResult ITransactionAbort(System.IntPtr ptr)
{
OleDbHResult hr = OleDbHResult.E_UNEXPECTED;
- ITransactionLocal transactionLocal = null;
+ ITransactionLocal? transactionLocal = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
internal static unsafe OleDbHResult ITransactionCommit(System.IntPtr ptr)
{
OleDbHResult hr = OleDbHResult.E_UNEXPECTED;
- ITransactionLocal transactionLocal = null;
+ ITransactionLocal? transactionLocal = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>netstandard2.0-Windows_NT;netstandard2.0;net461-Windows_NT</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. -->
<PropertyGroup>
using System.Configuration;
using System.Data.SqlTypes;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.Versioning;
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);
{
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);
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);
{
return InvalidOperation(error);
}
- internal static InvalidOperationException DataAdapter(string error, Exception inner)
+ internal static InvalidOperationException DataAdapter(string error, Exception? inner)
{
return InvalidOperation(error, inner);
}
{
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);
}
}
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);
}
//
{
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);
}
return OpenReaderExists(null);
}
- internal static Exception OpenReaderExists(Exception e)
+ internal static Exception OpenReaderExists(Exception? e)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
}
}
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)
{
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)
{
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)
{
}
- 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);
}
}
}
- 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);
}
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;
// 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)
// 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;
// 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;
}
// 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);
}
}
#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);
}
}
// 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;
}
return new DbConnectionPoolKey(this);
}
- internal virtual string ConnectionString
+ internal virtual string? ConnectionString
{
get
{
}
}
- 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);
}
{ // 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)
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);
}
GenerateLookup();
}
int index;
- object value = _fieldNameLookup[fieldName];
+ object? value = _fieldNameLookup![fieldName];
if (null != value)
{
// via case sensitive search, first match with lowest ordinal matches
private int LinearIndexOf(string fieldName, CompareOptions compareOptions)
{
- CompareInfo compareInfo = _compareInfo;
+ CompareInfo? compareInfo = _compareInfo;
if (null == compareInfo)
{
if (-1 != _defaultLocaleID)
{
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;
}
}
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;
}
internal string Name => _name;
- internal string Value => _value;
+ internal string? Value => _value;
- internal NameValuePair Next
+ internal NameValuePair? Next
{
get { return _next; }
set
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);
}
Validate(offset, 2 * length);
Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
- string value = null;
+ string? value = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
}
}
- protected override void Activate(SysTx.Transaction transaction)
+ protected override void Activate(SysTx.Transaction? transaction)
{
throw ADP.ClosedConnectionError();
}
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();
}
throw ADP.ClosedConnectionError();
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
return base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions);
}
{
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
throw ADP.ConnectionAlreadyOpen(State);
}
connectionFactory.SetInnerConnectionTo(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
if (retry == null || !retry.Task.IsCompleted)
{
// 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<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
- private static Task<DbConnectionInternal> s_completedTask;
+ private static readonly Task<DbConnectionInternal?>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal?>[Environment.ProcessorCount];
+ private static Task<DbConnectionInternal?>? s_completedTask;
protected DbConnectionFactory() : this(DbConnectionPoolCountersNoCounters.SingletonInstance) { }
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);
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)
return newConnection;
}
- internal virtual DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
+ internal virtual DbConnectionPoolGroupProviderInfo? CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
}
// GetCompletedTask must be called from within s_pendingOpenPooled lock
- private static Task<DbConnectionInternal> GetCompletedTask()
+ private static Task<DbConnectionInternal?> GetCompletedTask()
{
if (s_completedTask == null)
{
- TaskCompletionSource<DbConnectionInternal> source = new TaskCompletionSource<DbConnectionInternal>();
+ TaskCompletionSource<DbConnectionInternal?> source = new TaskCompletionSource<DbConnectionInternal?>();
source.SetResult(null);
s_completedTask = source.Task;
}
return s_completedTask;
}
- internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
+ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal>? 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
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)
// 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)
{
// 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);
{
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)
}
else if (task.IsFaulted)
{
- retry.TrySetException(task.Exception.InnerException);
+ retry.TrySetException(task.Exception!.InnerException!);
}
else
{
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
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<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
{
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
// 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
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
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);
{
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
}
}
- 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);
}
}
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);
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)
}
}
- internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup
+ internal System.Data.ProviderBase.DbConnectionPoolGroup? PoolGroup
{
get
{
}
}
- internal DbConnectionOptions UserConnectionOptions
+ internal DbConnectionOptions? UserConnectionOptions
{
get
{
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;
}
// 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
// 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)
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)
{
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");
}
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.
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.
}
}
- protected internal SysTx.Transaction EnlistedTransaction
+ protected internal SysTx.Transaction? EnlistedTransaction
{
get
{
}
set
{
- SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
+ SysTx.Transaction? currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
|| ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
{
// 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)
}
}
- 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
{
}
}
- protected DbConnectionPoolCounters PerformanceCounters
+ protected DbConnectionPoolCounters? PerformanceCounters
{
get
{
return _performanceCounters;
}
}
- protected internal DbReferenceCollection ReferenceCollection
+ protected internal DbReferenceCollection? ReferenceCollection
{
get
{
}
}
- protected abstract void Activate(SysTx.Transaction transaction);
+ protected abstract void Activate(SysTx.Transaction? transaction);
internal void AddWeakReference(object value, int tag)
{
// 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
}
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.
Deactivate(); // call it one more time just in case
- DbConnectionPool pool = Pool;
+ DbConnectionPool? pool = Pool;
if (null == pool)
{
// 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
_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.");
internal void NotifyWeakReference(int message)
{
- DbReferenceCollection referenceCollection = ReferenceCollection;
+ DbReferenceCollection? referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Notify(message);
/// override this and do the correct thing.</devdoc>
// 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<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions)
{
throw ADP.ConnectionAlreadyOpen(State);
}
- protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
+ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal>? 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);
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.
internal void RemoveWeakReference(object value)
{
- DbReferenceCollection referenceCollection = ReferenceCollection;
+ DbReferenceCollection? referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Remove(value);
internal void DetachCurrentTransactionIfEnded()
{
- SysTx.Transaction enlistedTransaction = EnlistedTransaction;
+ SysTx.Transaction? enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null)
{
bool transactionIsDead;
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;
internal void SetInStasis()
{
_isInStasis = true;
- PerformanceCounters.NumberOfStasisConnections.Increment();
+ PerformanceCounters!.NumberOfStasisConnections.Increment();
}
private void TerminateStasis(bool returningToPool)
{
- PerformanceCounters.NumberOfStasisConnections.Decrement();
+ PerformanceCounters!.NumberOfStasisConnections.Decrement();
_isInStasis = false;
}
{
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.
Activate(transaction);
- PerformanceCounters.NumberOfActiveConnections.Increment();
+ PerformanceCounters!.NumberOfActiveConnections.Increment();
}
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
// 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();
{
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
// 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();
private sealed class PendingGetConnection
{
- public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions)
+ public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions? userOptions)
{
DueTime = dueTime;
Owner = owner;
public long DueTime { get; private set; }
public DbConnection Owner { get; private set; }
public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; }
- public DbConnectionOptions UserOptions { get; private set; }
+ public DbConnectionOptions? UserOptions { get; private set; }
}
private sealed class TransactedConnectionPool
}
}
- 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)
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
{
// 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
{
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;
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<DbConnectionInternal> _objectList;
private int _totalObjects;
get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); }
}
- private void CleanupCallback(object state)
+ private void CleanupCallback(object? state)
{
// Called when the cleanup-timer ticks over.
if (_waitHandles.PoolSemaphore.WaitOne(0, false) /* != WAIT_TIMEOUT */)
{
// We obtained a objects from the semaphore.
- DbConnectionInternal obj;
+ DbConnectionInternal? obj;
if (_stackOld.TryPop(out obj))
{
{
while (true)
{
- DbConnectionInternal obj;
+ DbConnectionInternal? obj;
if (!_stackNew.TryPop(out obj))
break;
internal void Clear()
{
- DbConnectionInternal obj;
+ DbConnectionInternal? obj;
// First, quickly doom everything.
lock (_objectList)
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
{
// 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
}
}
- 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)
{
// 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;
}
{
Debug.Assert(!Thread.CurrentThread.IsThreadPoolThread, "This thread may block for a long time. Threadpool threads should not be used.");
- PendingGetConnection next;
+ PendingGetConnection? next;
do
{
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
} while (_pendingOpens.TryPeek(out next));
}
- internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
+ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal>? retry, DbConnectionOptions? userOptions, out DbConnectionInternal? connection)
{
uint waitForMultipleObjectsTimeout = 0;
bool allowCreate = false;
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();
case ERROR_HANDLE:
// Throw the error that PoolCreateRequest stashed.
Interlocked.Decrement(ref _waitCount);
- throw TryCloneCachedException();
+ throw TryCloneCachedException()!;
case CREATION_HANDLE:
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
/// <param name="userOptions">Options used to create the new connection</param>
/// <param name="oldConnection">Inner connection that will be replaced</param>
/// <returns>A new inner connection that is attached to the <paramref name="owningObject"/></returns>
- 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();
return newConnection;
}
- private DbConnectionInternal GetFromGeneralPool()
+ private DbConnectionInternal? GetFromGeneralPool()
{
- DbConnectionInternal obj = null;
+ DbConnectionInternal? obj = null;
if (!_stackNew.TryPop(out obj))
{
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)
{
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
// 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;
}
_state = State.ShuttingDown;
// deactivate timer callbacks
- Timer t = _cleanupTimer;
+ Timer? t = _cleanupTimer;
_cleanupTimer = null;
if (null != t)
{
}
}
- 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
{
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)
{
internal void Decrement()
{
- PerformanceCounter instance = _instance;
+ PerformanceCounter? instance = _instance;
if (null != instance)
{
instance.Decrement();
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)
{
internal void Increment()
{
- PerformanceCounter instance = _instance;
+ PerformanceCounter? instance = _instance;
if (null != instance)
{
instance.Increment();
{
}
- 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))
{
}
// 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);
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
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)
{
// 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))
{
// 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
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;
}
}
- 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();
}
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;
_connectionOptions = connectionOptions;
_poolKey = key;
- _poolGroupOptions = poolGroupOptions;
+ _poolGroupOptions = poolGroupOptions!;
// always lock this object before changing state
// HybridDictionary does not create any sub-objects until add
}
}
- internal DbConnectionPoolGroupProviderInfo ProviderInfo
+ internal DbConnectionPoolGroupProviderInfo? ProviderInfo
{
get
{
_providerInfo = value;
if (null != value)
{
- _providerInfo.PoolGroup = this;
+ _providerInfo!.PoolGroup = this;
}
}
}
}
}
- internal DbMetaDataFactory MetaDataFactory
+ internal DbMetaDataFactory? MetaDataFactory
{
get
{
// 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<DbConnectionPoolIdentity, DbConnectionPool> oldPoolCollection = null;
+ ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>? oldPoolCollection = null;
lock (this)
{
if (_poolCollection.Count > 0)
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.
// 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
{
internal class DbConnectionPoolGroupProviderInfo
{
- private DbConnectionPoolGroup _poolGroup;
+ private DbConnectionPoolGroup? _poolGroup;
- internal DbConnectionPoolGroup PoolGroup
+ internal DbConnectionPoolGroup? PoolGroup
{
get
{
return resultSid;
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
bool result = ((this == NoIdentity) || (this == value));
if (!result && (null != value))
ADP.CheckArgumentNull(serverVersion, "serverVersion");
ADP.CheckArgumentNull(normalizedServerVersion, "normalizedServerVersion");
- LoadDataSetFromXml(xmlStream);
+ _metaDataCollectionsDataSet = new DataSet { Locale = CultureInfo.InvariantCulture };
+ _metaDataCollectionsDataSet.ReadXml(xmlStream);
_serverVersionString = serverVersion;
_normalizedServerVersion = normalizedServerVersion;
}
}
- protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames)
+ protected DataTable CloneAndFilterCollection(string collectionName, string[]? hiddenColumnNames)
{
- DataTable sourceTable;
+ DataTable? sourceTable;
DataTable destinationTable;
DataColumn[] filteredSourceColumns;
DataColumnCollection destinationColumns;
{
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))
{
command.Parameters.Add(restrictionParameter);
}
- DbDataReader reader = null;
+ DbDataReader? reader = null;
try
{
try
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)
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;
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))
{
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)
throw ADP.MissingRestrictionColumn();
}
- foreach (DataRow restriction in restrictionsTable.Rows)
+ foreach (DataRow restriction in restrictionsTable!.Rows)
{
if (((string)restriction[collectionName] == neededCollectionName) &&
((int)restriction[restrictionNumber] == neededRestrictionNumber) &&
}
- 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
}
}
- string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string;
+ string populationMechanism = (requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string)!;
switch (populationMechanism)
{
case _dataTable:
return requestedSchema;
}
- private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames)
+ private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames)
{
bool result = true;
string sourceColumnName = sourceColumn.ColumnName;
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();
}
{
bool result = true;
DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns;
- DataColumn versionColumn;
+ DataColumn? versionColumn;
object version;
// check the minimum version first
// 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
}
}
- public object Target
+ public object? Target
{
get
{
}
}
+ [return: MaybeNull]
internal T FindItem<T>(int tag, Func<T, bool> filterMethod) where T : class
{
bool lockObtained = false;
{
// 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;
{
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);
{
}
- internal WrappedIUnknown(object unknown) : this()
+ internal WrappedIUnknown(object? unknown) : this()
{
if (null != unknown)
{
{
// 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
[PreserveSig]
System.Data.OleDb.OleDbHResult GetProperties(
[In] int cPropertyIDSets,
- [In] SafeHandle rgPropertyIDSets,
+ [In] SafeHandle? rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertySets);
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);
[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);
[PreserveSig]
System.Data.OleDb.OleDbHResult GetProperties(
[In] int cPropertyIDSets,
- [In] SafeHandle rgPropertyIDSets,
+ [In] SafeHandle? rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertySets);
[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,
[PreserveSig]
System.Data.OleDb.OleDbHResult GetProperties(
[In] int cPropertyIDSets,
- [In] SafeHandle rgPropertyIDSets,
+ [In] SafeHandle? rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertySets);
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
[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);
}