Skip to content

Commit

Permalink
Support DataSourceAttribute on .NET 6 and later
Browse files Browse the repository at this point in the history
  • Loading branch information
Youssef1313 committed Nov 18, 2024
1 parent 4e6f740 commit 8d8edc8
Show file tree
Hide file tree
Showing 33 changed files with 166 additions and 50 deletions.
20 changes: 20 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,26 @@
<MicrosoftTestingTargetFrameworks>net6.0;net7.0;net8.0</MicrosoftTestingTargetFrameworks>
</PropertyGroup>

<!-- Constants -->
<PropertyGroup>
<!-- Historically, DataSourceAttribute was only supported for .NET Framework ONLY. -->
<!-- We are adding the support for net6.0 and later only for now (not including netstandard2.0, nor netcoreapp3.1) -->
<!-- On netcoreapp3.1, we get this warning: -->
<!--
C:\Users\<USER>\.nuget\packages\system.security.cryptography.protecteddata\8.0.0\buildTransitive\netcoreapp2.0\System.Security.Cryptography.ProtectedData.targets(4,5)
: error : System.Security.Cryptography.ProtectedData 8.0.0 doesn't support netcoreapp3.1 and has not been tested with it. Consider upgrading your TargetFramework to ne
t6.0 or later. You may also set <SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings> in the project file to ignore this warning and attempt to run i
n this unsupported configuration at your own risk. [C:\Users\<USER>\Desktop\testfx\test\UnitTests\MSTestAdapter.UnitTests\MSTestAdapter.UnitTests.csproj::TargetFramew
ork=netcoreapp3.1]
-->
<!-- For now, we don't care that much about netcoreapp3.1. That's a better idea than suppressing the build warning. -->
<!-- Also, on WinUI we are hitting this bug, https://github.com/microsoft/microsoft-ui-xaml/issues/5689, so not including it for now. -->
<IsDataSourceSupported>false</IsDataSourceSupported>
<IsDataSourceSupported Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0')) AND '$(TargetFramework)'!='$(WinUiMinimum)'">true</IsDataSourceSupported>
<IsDataSourceSupported Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', '$(NetFrameworkMinimum)'))">true</IsDataSourceSupported>
<DefineConstants Condition="$(IsDataSourceSupported)">$(DefineConstants);IS_DATA_SOURCE_SUPPORTED</DefineConstants>
</PropertyGroup>

<!-- Build config -->
<PropertyGroup>
<!-- Prevent warning about deprecated target frameworks -->
Expand Down
4 changes: 4 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,17 @@
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
</ItemGroup>
<ItemGroup Label="Product dependencies">
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
<PackageVersion Include="System.Data.Odbc" Version="8.0.0" />
<PackageVersion Include="System.Data.OleDb" Version="8.0.0" />
<PackageVersion Include="Microsoft.ApplicationInsights" Version="2.22.0" />
<PackageVersion Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildVersion)" />
<PackageVersion Include="Microsoft.Build.Utilities.Core" Version="$(MicrosoftBuildVersion)" />
<PackageVersion Include="Microsoft.CodeAnalysis" Version="$(MicrosoftCodeAnalysisVersion)" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="$(MicrosoftCodeAnalysisAnalyzersVersion)" />
<PackageVersion Include="Microsoft.CodeAnalysis.Common" Version="$(MicrosoftCodeAnalysisVersion)" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="$(MicrosoftCodeAnalysisVersion)" />
<PackageVersion Include="Microsoft.Data.SqlClient" Version="5.1.5" />
<PackageVersion Include="Microsoft.Diagnostics.NETCore.Client" Version="0.2.510501" />
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="$(MicrosoftTestingExtensionsCodeCoverageVersion)" />
<PackageVersion Include="Microsoft.Testing.Extensions.Retry" Version="$(MicrosoftTestingInternalFrameworkVersion)" />
Expand Down
2 changes: 1 addition & 1 deletion samples/FxExtensibility/FxExtensibility.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<PropertyGroup>
<RootNamespace>MSTest.Extensibility.Samples</RootNamespace>
<AssemblyName>MSTest.Extensibility.Samples</AssemblyName>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>$(DefineConstants);TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
<PropertyGroup>
<RootNamespace>Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter</RootNamespace>
<AssemblyName>Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter</AssemblyName>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>$(DefineConstants);TRACE</DefineConstants>
<!-- Force NuGet package dependencies to be copied to the output directory so we can embed AdapterUtilities in our NuGet. -->
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED

using System.Collections;
using System.Data;
Expand Down Expand Up @@ -77,6 +77,13 @@ public override List<string> GetDataTablesAndViews()
[SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security", Justification = "Not passed in from user.")]
public DataTable ReadTable(string tableName, IEnumerable? columns, int maxRows)
{
#if !NETFRAMEWORK
if (!OperatingSystem.IsWindows())
{
// TODO: It looks like the whole Csv logic can be refactored to work on all operating systems by not using OleDbConnection at all?
throw new NotSupportedException("CsvDataConnection is only supported on Windows.");
}
#endif
// We specifically use OleDb to read a CSV file...
WriteDiagnostics("ReadTable: {0}", tableName);
WriteDiagnostics("Current Directory: {0}", Directory.GetCurrentDirectory());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED

using System.Data.Odbc;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED

using System.Data.OleDb;
#if !NETFRAMEWORK
using System.Runtime.Versioning;
#endif

using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand All @@ -12,6 +15,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Dat
/// <summary>
/// Utility classes to access databases, and to handle quoted strings etc for OLE DB.
/// </summary>
#if !NETFRAMEWORK
[SupportedOSPlatform("windows")]
#endif
internal sealed class OleDataConnection : TestDataConnectionSql
{
private readonly bool _isMSSql;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED

#if NETFRAMEWORK
using System.Data.SqlClient;
#else
using Microsoft.Data.SqlClient;
#endif

using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
using System.Collections;
using System.Data;
using System.Data.Common;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED

using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Data.OleDb;
#if NETFRAMEWORK
using System.Data.SqlClient;
#endif
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;

#if !NETFRAMEWORK
using Microsoft.Data.SqlClient;
#endif
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand All @@ -35,11 +40,11 @@ protected internal TestDataConnectionSql(string invariantProviderName, string co
DebugEx.Assert(Factory != null, "factory should not be null.");
WriteDiagnostics("DbProviderFactory {0}", Factory);

_connection = Factory.CreateConnection();
_connection = Factory.CreateConnection()!;
DebugEx.Assert(_connection != null, "connection");
WriteDiagnostics("DbConnection {0}", _connection);

CommandBuilder = Factory.CreateCommandBuilder();
CommandBuilder = Factory.CreateCommandBuilder()!;
DebugEx.Assert(CommandBuilder != null, "builder");
WriteDiagnostics("DbCommandBuilder {0}", CommandBuilder);

Expand Down Expand Up @@ -81,6 +86,13 @@ public static TestDataConnectionSql Create(string invariantProviderName, string
}
else if (string.Equals(invariantProviderName, "System.Data.OleDb", StringComparison.OrdinalIgnoreCase))
{
#if !NETFRAMEWORK
if (!OperatingSystem.IsWindows())
{
throw new NotSupportedException($"Failed to create connection to '{connectionString}'. OleDbConnection is only supported on Windows.");
}
#endif

return new OleDataConnection(invariantProviderName, connectionString, dataFolders);
}
else if (string.Equals(invariantProviderName, "System.Data.Odbc", StringComparison.OrdinalIgnoreCase))
Expand Down Expand Up @@ -485,7 +497,7 @@ public override List<string> GetDataTablesAndViews()
try
{
WriteDiagnostics("Getting schema table {0}", metadata.SchemaTable);
dataTable = Connection.GetSchema(metadata.SchemaTable);
dataTable = Connection.GetSchema(metadata.SchemaTable!);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -521,9 +533,9 @@ public override List<string> GetDataTablesAndViews()
}

// Get the schema name, and filter bad schemas
if (row[metadata.SchemaColumn] != DBNull.Value)
if (row[metadata.SchemaColumn!] != DBNull.Value)
{
tableSchema = row[metadata.SchemaColumn] as string;
tableSchema = row[metadata.SchemaColumn!] as string;

if (IsInArray(tableSchema, metadata.InvalidSchemas))
{
Expand All @@ -536,7 +548,7 @@ public override List<string> GetDataTablesAndViews()
isDefaultSchema = string.Equals(tableSchema, defaultSchema, StringComparison.OrdinalIgnoreCase);
}

string? tableName = row[metadata.NameColumn] as string;
string? tableName = row[metadata.NameColumn!] as string;
WriteDiagnostics("Table {0}{1} found", tableSchema != null ? tableSchema + "." : string.Empty, tableName);

// If schema is defined and is not equal to default, prepend table schema in front of the table.
Expand Down Expand Up @@ -599,7 +611,7 @@ public override List<string> GetDataTablesAndViews()
foreach (DataRow columnRow in columns.Rows)
{
WriteDiagnostics("Column info: {0}", columnRow);
result.Add(columnRow["COLUMN_NAME"].ToString());
result.Add(columnRow["COLUMN_NAME"].ToString()!);
}

// Now we are done, since for any particular table or view, all the columns
Expand Down Expand Up @@ -723,6 +735,12 @@ protected virtual bool IsUserSchema(string tableSchema) =>
{
var oleDbConnection = Connection as OleDbConnection;
var odbcConnection = Connection as OdbcConnection;
#if !NETFRAMEWORK
if (oleDbConnection is not null && !OperatingSystem.IsWindows())
{
throw new NotSupportedException("OleDbConnection is only supported on Windows.");
}
#endif
DebugEx.Assert(
Connection is SqlConnection ||
(oleDbConnection != null && IsMSSql(oleDbConnection.Provider)) ||
Expand All @@ -732,7 +750,11 @@ Connection is SqlConnection ||
DebugEx.Assert(IsOpen(), "The connection must already be open!");
DebugEx.Assert(!StringEx.IsNullOrEmpty(Connection.ServerVersion), "GetDefaultSchema: the ServerVersion is null or empty!");

#if NETFRAMEWORK
int index = Connection.ServerVersion.IndexOf(".", StringComparison.Ordinal);
#else
int index = Connection.ServerVersion.IndexOf('.');
#endif
DebugEx.Assert(index > 0, "GetDefaultSchema: index should be 0");

string versionString = Connection.ServerVersion.Substring(0, index);
Expand Down Expand Up @@ -776,8 +798,8 @@ Connection is SqlConnection ||
public override DataTable ReadTable(string tableName, IEnumerable? columns)
#pragma warning restore SA1202 // Elements must be ordered by access
{
using DbDataAdapter dataAdapter = Factory.CreateDataAdapter();
using DbCommand command = Factory.CreateCommand();
using DbDataAdapter dataAdapter = Factory.CreateDataAdapter()!;
using DbCommand command = Factory.CreateCommand()!;

// We need to escape bad characters in table name like [Sheet1$] in Excel.
// But if table name is quoted in terms of provider, don't touch it to avoid e.g. [dbo.tables.etc].
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
using System.Collections;
using System.Data;
using System.Diagnostics.CodeAnalysis;
Expand Down Expand Up @@ -87,6 +87,9 @@ public XmlDataConnection(string fileName, List<string> dataFolders)
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Un-tested. Preserving behavior.")]
[SuppressMessage("Security", "CA3075:Insecure DTD processing in XML", Justification = "Not enough tests to understand if we would break")]
[SuppressMessage("Security", "CA5366:Use XmlReader for 'DataSet.ReadXml()'", Justification = "Not enough tests to understand if we would break")]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "While this can fail and the analysis is actually correct, it seems like if it happened it's likely to be user's fault?" +
"If the user is referencing type from XML, they should be confident that they are not trimmed.")]
private DataSet? LoadDataSet(bool schemaOnly)
{
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<PropertyGroup>
<RootNamespace>Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices</RootNamespace>
<AssemblyName>Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices</AssemblyName>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>$(DefineConstants);TRACE</DefineConstants>
</PropertyGroup>

<!-- Properties specific to UWP -->
Expand All @@ -36,6 +36,10 @@

<ItemGroup>
<PackageReference Include="System.Diagnostics.TextWriterTraceListener" Condition=" '$(TargetFramework)' == '$(WinUiMinimum)' " />

<PackageReference Include="System.Data.Odbc" Condition="$(IsDataSourceSupported)" />
<PackageReference Include="System.Data.OleDb" Condition="$(IsDataSourceSupported)" />
<PackageReference Include="Microsoft.Data.SqlClient" Condition="$(IsDataSourceSupported)" />
</ItemGroup>

<PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
#nullable enable
override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.DataConnection.get -> System.Data.Common.DbConnection?
override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.DataRow.get -> System.Data.DataRow?
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
#nullable enable
override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.DataConnection.get -> System.Data.Common.DbConnection?
override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.DataRow.get -> System.Data.DataRow?
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
#nullable enable
override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.DataConnection.get -> System.Data.Common.DbConnection?
override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.DataRow.get -> System.Data.DataRow?
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
using System.Data;
using System.Data.Common;
#endif
Expand Down Expand Up @@ -53,7 +53,7 @@ public class TestContextImplementation : TestContext, ITestContext
/// </summary>
private UnitTestOutcome _outcome;

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
/// <summary>
/// DB connection for test context.
/// </summary>
Expand Down Expand Up @@ -100,7 +100,7 @@ public TestContextImplementation(ITestMethod testMethod, StringWriter stringWrit
/// <inheritdoc/>
public override UnitTestOutcome CurrentTestOutcome => _outcome;

#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
/// <inheritdoc/>
public override DbConnection? DataConnection => _dbConnection;

Expand Down Expand Up @@ -266,7 +266,7 @@ public void SetException(Exception? exception)
/// <param name="dataRow">data row.</param>
public void SetDataRow(object? dataRow)
{
#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
#pragma warning disable IDE0022 // Use expression body for method
_dataRow = dataRow as DataRow;
#pragma warning restore IDE0022 // Use expression body for method
Expand All @@ -282,7 +282,7 @@ public void SetDataRow(object? dataRow)
/// <param name="dbConnection">db Connection.</param>
public void SetDataConnection(object? dbConnection)
{
#if NETFRAMEWORK
#if IS_DATA_SOURCE_SUPPORTED
#pragma warning disable IDE0022 // Use expression body for method
_dbConnection = dbConnection as DbConnection;
#pragma warning restore IDE0022 // Use expression body for method
Expand Down
Loading

0 comments on commit 8d8edc8

Please sign in to comment.