Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,12 @@ internal static class IpAddressPreferenceUtilities
/// <summary>
/// IP Address Preference.
/// </summary>
private static readonly Dictionary<string, SqlConnectionIPAddressPreference> s_preferenceNames = new(StringComparer.InvariantCultureIgnoreCase);

static IpAddressPreferenceUtilities()
private static readonly Dictionary<string, SqlConnectionIPAddressPreference> s_preferenceNames = new(StringComparer.InvariantCultureIgnoreCase)
{
foreach (SqlConnectionIPAddressPreference item in Enum.GetValues(typeof(SqlConnectionIPAddressPreference)))
{
s_preferenceNames.Add(item.ToString(), item);
}
}
{ nameof(SqlConnectionIPAddressPreference.IPv4First), SqlConnectionIPAddressPreference.IPv4First },
{ nameof(SqlConnectionIPAddressPreference.IPv6First), SqlConnectionIPAddressPreference.IPv6First },
{ nameof(SqlConnectionIPAddressPreference.UsePlatformDefault), SqlConnectionIPAddressPreference.UsePlatformDefault },
};

/// <summary>
/// Convert a string value to the corresponding IPAddressPreference.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
Expand Down Expand Up @@ -97,7 +98,7 @@ internal static DataTable GetDataSources()
return ParseServerEnumString(strbldr.ToString());
}

private static DataTable ParseServerEnumString(string serverInstances)
internal static DataTable ParseServerEnumString(string serverInstances)
{
DataTable dataTable = PrepareDataTable();
string serverName = null;
Expand Down Expand Up @@ -147,15 +148,8 @@ private static DataTable ParseServerEnumString(string serverInstances)
version = instance2.Substring(s_versionLength);
}

string query = "ServerName='" + serverName + "'";

if (!string.IsNullOrEmpty(instanceName))
{ // SQL BU DT 20006584: only append instanceName if present.
query += " AND InstanceName='" + instanceName + "'";
}

// SNI returns dupes - do not add them. SQL BU DT 290323
if (dataTable.Select(query).Length == 0)
if (!ContainsInstance(dataTable, serverName, instanceName))
Comment thread
charlesroddie marked this conversation as resolved.
Resolved
Comment thread
charlesroddie marked this conversation as resolved.
Resolved
{
DataRow dataRow = dataTable.NewRow();
dataRow[0] = serverName;
Expand All @@ -171,5 +165,31 @@ private static DataTable ParseServerEnumString(string serverInstances)
}
return dataTable.SetColumnsReadOnly();
}

private static bool ContainsInstance(DataTable dataTable, string serverName, string instanceName)
{
CompareInfo compareInfo = dataTable.Locale.CompareInfo;
CompareOptions options = dataTable.CaseSensitive
? CompareOptions.None
: CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;

foreach (DataRow row in dataTable.Rows)
{
if (EqualsInTable(compareInfo, options, row[ServerNameCol] as string, serverName) &&
// SQL BU DT 20006584: only match instanceName if present.
(string.IsNullOrEmpty(instanceName) || EqualsInTable(compareInfo, options, row[InstanceNameCol] as string, instanceName)))
{
return true;
}
}
return false;
}
Comment thread
charlesroddie marked this conversation as resolved.
Resolved

// Matches DataTable's string equality.
private static bool EqualsInTable(CompareInfo compareInfo, CompareOptions options, string s1, string s2) =>
compareInfo.Compare(
s1?.TrimEnd(' ', '\u3000'),
s2?.TrimEnd(' ', '\u3000'),
options) == 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ private bool LoadUserInstanceDll()
}

// Set the delegate the invoke.
localDBStartInstanceFunc = (LocalDBStartInstance)Marshal.GetDelegateForFunctionPointer(_startInstanceHandle, typeof(LocalDBStartInstance));
localDBStartInstanceFunc = Marshal.GetDelegateForFunctionPointer<LocalDBStartInstance>(_startInstanceHandle);

if (localDBStartInstanceFunc == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ internal void Bind(TdsParserStateObject stateObj)
}

#if !NETFRAMEWORK
[SuppressMessage("ReflectionAnalysis", "IL2111",
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2111",
Justification = "System.Type.TypeInitializer would not be used in dataType and providerSpecificDataType columns.")]
#endif
internal DataTable BuildSchemaTable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
Expand Down Expand Up @@ -443,7 +444,7 @@ private async ValueTask<DataTable> ExecuteCommandAsync(DataRow requestedCollecti

foreach (DbColumn col in colSchema)
{
resultTable.Columns.Add(col.ColumnName, col.DataType);
AddColumn(resultTable, col);
}

if (firstResultAvailable)
Expand All @@ -462,6 +463,13 @@ private async ValueTask<DataTable> ExecuteCommandAsync(DataRow requestedCollecti
}
return resultTable;
}

#if NET
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072",
Justification = "DataColumn only reflects over INullable column types, and no schema collection columns are INullable.")]
#endif
private static void AddColumn(DataTable table, DbColumn column) =>
table.Columns.Add(column.ColumnName, column.DataType);
#endregion

#region GetSchema Helpers: PrepareCollection Population Method
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Threading.Tasks;
using Xunit;

Expand Down Expand Up @@ -170,9 +171,25 @@ public static async Task GetDataTypesFromSchema()

Assert.All(testColumnNames, column => Assert.Contains(column, syncColumnNames));
Assert.All(testColumnNames, column => Assert.Contains(column, asyncColumnNames));
VerifyNoINullableColumns(syncTable);
VerifyNoINullableColumns(asyncTable);
return (syncTable, asyncTable);
}

/// <summary>
/// Verifies that no column of a schema collection has an <see cref="INullable"/> type, which
/// SqlMetaDataFactory.AddColumn relies on to suppress IL2072.
/// </summary>
/// <param name="schemaTable">The table returned for a schema collection.</param>
private static void VerifyNoINullableColumns(DataTable schemaTable)
{
foreach (DataColumn column in schemaTable.Columns)
{
Assert.False(typeof(INullable).IsAssignableFrom(column.DataType),
$"Column '{column.ColumnName}' of schema collection '{schemaTable.TableName}' has INullable type {column.DataType}.");
}
}

private static void VerifyDataTypesTable(DataTable dataTypesTable)
{
string[] expectedTypes = [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using Microsoft.Data.Common.ConnectionString;
using Microsoft.Data.SqlClient;
using Xunit;

namespace Microsoft.Data.Common.UnitTests;

/// <summary>
/// Tests for <see cref="IpAddressPreferenceUtilities"/>.
/// </summary>
public class IpAddressPreferenceUtilitiesTest
{
/// <summary>
/// Verifies that each enum value's name converts back to that value, so the explicitly listed names
/// stay in sync with the enum definition.
/// </summary>
[Fact]
public void TryConvertToIPAddressPreference_AcceptsEveryEnumValueName()
{
foreach (SqlConnectionIPAddressPreference value in Enum.GetValues(typeof(SqlConnectionIPAddressPreference)))
{
Assert.True(IpAddressPreferenceUtilities.TryConvertToIPAddressPreference(value.ToString(), out SqlConnectionIPAddressPreference result), $"{value} is missing.");
Assert.Equal(value, result);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Data;
using System.Linq;
using Xunit;

namespace Microsoft.Data.Sql.UnitTests;

/// <summary>
/// Tests parsing and de-duplication of the native SNI server enumeration string in
/// <see cref="SqlDataSourceEnumeratorNativeHelper.ParseServerEnumString"/>, which must match
/// the string equality of the case-insensitive <see cref="DataTable"/> it populates.
/// </summary>
public class SqlDataSourceEnumeratorNativeHelperTest
{
/// <summary>
/// Gets server and instance names that a case-insensitive <see cref="DataTable"/> treats as equal to
/// "server" and "inst": identical, differing in case, with trailing ASCII or ideographic spaces, and full-width.
/// </summary>
/// <see cref="EquivalentEntry_IsDropped"/>
public static TheoryData<string, string> EquivalentNames => new()
{
{ "server", "inst" },
{ "SERVER", "INST" },
{ "server ", "inst " },
{ "server" + (char)0x3000, "inst" + (char)0x3000 },
{ ToFullWidth("server"), ToFullWidth("inst") },
};

/// <summary>
/// Verifies that every column of distinct entries is returned, and that an entry without an instance
/// name stores <see cref="DBNull"/> for the instance.
/// </summary>
[Fact]
public void DistinctEntries_AreAllReturned()
Comment thread
charlesroddie marked this conversation as resolved.
Resolved
{
DataTable table = Parse(Entry("server1", "inst1", "Yes", "16.0.1000.6"), Entry("server2", null));

Assert.Equal(2, table.Rows.Count);
Assert.Equal("server1", table.Rows[0][SqlDataSourceEnumeratorUtil.ServerNameCol]);
Assert.Equal("inst1", table.Rows[0][SqlDataSourceEnumeratorUtil.InstanceNameCol]);
Assert.Equal("Yes", table.Rows[0][SqlDataSourceEnumeratorUtil.IsClusteredCol]);
Assert.Equal("16.0.1000.6", table.Rows[0][SqlDataSourceEnumeratorUtil.VersionNameCol]);
Assert.Equal("server2", table.Rows[1][SqlDataSourceEnumeratorUtil.ServerNameCol]);
Assert.Equal(DBNull.Value, table.Rows[1][SqlDataSourceEnumeratorUtil.InstanceNameCol]);
}

/// <summary>
/// Verifies that an entry equal to an earlier one under <see cref="DataTable"/> string comparison is dropped.
/// </summary>
/// <param name="serverName">A server name equivalent to "server".</param>
/// <param name="instanceName">An instance name equivalent to "inst".</param>
[Theory]
[MemberData(nameof(EquivalentNames))]
public void EquivalentEntry_IsDropped(string serverName, string instanceName)
{
DataTable table = Parse(Entry("server", "inst"), Entry(serverName, instanceName));

Assert.Equal(1, table.Rows.Count);
}

/// <summary>
/// Verifies that two instances on the same server are both returned.
/// </summary>
[Fact]
public void SameServerWithDifferentInstance_IsKept()
{
DataTable table = Parse(Entry("server", "inst1"), Entry("server", "inst2"));

Assert.Equal(2, table.Rows.Count);
}

/// <summary>
/// Verifies that an entry without an instance name is treated as a duplicate of an earlier entry for the
/// same server, whatever that entry's instance.
/// </summary>
[Fact]
public void EntryWithoutInstance_MatchesExistingServerWithAnyInstance()
{
DataTable table = Parse(Entry("server", "inst"), Entry("server", null));

Assert.Equal(1, table.Rows.Count);
}

/// <summary>
/// Verifies that an entry with an instance name is not a duplicate of an earlier entry for the same server
/// that has no instance.
/// </summary>
[Fact]
public void EntryWithInstance_DoesNotMatchExistingServerWithoutInstance()
{
DataTable table = Parse(Entry("server", null), Entry("server", "inst"));

Assert.Equal(2, table.Rows.Count);
}

/// <summary>
/// Joins entries with the native end-of-instance delimiter and parses them.
/// </summary>
/// <param name="entries">Entries formatted by <see cref="Entry"/>.</param>
/// <returns>The parsed data sources table.</returns>
private static DataTable Parse(params string[] entries) =>
SqlDataSourceEnumeratorNativeHelper.ParseServerEnumString(
string.Join(SqlDataSourceEnumeratorUtil.EndOfServerInstanceDelimiter_Native.ToString(), entries));

/// <summary>
/// Formats one entry as native SNI returns it: "serverName[\instanceName];Clustered:[Yes|No];Version:...".
/// </summary>
/// <param name="serverName">The server name.</param>
/// <param name="instanceName">The instance name, or <see langword="null"/> for a default instance.</param>
/// <param name="clustered">The clustered flag.</param>
/// <param name="version">The server version.</param>
/// <returns>The formatted entry.</returns>
private static string Entry(string serverName, string? instanceName, string clustered = "No", string version = "15.0.2000.5") =>
(instanceName is null ? serverName : serverName + SqlDataSourceEnumeratorUtil.ServerNamesAndInstanceDelimiter + instanceName) +
SqlDataSourceEnumeratorUtil.InstanceKeysDelimiter + SqlDataSourceEnumeratorUtil.Clustered + clustered +
SqlDataSourceEnumeratorUtil.InstanceKeysDelimiter + SqlDataSourceEnumeratorUtil.Version + version;

/// <summary>
/// Converts printable ASCII characters to their full-width forms.
/// </summary>
/// <param name="value">A string of printable ASCII characters.</param>
/// <returns>The full-width string.</returns>
private static string ToFullWidth(string value) =>
new(value.Select(c => (char)(c + 0xFEE0)).ToArray());
}
Loading