Skip to content

Commit

Permalink
Add global usings for .NET projects (.NET SDK, Web and Worker) (#18459)
Browse files Browse the repository at this point in the history
  • Loading branch information
John Luo authored Jul 8, 2021
1 parent aaa6580 commit 8594395
Show file tree
Hide file tree
Showing 29 changed files with 686 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
<PropertyGroup>
<TargetFramework>$(AspNetTestTfm)</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<!-- Removing implicit namespace imports for web since AspNetCore.App is removed -->
<DisableImplicitNamespaceImports_Web>true</DisableImplicitNamespaceImports_Web>
</PropertyGroup>

<ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions src/Layout/toolset-tasks/toolset-tasks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<TargetFrameworks>$(SdkTargetFramework);net472</TargetFrameworks>
<TargetFrameworks Condition=" '$([MSBuild]::IsOSPlatform(`Windows`))' == 'false' ">$(SdkTargetFramework)</TargetFrameworks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<DisableImplicitNamespaceImports>true</DisableImplicitNamespaceImports>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!--
***********************************************************************************************
Microsoft.NET.GenerateImplicitNamespaceImports.targets
WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have
created a backup copy. Incorrect changes to this file will make it
impossible to load or build your projects from the command-line or the IDE.
Copyright (c) .NET Foundation. All rights reserved.
***********************************************************************************************
-->
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!--
============================================================
GenerateImplicitNamespaceImports
Generates implicit namespace imports source to intermediate directory for C# projects
============================================================
-->
<PropertyGroup>
<GeneratedImplicitNamespaceImportFile Condition="'$(GeneratedImplicitNamespaceImportFile)' ==''">$(IntermediateOutputPath)$(MSBuildProjectName).ImplicitNamespaceImports$(DefaultLanguageSourceExtension)</GeneratedImplicitNamespaceImportFile>
<DisableImplicitNamespaceImports_DotNet Condition="'$(DisableImplicitNamespaceImports_DotNet)' == '' and '$(DisableImplicitNamespaceImports)' != 'true'">false</DisableImplicitNamespaceImports_DotNet>
</PropertyGroup>

<!--
Note that this must run before every invocation of CoreCompile to ensure that all compiler
runs see the generated assembly info. There is at least one scenario involving Xaml
where CoreCompile is invoked without other potential hooks such as Compile or CoreBuild,
etc., so we hook directly on to CoreCompile. Furthermore, we must run *after*
PrepareForBuild to ensure that the intermediate directory has been created.
Targets that generate Compile items are also expected to run before
BeforeCompile targets (common targets convention).
-->
<Target Name="GenerateImplicitNamespaceImports"
BeforeTargets="BeforeCompile;CoreCompile"
DependsOnTargets="PrepareForBuild;CoreGenerateImplicitNamespaceImports"
Condition="'$(DisableImplicitNamespaceImports)' != 'true'" />

<Target Name="CoreGenerateImplicitNamespaceImports"
Outputs="$(GeneratedImplicitNamespaceImportFile)"
Condition="'@(Import)' != ''">
<ItemGroup>
<_UniqueImport Include="@(Import->Distinct())" />
<_ImportFileLine Include="// %3Cautogenerated />"/>
<_ImportFileLine Include="global using global::%(_UniqueImport.Identity)%3B"/>
</ItemGroup>

<WriteLinesToFile Lines="@(_ImportFileLine)" File="$(GeneratedImplicitNamespaceImportFile)" Overwrite="true" WriteOnlyWhenDifferent="true" />

<ItemGroup>
<Compile Include="$(GeneratedImplicitNamespaceImportFile)" />
<FileWrites Include="$(GeneratedImplicitNamespaceImportFile)" />
</ItemGroup>
</Target>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,16 @@ Copyright (c) .NET Foundation. All rights reserved.

</ItemGroup>

<ItemGroup Condition=" '$(DisableImplicitNamespaceImports_DotNet)' != 'true'
and '$(TargetFrameworkIdentifier)' == '.NETCoreApp'
and $([MSBuild]::VersionGreaterThanOrEquals($(_TargetFrameworkVersionWithoutV), '6.0'))">
<Import Include="System" />
<Import Include="System.Collections.Generic" />
<Import Include="System.IO" />
<Import Include="System.Linq" />
<Import Include="System.Net.Http" />
<Import Include="System.Threading" />
<Import Include="System.Threading.Tasks" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ Copyright (c) .NET Foundation. All rights reserved.
***********************************************************************************************
-->
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<DisableImplicitNamespaceImports Condition="'$(DisableImplicitNamespaceImports)'==''">$(DisableImplicitFrameworkReferences)</DisableImplicitNamespaceImports>
</PropertyGroup>
<ItemGroup Condition=" '$(DisableImplicitNamespaceImports)' != 'true' and '$(TargetFrameworkIdentifier)' == '.NETFramework'">
<!-- These namespaces are present in 2.0 Framework assemblies -->
<Import Include="Microsoft.VisualBasic" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Copyright (c) .NET Foundation. All rights reserved.
<ComputeNETCoreBuildOutputFiles Condition=" '$(ComputeNETCoreBuildOutputFiles)' == '' and '$(TargetFrameworkIdentifier)' == '.NETCoreApp'">true</ComputeNETCoreBuildOutputFiles>
<_GenerateRuntimeConfigurationPropertyInputsCache Condition="'$(_GenerateRuntimeConfigurationPropertyInputsCache)' == ''">$(IntermediateOutputPath)$(MSBuildProjectName).genruntimeconfig.cache</_GenerateRuntimeConfigurationPropertyInputsCache>
<_GenerateRuntimeConfigurationPropertyInputsCache>$([MSBuild]::NormalizePath($(MSBuildProjectDirectory), $(_GenerateRuntimeConfigurationPropertyInputsCache)))</_GenerateRuntimeConfigurationPropertyInputsCache>
<DisableImplicitNamespaceImports Condition="'$(DisableImplicitNamespaceImports)'==''">$(DisableImplicitFrameworkReferences)</DisableImplicitNamespaceImports>
</PropertyGroup>

<ItemGroup>
Expand Down Expand Up @@ -1087,6 +1088,7 @@ Copyright (c) .NET Foundation. All rights reserved.
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.DisableStandardFrameworkResolution.targets" Condition="'$(DisableStandardFrameworkResolution)' == 'true'" />
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.DesignerSupport.targets" />
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.GenerateAssemblyInfo.targets" Condition="'$(UsingNETSdkDefaults)' == 'true'"/>
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.GenerateImplicitNamespaceImports.targets" Condition="'$(DisableImplicitNamespaceImports)' != 'true' and '$(Language)' == 'C#'"/>
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.GenerateSupportedRuntime.targets" />
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.ComposeStore.targets" Condition="'$(UsingNETSdkDefaults)' == 'true'" />
<Import Project="$(MSBuildThisFileDirectory)Microsoft.NET.CrossGen.targets" />
Expand Down
2 changes: 1 addition & 1 deletion src/Tests/EndToEnd.Tests/GivenDotNetUsesMSBuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public GivenDotNetUsesMSBuild(ITestOutputHelper log) : base(log)
{
}

[RequiresMSBuildVersionFact("16.8.0")]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void ItCanNewRestoreBuildRunCleanMSBuildProject()
{
string projectDirectory = _testAssetsManager.CreateTestDirectory().Path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static void AssemblyNamesDoNotMatch()
Assert.Equal(expected, differences.First(), CompatDifferenceComparer.Default);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void AssemblyCultureMustBeCompatible()
{
// setting different assembly culture for net6.0
Expand All @@ -54,7 +54,7 @@ public void AssemblyCultureMustBeCompatible()
TestAsset testAsset = _testAssetsManager.CreateTestProject(testProject);
BuildCommand buildCommand = new(testAsset);
buildCommand.Execute().Should().Pass();

string leftDllPath = Path.Combine(buildCommand.GetOutputDirectory("netstandard2.0").FullName, "Project.dll");
string rightDllPath = Path.Combine(buildCommand.GetOutputDirectory("net6.0").FullName, "Project.dll");
IAssemblySymbol leftSymbols = new AssemblySymbolLoader().LoadAssembly(leftDllPath);
Expand All @@ -68,7 +68,7 @@ public void AssemblyCultureMustBeCompatible()
Assert.Equal(expected, differences.First(), CompatDifferenceComparer.Default);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void AssemblyVersionMustBeCompatible()
{
// setting different assembly culture for netstanard2.0
Expand Down Expand Up @@ -102,7 +102,7 @@ public void AssemblyVersionMustBeCompatible()
Assert.Equal(expected, differences.First(), CompatDifferenceComparer.Default);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void AssemblyVersionMustBeStrictlyCompatible()
{
// setting different assembly culture for netstanard2.0
Expand Down Expand Up @@ -144,7 +144,7 @@ public void AssemblyVersionMustBeStrictlyCompatible()
Assert.Equal(expected, differences.First(), CompatDifferenceComparer.Default);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void AssemblyKeyTokenMustBeCompatible()
{
var testAsset = _testAssetsManager
Expand All @@ -165,7 +165,7 @@ public void AssemblyKeyTokenMustBeCompatible()
Assert.Empty(differences);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void LeftAssemblyKeyTokenNull()
{
var testAsset = _testAssetsManager
Expand All @@ -185,7 +185,7 @@ public void LeftAssemblyKeyTokenNull()
Assert.Empty(differences);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void RightAssemblyKeyTokenNull()
{
var testAsset = _testAssetsManager
Expand All @@ -208,7 +208,7 @@ public void RightAssemblyKeyTokenNull()
Assert.Equal(expected, differences.First(), CompatDifferenceComparer.Default);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void RetargetableFlagSet()
{
var testAsset = _testAssetsManager
Expand All @@ -230,7 +230,7 @@ public void RetargetableFlagSet()
Assert.Empty(differences);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void LeftAssemblyKeyTokenNullStrictMode()
{
var testAsset = _testAssetsManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public ValidatePackageTargetTests(ITestOutputHelper log) : base(log)
{
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void InvalidPackage()
{
var testAsset = _testAssetsManager
Expand All @@ -30,7 +30,7 @@ public void InvalidPackage()
Assert.Contains("error CP0002: Member 'PackageValidationTestProject.Program.SomeAPINotIn6_0()' exists on lib/netstandard2.0/PackageValidationTestProject.dll but not on lib/net6.0/PackageValidationTestProject.dll", result.StdOut);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void ValidatePackageTargetRunsSuccessfully()
{
var testAsset = _testAssetsManager
Expand All @@ -44,7 +44,7 @@ public void ValidatePackageTargetRunsSuccessfully()
Assert.Equal(0, result.ExitCode);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void ValidatePackageTargetRunsSuccessfullyWithBaselineCheck()
{
var testAsset = _testAssetsManager
Expand All @@ -64,7 +64,7 @@ public void ValidatePackageTargetRunsSuccessfullyWithBaselineCheck()
Assert.Equal(0, result.ExitCode);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void ValidatePackageTargetRunsSuccessfullyWithBaselineVersion()
{
var testAsset = _testAssetsManager
Expand All @@ -83,7 +83,7 @@ public void ValidatePackageTargetRunsSuccessfullyWithBaselineVersion()
Assert.Equal(0, result.ExitCode);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void ValidatePackageTargetFailsWithBaselineVersion()
{
var testAsset = _testAssetsManager
Expand All @@ -104,7 +104,7 @@ public void ValidatePackageTargetFailsWithBaselineVersion()
Assert.Contains("error CP0002: Member 'PackageValidationTestProject.Program.SomeApiNotInLatestVersion()' exists on [Baseline] lib/netstandard2.0/PackageValidationTestProject.dll but not on lib/netstandard2.0/PackageValidationTestProject.dll", result.StdOut);
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void ValidatePackageTargetWithIncorrectBaselinePackagePath()
{
var testAsset = _testAssetsManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static void Main(string [] args)
}
}";

[WindowsOnlyTheory]
[WindowsOnlyRequiresMSBuildVersionTheory("17.0.0.32901")]
[InlineData("net6.0", true)]
[InlineData("netcoreapp3.1", false)]
public void Multiple_frameworks_are_written_to_runtimeconfig_when_there_are_multiple_FrameworkReferences(string targetFramework, bool shouldIncludeBaseFramework)
Expand Down Expand Up @@ -149,7 +149,7 @@ public void ForceGenerateRuntimeConfigurationFiles_works_even_on_netFramework_tf
Assert.True(File.Exists(runtimeConfigFile), $"Expected to generate runtime config file '{runtimeConfigFile}'");
}

[WindowsOnlyFact]
[WindowsOnlyRequiresMSBuildVersionFact("17.0.0.32901")]
public void DuplicateFrameworksAreNotWrittenToRuntimeConfigWhenThereAreDifferentProfiles()
{
var testProject = new TestProject()
Expand Down Expand Up @@ -494,7 +494,7 @@ public void BuildFailsIfRuntimePackHasNotBeenRestored()
TargetFrameworks = "netcoreapp3.0",
IsExe = true,
};

// Use a test-specific packages folder
testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packages";

Expand Down Expand Up @@ -676,7 +676,7 @@ public void TargetingPackVersionCanBeSpecifiedOnFrameworkReference()
// Transitive framework references require NuGet support, which isn't currently
// in the full Framework MSBuild we use in CI, so only run these tests for
// core MSBuild for now
[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void TransitiveFrameworkReferenceFromProjectReference()
{
var testProject = new TestProject()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ public void It_marks_package_references_as_externally_resolved(bool? markAsExter
}
}

[Theory]
[RequiresMSBuildVersionTheory("17.0.0.32901")]
[InlineData("net5.0", false, false, false, null)] // Pre .NET 6.0 predefinedCulturesOnly is not supported.
[InlineData("net5.0", true, false, false, null)] // Pre .NET 6.0 predefinedCulturesOnly is not supported.
[InlineData("net5.0", false, true, true, "True")] // Pre .NET 6.0 predefinedCulturesOnly can end up in the runtime config file but with no effect at runtime.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public void WhenTargetPlatformMinVersionIsSetForWindowsItIsUsedForTheSupportedOS
.And.HaveStdOutContaining(SupportedOSPlatformAttribute("Windows10.0.18362.0"));
}

[WindowsOnlyFact]
[WindowsOnlyRequiresMSBuildVersionFact("17.0.0.32901")]
public void WhenTargetingWindowsSupportedOSVersionPropertySetsTargetPlatformMinVersion()
{
TestProject testProject = SetUpProject("net6.0-windows10.0.19041");
Expand All @@ -190,7 +190,7 @@ public void WhenTargetingWindowsSupportedOSVersionPropertySetsTargetPlatformMinV

getValuesCommand.GetValues()
.Should()
.BeEquivalentTo("10.0.18362.0");
.BeEquivalentTo("10.0.18362.0");
}

[WindowsOnlyFact]
Expand Down Expand Up @@ -266,7 +266,7 @@ private static string TargetPlatformAttribute(string targetPlatform)

return expected;
}

private static string SupportedOSPlatformAttribute(string supportedOSPlatform)
{
string expected = string.IsNullOrEmpty(supportedOSPlatform) ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ public void It_stops_generating_runtimeconfig_dev_json_after_net6(string targetF
File.Exists(runtimeconfigFile).Should().Be(shouldGenerateRuntimeConfigDevJson);
}

[Theory]
[RequiresMSBuildVersionTheory("17.0.0.32901")]
[InlineData("netcoreapp2.0")]
[InlineData("netcoreapp3.0")]
[InlineData("net5.0")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public void It_imports_when_targeting_dotnet_3()
getValuesCommand.GetValues().ShouldBeEquivalentTo(new[] { "true" });
}

[WindowsOnlyFact]
[WindowsOnlyRequiresMSBuildVersionFact("17.0.0.32901", Skip = "https://github.com/dotnet/sdk/issues/18800")]
public void It_builds_successfully_when_targeting_net_framework()
{
var testDirectory = _testAssetsManager.CreateTestDirectory().Path;
Expand Down Expand Up @@ -241,7 +241,7 @@ public void It_fails_if_target_platform_identifier_and_version_are_invalid()
.NotHaveStdOutContaining("NETSDK1140");
}

[WindowsOnlyFact]
[WindowsOnlyRequiresMSBuildVersionFact("17.0.0.32901")]
public void UseWPFCanBeSetInDirectoryBuildTargets()
{
var testDir = _testAssetsManager.CreateTestDirectory();
Expand Down Expand Up @@ -367,7 +367,7 @@ public void WindowsWorkloadIsInstalledForNet5AndUp(string targetFramework, bool
getValueCommand.GetValues()
.Should()
.Contain("windows");
}
}
else
{
getValueCommand.GetValues()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ public void It_includes_internals_visible_to()
AssemblyInfo.Get(assemblyPath)["InternalsVisibleToAttribute"].Should().Be("Tests");
}

[Theory]
[RequiresMSBuildVersionTheory("17.0.0.32901")]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, false)]
Expand Down Expand Up @@ -429,7 +429,7 @@ public void TestPreviewFeatures(bool enablePreviewFeatures, bool generateRequire
}
}

[Fact]
[RequiresMSBuildVersionFact("17.0.0.32901")]
public void It_doesnt_includes_requires_preview_features()
{
var testAsset = _testAssetsManager
Expand Down
Loading

0 comments on commit 8594395

Please sign in to comment.