Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,16 @@ private static extern unsafe uint SNISecGenClientContextWrapper(

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket);
#endregion

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumOpenWrapper")]
internal static extern IntPtr SNIServerEnumOpen();

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumCloseWrapper")]
internal static extern void SNIServerEnumClose([In] IntPtr packet);

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumReadWrapper")]
internal static extern int SNIServerEnumRead([In] IntPtr packet, [In, Out] char[] readBuffer, int bufferLength, ref bool more);
#endregion

internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
<Compile Include="..\..\src\Microsoft\Data\Sql\SqlNotificationRequest.cs">
<Link>Microsoft\Data\Sql\SqlNotificationRequest.cs</Link>
</Compile>
<Compile Include="..\..\src\Microsoft\Data\Sql\SqlDataSourceEnumerator.cs">
<Link>Microsoft\Data\Sql\SqlDataSourceEnumerator.cs</Link>
</Compile>
<Compile Include="..\..\src\Microsoft\Data\Common\ActivityCorrelator.cs">
<Link>Microsoft\Data\Common\ActivityCorrelator.cs</Link>
</Compile>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ internal static int GetTimeoutMilliseconds(long timeoutTime)
}
return (int)msecRemaining;
}
static internal long GetTimeoutSeconds(int timeout)
{
return GetTimeout((long)timeout * 1000L);
}

internal static long GetTimeout(long timeoutMilliseconds)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@
<Compile Include="..\..\src\Microsoft\Data\Sql\SqlNotificationRequest.cs">
<Link>Microsoft\Data\Sql\SqlNotificationRequest.cs</Link>
</Compile>
<Compile Include="..\..\src\Microsoft\Data\Sql\SqlDataSourceEnumerator.cs">
<Link>Microsoft\Data\Sql\SqlDataSourceEnumerator.cs</Link>
</Compile>
<Compile Include="..\..\src\Microsoft\Data\SqlClient\DataClassification\SensitivityClassification.cs">
<Link>Microsoft\Data\SqlClient\DataClassification\SensitivityClassification.cs</Link>
</Compile>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,14 @@ internal static extern unsafe uint SNISecGenClientContextWrapper(

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr SNIClientCertificateFallbackWrapper(IntPtr pCallbackContext);

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumOpenWrapper")]
internal static extern IntPtr SNIServerEnumOpen();

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumCloseWrapper")]
internal static extern void SNIServerEnumClose([In] IntPtr packet);

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumReadWrapper")]
internal static extern int SNIServerEnumRead([In] IntPtr packet, [In, Out] char[] readBuffer, int bufferLength, out bool more);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,14 @@ internal static extern unsafe uint SNISecGenClientContextWrapper(

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr SNIClientCertificateFallbackWrapper(IntPtr pCallbackContext);

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumOpenWrapper")]
internal static extern IntPtr SNIServerEnumOpen();

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumCloseWrapper")]
internal static extern void SNIServerEnumClose([In] IntPtr packet);

[DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIServerEnumReadWrapper")]
internal static extern int SNIServerEnumRead([In] IntPtr packet, [In, Out] char[] readBuffer, int bufferLength, out bool more);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,37 @@ internal static uint SNIInitialize()
return SNIInitialize(LocalAppContextSwitches.UseSystemDefaultSecureProtocols, IntPtr.Zero);
}

internal static IntPtr SNIServerEnumOpen()
{
if (s_is64bitProcess)
{
return SNINativeManagedWrapperX64.SNIServerEnumOpen();
}
else
{
return SNINativeManagedWrapperX86.SNIServerEnumOpen();
}
}

internal static void SNIServerEnumClose([In] IntPtr packet)
{
if (s_is64bitProcess)
{
SNINativeManagedWrapperX64.SNIServerEnumClose(packet);
}
else
{
SNINativeManagedWrapperX86.SNIServerEnumClose(packet);
}
}

internal static int SNIServerEnumRead([In] IntPtr packet, [In, Out] char[] readbuffer, int bufferLength, ref bool more)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIServerEnumRead(packet, readbuffer, bufferLength, out more) :
SNINativeManagedWrapperX86.SNIServerEnumRead(packet, readbuffer, bufferLength, out more);
}

internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo)
{
// initialize consumer info for MARS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,11 @@ internal static long GetTimeout(long timeoutMilliseconds)
return result;
}

static internal long GetTimeoutSeconds(int timeout)
{
return GetTimeout((long)timeout * 1000L);
}

internal static bool TimeoutHasExpired(long timeoutTime)
{
bool result = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1201,6 +1201,9 @@ static internal Exception InvalidMixedUsageOfCredentialAndAccessToken()
=> InvalidOperation(StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
#endregion

internal static bool IsEmpty(string str) => string.IsNullOrEmpty(str);
internal static readonly IntPtr s_ptrZero = IntPtr.Zero; // IntPtr.Zero

#if NETFRAMEWORK
#region netfx project only
internal static Task<T> CreatedTaskWithException<T>(Exception ex)
Expand Down Expand Up @@ -1355,7 +1358,6 @@ internal static InvalidOperationException ComputerNameEx(int lastError)
internal const float FailoverTimeoutStepForTnir = 0.125F; // Fraction of timeout to use in case of Transparent Network IP resolution.
internal const int MinimumTimeoutForTnirMs = 500; // The first login attempt in Transparent network IP Resolution

internal static readonly IntPtr s_ptrZero = IntPtr.Zero; // IntPtr.Zero
internal static readonly int s_ptrSize = IntPtr.Size;
internal static readonly IntPtr s_invalidPtr = new(-1); // use for INVALID_HANDLE

Expand Down Expand Up @@ -1446,7 +1448,6 @@ internal static IntPtr IntPtrOffset(IntPtr pbase, int offset)
return (IntPtr)checked(pbase.ToInt64() + offset);
}

internal static bool IsEmpty(string str) => string.IsNullOrEmpty(str);
#endregion
#else
#region netcore project only
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
using Microsoft.Data.Common;
using Microsoft.Data.SqlClient;
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;

namespace Microsoft.Data.Sql
{
/// <summary>
/// Provides a mechanism for enumerating all available instances of SQL Server within the local network
/// </summary>
public sealed class SqlDataSourceEnumerator : DbDataSourceEnumerator
{

private static readonly SqlDataSourceEnumerator SingletonInstance = new SqlDataSourceEnumerator();
internal const string ServerName = "ServerName";
internal const string InstanceName = "InstanceName";
internal const string IsClustered = "IsClustered";
internal const string Version = "Version";
private static string _Version = "Version:";
private static string _Cluster = "Clustered:";
private static int _clusterLength = _Cluster.Length;
private static int _versionLength = _Version.Length;
private const int timeoutSeconds = ADP.DefaultCommandTimeout;
private long timeoutTime; // variable used for timeout computations, holds the value of the hi-res performance counter at which this request should expire

private SqlDataSourceEnumerator() : base()
{
}

/// <summary>
/// Gets an instance of the SqlDataSourceEnumerator, which can be used to retrieve information about available SQL Server instances.
/// </summary>
public static SqlDataSourceEnumerator Instance => SqlDataSourceEnumerator.SingletonInstance;

/// <summary>
/// Retrieves a DataTable containing information about all visible SQL Server instances
/// </summary>
/// <returns></returns>
override public DataTable GetDataSources()
{
(new NamedPermissionSet("FullTrust")).Demand(); // SQLBUDT 244304
char[] buffer = null;
StringBuilder strbldr = new StringBuilder();

Int32 bufferSize = 1024;
Int32 readLength = 0;
buffer = new char[bufferSize];
bool more = true;
bool failure = false;
IntPtr handle = ADP.s_ptrZero;

RuntimeHelpers.PrepareConstrainedRegions();
try
{
timeoutTime = TdsParserStaticMethods.GetTimeoutSeconds(timeoutSeconds);
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
finally
{
handle = SNINativeMethodWrapper.SNIServerEnumOpen();
}

if (handle != ADP.s_ptrZero)
{
while (more && !TdsParserStaticMethods.TimeoutHasExpired(timeoutTime))
{
readLength = SNINativeMethodWrapper.SNIServerEnumRead(handle, buffer, bufferSize, ref more);

if (readLength > bufferSize)
{
failure = true;
more = false;
}
else if (0 < readLength)
{
strbldr.Append(buffer, 0, readLength);
}
}
}
}
finally
{
if (handle != ADP.s_ptrZero)
{
SNINativeMethodWrapper.SNIServerEnumClose(handle);
}
}

if (failure)
{
Debug.Assert(false, "GetDataSources:SNIServerEnumRead returned bad length");
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlDataSourceEnumerator.GetDataSources|ERR> GetDataSources:SNIServerEnumRead returned bad length, requested %d, received %d", bufferSize, readLength);
throw ADP.ArgumentOutOfRange("readLength");
}

return ParseServerEnumString(strbldr.ToString());
}

static private System.Data.DataTable ParseServerEnumString(string serverInstances)
{
DataTable dataTable = new DataTable("SqlDataSources");
dataTable.Locale = CultureInfo.InvariantCulture;
dataTable.Columns.Add(ServerName, typeof(string));
dataTable.Columns.Add(InstanceName, typeof(string));
dataTable.Columns.Add(IsClustered, typeof(string));
dataTable.Columns.Add(Version, typeof(string));
DataRow dataRow = null;
string serverName = null;
string instanceName = null;
string isClustered = null;
string version = null;

// Every row comes in the format "serverName\instanceName;Clustered:[Yes|No];Version:.."
// Every row is terminated by a null character.
// Process one row at a time
foreach (string instance in serverInstances.Split(new string[] { "\0\0\0" }, StringSplitOptions.None))
{
// string value = instance.Trim('\0'); // MDAC 91934
string value = instance.Replace("\0", "");
if (0 == value.Length)
{
continue;
}
foreach (string instance2 in value.Split(';'))
{
if (serverName == null)
{
foreach (string instance3 in instance2.Split('\\'))
{
if (serverName == null)
{
serverName = instance3;
continue;
}
Debug.Assert(instanceName == null);
instanceName = instance3;
}
continue;
}
if (isClustered == null)
{
Debug.Assert(String.Compare(_Cluster, 0, instance2, 0, _clusterLength, StringComparison.OrdinalIgnoreCase) == 0);
isClustered = instance2.Substring(_clusterLength);
continue;
}
Debug.Assert(version == null);
Debug.Assert(String.Compare(_Version, 0, instance2, 0, _versionLength, StringComparison.OrdinalIgnoreCase) == 0);
version = instance2.Substring(_versionLength);
}

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

if (!ADP.IsEmpty(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)
{
dataRow = dataTable.NewRow();
dataRow[0] = serverName;
dataRow[1] = instanceName;
dataRow[2] = isClustered;
dataRow[3] = version;
dataTable.Rows.Add(dataRow);
}
serverName = null;
instanceName = null;
isClustered = null;
version = null;
}
foreach (DataColumn column in dataTable.Columns)
{
column.ReadOnly = true;
}
return dataTable;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
<Compile Include="BaseProviderAsyncTest\MockDataReader.cs" />
<Compile Include="SqlCredentialTest.cs" />
<Compile Include="SqlDataRecordTest.cs" />
<Compile Include="SqlDataSourceEnumeratorTest.cs" />
<Compile Include="SqlExceptionTest.cs" />
<Compile Include="SqlFacetAttributeTest.cs" />
<Compile Include="SqlNotificationRequestTest.cs" />
Expand All @@ -68,6 +69,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkVersion)" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="$(SystemDiagnosticsDiagnosticSourceVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="4.4.1" />
<Reference Condition="'$(TargetGroup)'=='netfx'" Include="System.Transactions" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Data;
using System.ServiceProcess;
using Microsoft.Data.Sql;
using Xunit;

namespace Microsoft.Data.SqlClient.Tests
{
internal class SqlDataSourceEnumeratorTest
{
[PlatformSpecific(TestPlatforms.Windows)]
public void SqlDataSourceEnumerator_VerfifyDataTableSize()
{
ServiceController sc = new ServiceController("SQLBrowser");
Assert.Equal(ServiceControllerStatus.Running, sc.Status);

SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
DataTable table = instance.GetDataSources();
Assert.NotEmpty(table.Rows);
}
}
}